Question

I have the following HTML with me containing various multiselect boxes -

 <p>
 <label>Main Category</label>
 <select id="mainSelect" name="super_category" multiple>
    <option value="CatA">CatA</option>
    <option value="CatB">CatB</option>
 </select>
 </p>
 <p>
 <label>SubCategoryA</label>
 <select class="multiselectbox" name="super_subcategory_CatA" multiple>
     <option value="SubcatA1">SubcatA1</option>
     <option value="SubcatA2">SubcatA2</option>
 </select>
 </p>
<p>
<label>SubCategoryB</label>
<select class="multiselectbox" name="contact_subcategory_CatB" multiple>
     <option value="SubcatB1">SubcatB1</option>
     <option value="SubcatB2">SubcatB2</option>
</select>
</p>

I am trying to create dynamic jquery code where in if i select any option from subcategory_X multiselect field that same sub category should get selected in super_category multiselect

Similarly when I deselect any option subcategory_X from super_category multiselect, any/all options from the particular subcategory_X s multiselect should get deselected.

Trying to do this using Jquery but I'm a newbie to it. Was thinking of doing this on onchange event such that if any option is selected/deselected from any multi-select, it's corresponding "category" either gets selected in the "super_category" multiselect or all values get deselected from "subcategory"'s own multiselect.

Hope I haven't confused any one. Any help on this would be greatly appreciated.

Thanks in advance.

EDIT: JSfiddle link http://jsfiddle.net/M53JX/

Was it helpful?

Solution

Try this

$(document).ready(function () {
    $('#mainSelect').on('change', function () {
        $("select[name^=contact_subcategory] option").prop("selected", "");
        var name = $(this).val(); alert(name);
        $(name).each(function() {
            $("select[name=contact_subcategory_" +this  + "] option").prop("selected", "selected"); 
        })

    });
});

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top