6

Hi I wrote that html codes and I want change selected item by using jQuery

<select id="slc"> 
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

I tried this but I can't change

$("#slc").val("2");

$("#slc").prop("selectedIndex", 1);
Enes
  • 301
  • 2
  • 7
  • 15

3 Answers3

4

$("#slc option[value=3]").prop('selected', 'selected');//get option with value 3 and set selected
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="slc">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Do like this

guradio
  • 15,524
  • 4
  • 36
  • 57
1

I think your first try was the right try.

 $('#slc').val('3');

It does seem to work: https://jsfiddle.net/crix/hdtndzkb/

Did you include the jquery library right? Does your code gets hit? Just try to see if it does by add a console.log() entry.

Crix
  • 86
  • 3
0

When do you fire the code? Maybe you should just wrap it in a document.ready function? I made this, and it works like a charm: https://jsfiddle.net/41bna2e9/

$(document).ready(function(){
    $("#slc").val("2");
});

Hope that it helps!

Bjørn Nyborg
  • 993
  • 7
  • 17