简体   繁体   中英

matching text of option tag using filter function

I have two select box. on change event of first select box, i'm adding that text into second select box. but i don't want to add duplicate record.for this i'm using filter function,(if any text that has already added then i don't want to add again) but it's not working as i want.

html

<select id="ddlCategory">
           <option value="0">Select Category</option>
           <option value="1">Category 1</option>
           <option value="2">Category 2</option>
           <option value="3">Category 3</option>
 </select>

<select multiple="multiple" id="my-select" name="my-select[]" class="multiDrop"> </select>

<select multiple="multiple" id="your-select" name="my-selectyour[]" class="multiDrop">

myJs:

  $('#my-select').change(function () {
        var getValue = $(this).find('option:selected').val();
        var getText = $(this).find('option:selected').text();
        var getCategory = $('#ddlCategory').find('option:selected').text();
        if ($('#your-select > option').hasClass(getCategory)) {
            $("#your-select > option").filter(function (index) {
                if ($(this).html() == getText) {
                    return;
                }
                $('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
            });


        } else {
            $('#your-select').html('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
        }
    });

Jsfiddle

Here you go... my edited fiddle: http://jsfiddle.net/stoz1m6v/2/

This way it does not duplicate the entries in myselect... you had some checking of class/category there which I removed, because I found it incorrectly done, however I could not comprehend how exactly you wanted to check the category...

and the script goes like this... I have changed only the change handler of the my-select:

    $('#my-select').change(function () {
        var getValue = $(this).find('option:selected').val();
        var getText = $(this).find('option:selected').text();
        var getCategory = $('#ddlCategory').find('option:selected').text();
        if ($("#your-select > option").filter(function (index) {
            return $(this).html() == getText; }).length ==0) { 
            $('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText +        '</option>');
        }

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM