Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save wchristian/21fa8387c05a6aed755e to your computer and use it in GitHub Desktop.

Select an option

Save wchristian/21fa8387c05a6aed755e to your computer and use it in GitHub Desktop.

Revisions

  1. wchristian renamed this gist Dec 18, 2014. 1 changed file with 0 additions and 0 deletions.
  2. @hartez hartez created this gist Jun 25, 2012.
    41 changes: 41 additions & 0 deletions jquery-validation-engine_with_select2
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    <script type="text/javascript">
    // This is a workaround for using jquery-validation-engine with select2 for 'required' validation
    // Since the _required validator for jquery-validation-engine uses .val() to see
    // if there's anything in the input, we can hijack .val() for the container created by select2\
    // and redirect it to the value of the hidden element

    // jquery-validation-engine throws an error if the thing we're validating doesn't have an id
    // so we'll put one on the container created by select2 (that way, the positioning of the prompts
    // will be correct)
    $('#mySelector').select2('container').attr('id', 'mySelectorValidate');

    // Mostly lifted from http://stackoverflow.com/questions/6731153/what-are-jquery-valhooks
    $.fn.setTypeForHook = function () {
    this.each(function () {
    this.type = 'mySelector';
    });
    return this;
    };

    $('#mySelector').select2('container').setTypeForHook();

    // With the 'type' set, we can add a valhook to redirect .val() for the container
    // to .val() from the hidden input
    // select2 sets up its own 'val' method, so we'll use that in this case
    $.valHooks['mySelector'] = {
    get: function (el) {
    return $('#mySelector').select2("val");
    },
    set: function (el, val) {
    $('#mySelector').select2("val", val);
    }
    };

    </script>

    <div class="mySelectorContainer" id="tcuSelection">

    <!-- select2 will copy the validate[required] class to the container it creates -->
    <input type="hidden" id="mySelector" name="TCUId" class="mySelector validate[required]"/>

    </div>