Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery option select not working in chrome

I'm trying to auto select the option in select by jquery after fetching the option value that needs to be selected. However it is not working in Chrome. Its working in firefox and IE 9. Why is it so ? function fill is the one that fills in the values. (function res, only resets the values filled by function fill and is not important for this question)

function fill(thisValue) {
    $('#inputString').val(thisValue);
    $.post("get.php?op=category", {queryString: ""+thisValue+""}, function(data){
            if(data.length >0) {
                $("#mymenu option[value='"+data+"']").attr('selected', 'selected');
                $('#mymenu').attr("disabled","disabled");
            }
        });
    $.post("get.php?op=name", {queryString: ""+thisValue+""}, function(data){
            if(data.length >0) {
                $('#nameString').val(data);
                $('#nameString').attr("disabled","disabled");
            }
        });
    $.post("get.php?op=author", {queryString: ""+thisValue+""}, function(data){
            if(data.length >0) {
                $('#authorString').val(data);
                $('#authorString').attr("disabled","disabled");                 
            }
        });
    $.post("get.php?op=publisher", {queryString: ""+thisValue+""}, function(data){
            if(data.length >0) {
                $('#publisherString').val(data);
                $('#publisherString').attr("disabled","disabled");
            }
        });


    setTimeout("$('#suggestions').hide();", 200);
}

function res(inputString) {
$('#publisherString').attr("disabled", false);
$('#publisherString').val('');
$('#nameString').attr("disabled",false);
$('#nameString').val('');
$('#authorString').attr("disabled",false);
$('#authorString').val('');
$('#mymenu').attr("disabled",false);
$('#mymenu option').attr('selected', false);
}
like image 723
Nuv Avatar asked Mar 04 '13 05:03

Nuv


1 Answers

You can use val() to set the value of a select element.

Change

$("#mymenu option[value='"+data+"']").attr('selected', 'selected');

to

$("#mymenu").val(data);

Demo Fiddle

Another solution is to use prop(). The attr() method is used to set the attribute value of the element not to set the property.

$('#mymenu option[value="5"]').prop('selected', true)

You can read more about attr vs prop, as well as the jQuery 1.6 release note

Demo Fiddle

like image 122
Arun P Johny Avatar answered Oct 13 '22 18:10

Arun P Johny