cicakman
cicakman

Reputation: 1990

Select option selected via jquery not working on chrome only

I cant figure it out why it doesn't work on chrome only whereas it working on firefox and ie.

HTML CODE:

<select name="goyale" id="goyale">
<option value="0">Select</option>
<option value="1">Fish</option>
<option value="2">Chicken</option>
<option value="3">Meat</option>
</select>

jQuery CODE:

$(document).ready(function () {
    $("select#goyale option[value='<?php echo $row['goyale']; ?>']").attr("selected", "selected");
});

Whenever i inspect element on chrome, it displays the option as <option value="3" selected="selected">Meat</option> but the option doesn't appear selected on naked eye display.

Thanks.

Upvotes: 1

Views: 10060

Answers (5)

Fabio Nolasco
Fabio Nolasco

Reputation: 7492

Try to use the Prop method. I tested it on Safari, Opera, Firefox, and Chrome, and it worked fine.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test - Option selected - jQuery</title>
</head>
<body>
    <form>
      <select>
        <option value="11">aa</option>
        <option value="22">bb</option>
        <option value="33">cc</option>
        <option value="44">dd</option>
      </select>
    </form>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $(function(){
            $('select option:last').prop('selected','selected');
        });
    </script>
</body>
</html>

You can find more information here:

http://jquery.com/upgrade-guide/1.9/#attr-versus-prop-

Upvotes: 4

Robin Michael Poothurai
Robin Michael Poothurai

Reputation: 5664

i Hope this will solve your problem

$("#goyale").val("<?php echo $row['goyale']; ?>");

Upvotes: 1

cicakman
cicakman

Reputation: 1990

The problem lies within jQuery 1.6, once i update to jQuery 1.7, the problem gone and the select function is working as intended. Thank you and i have should have updated to latest version before posting here.

Upvotes: 1

pravin
pravin

Reputation: 231

ok do this , give id="goyale" in tag ,because may be chrome not support selector # id selector for "name" attrib, else try option[name=goyale] selector of jquery

Upvotes: 0

Purag
Purag

Reputation: 17061

You're looking for any select element with the id of goyale. In your HTML, goyale is the name attribute of your element.

Uses this instead:

$(function(){
    $("select[name='goyale']").etc();
});

Also, use prop() to add the selected attribute to option elements:

$("option[value='<?php echo $row['goyale']; ?>']").prop("selected",true);

More about prop() here.

Upvotes: 1

Related Questions