Содержание
I am trying to set the value of a with javascript here is my code
But when I run this I dont see Tuesday as selected, Monday is selected as it is just the first value in the , how can I set the value of the
7 Answers 7
Try this (After your last statement, set the value in the select)
As you should select the value after adding the options to the select .
You have to set select.value after you added the options. Otherwise there is no option to select from.
Untested but should work.
Because that’s what I would do in HTML, wouldn’t you?
I have the following HTML
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
15 Answers 15
You can use this function:
If you are using jQuery you can also do this:
This will select the with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector , you can select an element based on a CSS selector:
Using the more established approach with document.getElementById() , that will, as the name of the function implies, let you select an element based on its id :
You can run the below code snipped to see these methods and the jQuery function in action:
This question already has an answer here:
and I have a variable named temp in my JavaScript:
Now I want to set the value of the option that is equal to temp as default value for my select.
How can I do it?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
6 Answers 6
You first need to add values to your select options and for easy targetting give the select itself an id .
Let’s make option b the default:
Now you can change the default selected value with JavaScript like this:
You should define the attributes of option like selected="selected"
Simplay you can place HTML select attribute to option a like shown below
Define the attributes like selected="selected"