Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $("#select-id").prop("selectedIndex") In A Select Statement

Tags:

jquery

OK, so I've been made to understand that using this

$("#select-id").prop("selectedIndex")

in conjunction with this

$("#select-id").prop("selectedIndex", 1)

Would help obtain the results I'm looking for in getting certain elements passed back to a select statement, but I cannot find any examples of usage for this.

Lets say I have 6 elements in the select, and I have them being compared against something in another field. What would be the recommended way to set this up? I understand use a for loop, and then an if statement to iterate through the values, but I don't quite get how to use the aforementioned .prop statements.

Any help would be appreciated.

function compareAmts($FIELDSwitchText, $FIELDSwitchPull)
{
var SwitchAdv = 0;
temp = $("#FIELD_SwitchPull").val();
var SwitchComm = parseInt(temp.replace(/\,/g,''));

if($("#FIELD_SwitchText").val()!=""){
    SwitchAdv = parseInt($("#FIELD_SwitchText").val());

Basically this collects the information, I then need to use the 2 lines above in a For Loop to Get and Set the SelectedIndex, and thus the Select DropDown

like image 998
Jack Parker Avatar asked Apr 09 '26 05:04

Jack Parker


1 Answers

If you are trying to select a specific option in the select by its value, use val(). For example:

$('#select-id').val('foo');

Would select the following option:

<select id="select-id">
    <option value="">Please select</option>
    <option value="foo">Foo</option> <!-- jQuery code selects this one -->
    <option value="bar">Bar</option>
</select>

Update

If you have a specific item index you want to select, you can use eq() to get the specific option. Given the above HTML, the following would also select the foo option:

$('#select-id option').eq(1).prop('selected', true);
like image 73
Rory McCrossan Avatar answered Apr 11 '26 19:04

Rory McCrossan