abhishek
abhishek

Reputation: 149

how to get the indexvalue for given option in select box

I have a select box with various options which are loaded dynamically . I am writing code to iterate through the code and make it the default option if the text value is a particular value example for in this case 8065992445. Not getting a way to do it.

$("#locationselect > option").each(function() {
          if(this.text==8065992445)

        });

Upvotes: 0

Views: 41

Answers (2)

Mohammad
Mohammad

Reputation: 21499

If you want to check value of option use $(selector).val() to getting value of option.

$("option").each(function(){
    if ($(this).val() == "3")
        $(this).text($(this).text() + " - Changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
    <option value="5">Option 5</option>
</select>

And if you want to check text of option use $(selector).text() to getting text of option.

$("option").each(function(){
    if ($(this).text() == "Option 2")
        $(this).text($(this).text() + " - Changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
    <option value="5">Option 5</option>
</select>

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85633

Use val method to get the value of select option:

$("#locationselect > option").each(function() {
    if($(this).val()==8065992445){
      //do your task...
    }
});

Upvotes: 2

Related Questions