0
$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");

How do I write above piece of code in javascript?

5
  • What browsers do you need to target? Commented Jun 23, 2017 at 6:16
  • please explain your question with relevent codes and explanation Commented Jun 23, 2017 at 6:17
  • var yourelement = document.getElementsByName('salesrep'); yourelement.value = "valueToSelect;"; Commented Jun 23, 2017 at 6:19
  • @manikantgautam Please read the question again (: Commented Jun 23, 2017 at 6:20
  • @Reshma I am having a input text field[name="iTextField"] .In onchange event of the particular field i am calling a function in which i need to make an option of drop down get selected Commented Jun 23, 2017 at 6:22

2 Answers 2

2

You can use querySelector as below

document.querySelector('select[name^="salesrep"] option[value="Bruce Jones"]').selected = true;
<select name="salesrep">
<option value="Bruce Jones">Bruce Jones</option>
<option value="John Doo">John Doo</option>
<option value="John Lee">John Lee</option>
<option value="Jane Doo">Jane Doo</option>
</select>

Sign up to request clarification or add additional context in comments.

2 Comments

can i make option text get selected like
document.querySelector('select[name^="salesrep"] option[text="Bruce Jones"]').selected = true;
0

JavaScript:

var mySelect = document.getElementById('salesrep');
for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == 'Bruce Jones') {
        mySelect.selectedIndex = j;
        break;
    }
}
<select name="salesrep" id="salesrep">
<option value="Bruce Jones">Bruce Jones</option>
<option value="John Doo">John Doo</option>
<option value="John Lee">John Lee</option>
<option value="Jane Doo">Jane Doo</option>
</select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.