Reputation:
<select id="weight-unit" class="styled" name="weight-unit" data-placeholder="kg ">
<option value="" selected></option>
<option class="kg" value="kg" id="kg" name="kg" >kg</option>
<option class="lbs" value="lbs" id="lbs">lbs</option>
</select>
When a user clicks a button I want that drop down menu should automatically display lbs without actually going to the drop down menu and selecting it.
Upvotes: 0
Views: 89
Reputation: 824
We can use jQuery to set the value of your select
tag when a particular button is pressed. Let's say you have some button
with id
"enterLbs":
<button id="enterLbs">Set to lbs.</button>
With jQuery, we can select this button and bind an event handler to the button's click
event. In this case, when the button is clicked, we want to set the value of the select
(with id
"weight-unit") to "lbs":
$("#enterLbs").click(function() {
$("#weight-unit").val("lbs");
});
So, when the button
with id
"enterLbs" is pressed, the select
with id
"weight-unit" has its value set to lbs
. Consider the following working example: http://jsfiddle.net/u2p9npt5/.
If you do not want to use jQuery, you can use JavaScript's document.getElementById
function to add an event handler to the button
with id
"enterLbs```:
var button = document.getElementById("enterLbs");
var select = document.getElementById("weight-unit");
button.addEventListener("click", function() {
select.value = "lbs";
});
Consider this jsfiddle if you would rather not use jQuery: http://jsfiddle.net/c51gsp1L/.
Upvotes: 0
Reputation: 150040
Perhaps a little something like this:
document.getElementById("idOfYourButton").addEventListener("click", function() {
document.getElementById("weight-unit").value = "lbs";
}, false);
That is, use document.getElementById()
to get a reference to your button (assuming it has an id - if not, give it one), then use the addEventListener()
method to add a click handler that sets the .value
property of the select element.
Note that the above code would need to be in a script element after the button, and/or in a document ready/onload handler.
Demo: http://jsfiddle.net/pan4ftn9/
Upvotes: 3