Filter and make a drop down menu item selected. What is the wrong with the code?

$(document).ready(function () {

    // get value when text box value changed

    $('#barcode').change(function(){

        var barcodeval = $('#barcode').val();

        // use that value to filer the relevant drop down menu item

        $("#Item1 option[value$='barcodeval']").attr("selected","selected");

    }); 

}); 

the recommended way to select an option with jquery is element.prop('selected',true)

call the .change() method on the object after you’ve set the property.

1 Like

I tried using various methods to utilize this option. But when it was used code didn’t work properly.

[att$=val]

Represents an element with the att attribute whose value ends with the suffix “val”. If “val” is the empty string then the selector does not represent anything.

How to make the item selected which ends its value as 1234567890.

JS code

$('#Item1').val().change();

val —> ending with 1234567890 —>

<option value='/0/1000.00/002/000003054/1234567890'>TestItem</option>

Why is this not working?

      var b = '1234567890';
      $('#Item1').val(option[value$="b"]).change();

This is also not working.

      var b = '1234567890';
      $('#Item1').val("#Item1 option[value$=b]").change();

because that’s not how string concatenation in Javascript works.

invalid. (val expects string; undefined variable ‘option’)

Invalid (option[value$=b] is not a valid selector.)

You can make it valid using actual string concatenation, with appropriate wrapping of selector value.

     var b = '1234567890';
      $('#Item1').val("#Item1 option[value$='"+b+"']").change();

Tho it should be pointed out that using a selector in .val is not valid jquery, either. So you’ll need to pull the value from the element with that selector, and insert it into that function.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.