Select object value - javascript

I just saw the following:
http://www.w3schools.com/jsref/prop_option_value.asp
And wonder if there's something wrong with selectObject.value. Why not a simple approach:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function displayResult(){
alert(document.getElementById("mySelect").value);
}
</script>
</head>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
<button type="button" onclick="displayResult()">
Display value of selected fruit
</button>
</body>
</html>
It seems to be working with no problem.
Thanks in advance!
Mike

Your method, document.getElementById("mySelect").value is returning the value of the select object - which sets itsself to the value of the currently selected option. The way w3Schools is doing it is finding the actual option tag, then you're getting the value of the option tag. So, as long as you are accessing the currently selected option tag, they return the exact same thing. However, the w3schools way allows you to actually set the value of the option tag instead of changing which option is selected when setting the value property (although that's probably not what you want).
Example:
​<select id='select'>
<option value=1>one</option>
<option value=2>two</option>
​</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
x=document.getElementById("mySelect").selectedIndex;
So, document.getElementById('select').value; returns the value of the select element.
And document.getElementsByTagName("option")[x].value​; returns the value of the selected option element.
Meaning that document.getElementById('select').value​=2​​​​ changes which option is selected, while document.getElementsByTagName("option")[x].value​=2 changes the value of the selected option element.
TLDR: When getting the value there is no difference, when setting the value there is.

Related

Wizard with Javascript

I wabt to create a wizard for this form in a such way to give options of the second input based on the option of the first input
<form method="post" action="result.php">
<select>
<option value="jean">jean</option>
<option value="t-shirt">t-shirt</option>
</select>
<select>
// if jean
<option value="black">Black</option>
<option value="blue">Blue</option>
// if t-shirt
<option value="yellow">Yellow</option>
<option value="green">Green</option>
</select>
<button type="submit">See products</button>
</form>
For example if the user choose t-shirt, it will show him available colors of that item
Something like this is probably what you're looking for:
function updateColors(product) {
document.getElementById("color").innerHTML = {
"jean": `<option value="black">Black</option>
<option value="blue">Blue</option>`,
"t-shirt": `<option value="yellow">Yellow</option>
<option value="green">Green</option>`
}[product];
}
window.onload = ()=>{updateColors("jean");}
<form method="post" action="result.php">
<select onchange="updateColors(this.value)">
<option value="jean" selected>jean</option>
<option value="t-shirt">t-shirt</option>
</select>
<select id="color"></select>
<button type="submit">See products</button>
</form>
The function updateColors takes a value, product, which is the value of the first selection box. It uses this to choose which colours to show; and then updates the HTML of that box.
We call updateColors using the onchange event of the first select box. This event is fired whenever the user picks an item; so that the change happens immediately after. From this; I pass this.value - in this context, this refers to the first selection box, and value refers to the value attribute of the selected <option> tag.
I have given the second selection box an id, color, so that we can easily reference it and change its contents.
document.getElementById("color") references the second selection box; so we can change its properties.
The .innerHTML property is used to change the HTML of a given DOM node (element on the page). By setting it, then we can change that element's HTML contents.
Then; I use a dictionary (known as a map in other languages). This is a data structure that maps keys to values. Here, jean is a key, and then the HTML for the colors jeans come in is the value. Hence; we can get that HTML given the key. Likewise, t-shirt is another key; which has a different value.
[product] is used to get the value for the given key. So if we pass in jean, it gives us back (as a string) the HTML value we set as the key. Then; that is set as the HTML code for the second selection box via innerHTML.
window.onload = ()=>{updateColors("jean");} calls this function automatically when the page finishes loading. This is to ensure that the form makes sense before the user fills it out; as jean is selected by default so it makes sense to set the default content of the second selection box to be the colors for jeans.

Change a Select Option value with no id/class

There's this website that I want to change how they display their dropdown menu.
http://i.stack.imgur.com/Wu718.jpg
I wanted to make it so that the default value is "Items for Sale", instead of "Forum Topics"
Here's their source code.
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
Since I don't really care about how it looks, I just want to change the value="topics" to value="s" even without changing the texts.
I've read some tutorials, but they mostly use IDs and Classes as a selector, in this case, how do I target this Select from many other in their website and change the value.
You can use:
$('select[name=sec]').val('s');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
I think this is what you're describing in the comments below:
var dropdown = $('select[name=sec]');
// change the s option to items
dropdown.find('option[value=s]').attr('value', 'items');
// change the topics option to s
dropdown.find('option[value=topics]').attr('value', 's');
// change the dropdown's value to s
// (first option should continue to be selected because its value is now s)
dropdown.val('s');
// (this is for demo purposes only)
dropdown.after($("<div>").text("New HTML is: " + dropdown[0].outerHTML));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You can use the name or any other attribute.
for css
select[name="sec"]
or jquery
$('select[name="sec"]').
DEMO inspect element from your browser to see the changes
you can select a select dropdown list with select[name=sec] and select the first option with option:first
$('select[name=sec] option:first').val('s');
and if you need to change any of options just use .eq()
$('select[name=sec] option').eq(0).val('s'); // eq(0) for the first option element . eq(1) for the second option element ...
If you want to make selected an other option use this code:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
This script removes the default selection (the first option) and select the option which has "s" value. For the Demo:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You have to find this element in the DOM. For this you should find the first parent container element of the which has ID or CLASS attribute. From that element you can create a search for the element what you want by using the .find() method.
If there're more element which has name attribute with "sec" value you should build a chain of find which separate that you want. For that you can use these function templates:
$(#CONTAINER_ID).find(.SUBCONTAINER_CLASS).find(ELEMENT_TYPE);
$(#CONTAINER_ID).find(SUBCONTAINER_TYPE).find(OTHER_SUBCONTAINER_TYPE:eq(X));

select multiple in HTML5

I'm new to HTML5 and I'm trying to test the <select> with the attribute multiple in forms on Google Chrome. I encounter two problems.
Firstly, the options list changes in an ugly rectangle
Whereas before it was "normal":
My second problem is that, it seems that when i want to get the values of the select (by clicking on the button and in the code using javascript), only one is given...
Here is my code:
<!DOCTYPE html>
<html>
<body>
How do you travel?
<form method="get" id=myForm" onsubmit="done();">
<select name="transport" multiple> <optgroup label="Ecological">
<option value="Feet" selected>By Foot</option>
<option value="Bike">By Bike</option> </optgroup>
<optgroup label="Non-ecological">
<option value="public transports">With public transports</option> <option value="motorbike">By motorbike</option> <option value="car">By car</option>
</optgroup> </select>
<button onclick="bdone();">button</button>
<script>
function bdone(){
var mesOptions=document.getElementsByTagName('select')[0];
alert(mesOptions.value);
}
</script>
</body>
</html>
Thank you for reading me!
The Styling Issue
Just a note: the multiple attribute of the select element is not specifically HTML5.
The styling is going to depend on the CSS styles that are being applied, both the user agent styles (the default browser styles), and the specific CSS on that page. Try putting it in a page by itself (or in a jsFiddle and see if you get the same styling.
The selection issue
The selectedOptions property of the select element you get will contain an array of HTMLOptionElements, all of which have the value property. See below:
jsFiddle
function bdone(){
var selectElem = document.getElementsByTagName('select')[0]
var mesOptions = selectElem.selectedOptions;
for(var a=0;a<mesOptions.length;a++) {
alert(mesOptions[a].value);
}
}

Execute some Javascript onChange using options?

I've been lurking a bit and couldn't find the answer. Basically I have a bunch of buttons that I want to turn into a drop down menu and have the code be executed onChange. But, I'm new to javascript and I am having a hard time figuring out how this would work. I somewhat got it to work, but I couldn't get it to work with more than one option. Here's what I have:
<button class="lightbutton" onclick="lightswitch(1,true);lightswitch(2,true);lightswitch(3,true);">
All lights on</button>
<button class="lightbutton" onclick="lightswitch(1,false);lightswitch(2,false);lightswitch(3,false);">
All lights off</button>
I got the lights to turn on by doing this:
<form name="functions">
<select name="jumpmenu" onChange="lightswitch(1,true);lightswitch(2,true);lightswitch(3,true);">
<option>LightFunctions</option>
<option value="*";>Light 1 On</option>
<option value="*";>Light 1 Off</option>
</select>
</form>
Now, I see why it works -- it's just telling it that whenever it changes to turn on all the lights. But how do I change the "onChange" to make it so it gets whichever option I have chosen?
I think I'm missing some JS but unsure.
I appreciate the help.
To have that select element control just the first lightswitch you can do this:
<select name="jumpmenu" onChange="lightswitch(1,this.value==='on');">
<option value="on";>Light 1 On</option>
<option value="off";>Light 1 Off</option>
</select>
That is, instead of hardcoding true as the second parameter to lightswitch() test the current value of the select element. (Note that I've changed the value attributes to something more meaningful. The expression this.value==='on' will evaluate to either true or false.)
Within the select's onChange attribute this will refer to the select element itself.
EDIT: To have the same select control multiple parameters you can add some data- attributes to the option elements to store as many extra parameters per option as needed (in this case I think you only need one extra). And I'd move the logic out of the inline attribute:
<select name="jumpmenu" onChange="jumpChange(this);">
<option value="">LightFunctions</option>
<option data-switchNo="1" value="on";>Light 1 On</option>
<option data-switchNo="1" value="off";>Light 1 Off</option>
<option data-switchNo="2" value="on";>Light 2 On</option>
<option data-switchNo="2" value="off";>Light 2 Off</option>
<option data-switchNo="3" value="on";>Light 3 On</option>
<option data-switchNo="3" value="off";>Light 3 Off</option>
</select>
function jumpChange(sel) {
if (sel.value === "") return; // do nothing if user selected first option
var whichLight = +sel.options[sel.selectedIndex].getAttribute("data-switchNo");
lightswitch(whichLight, sel.value==='on');
sel.value = ""; // reset select to display the "Light Functions" option
}
Demo: http://jsfiddle.net/N7b8j/2/
Within the jumpChange(sel) function that I added the parameter sel will be the select element (set as this from the onChange attribute). The "magic" happens on this line:
var whichLight = +sel.options[sel.selectedIndex].getAttribute("data-switchNo");
To explain that line: sel.options[sel.selectedIndex] gets a reference to the currently selected option, and .getAttribute("data-switchNo") gets that option's data- attribute. The + converts the attribute from a string to a number.

Select box onchange event with only one <option>

The onchange event works great and populates my input (textbox) just fine, but when the onchange event is applied to the drop down box with only 1 single option in it, it does not work. How can I get the onchange to fire even if, there is one or multiple items?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript">
function test(x) {
var x = document.getElementById(x).options[document.getElementById(x).selectedIndex].text
document.getElementById('output').value = x
}//end of function
</script>
</head>
<body>
<select id="drop1" onchange="test(this.id)">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
<select id="drop2" onchange="test(this.id)">
<option value="volvo">Volvo</option>
</select>
<br><br>
<input type="text" id="output">
</body>
</html>
You could add an empty option at the top of every select box, or perhaps an option that just says -Select-. Then, if necessary, alter your script to ignore the empty selection.
If there is only one item, it never will change. Try onblur instead. Or maybe onclick, depending on what you are actually trying to do.
I am answering this question in case it can help somebody in 2020. I had the same problem populating data from the database into the form where there was a single data and I was able to solve this way. In the example am gonna use jquery for illustrations.
First you have to empty the select element using .empty() function.
$('#drop2').empty();
Secondly add an empty value into the select using .append()
$('#drop2').append("<option value='0'>Select</option>");
After that now you can go ahead to add your data into the select element because they are going to be two options, one empty while the other carries the data.
Finally populate your data from server this way using ajax in success function
success:function(response){
$('#drop2').empty().append("<option value='0'>Select</option>");
response.forEach((item)=>{
$('#drop2').append("<option value='"+item[]+"'>"+item[1]</option>");
});
I have used the arrow function .forEach()
If you've come here in 2022 then this is the answer you are looking for:
The easiest solution is to simply put hidden in a 'placeholder' option tag.
<select>
<option hidden value="dontselect">Spinny wheely bois</option>
<option value="volvo">Volvo</option>
</select>
This means that there will always be 2 or more options in the select but the placeholder option does not show in the drop-down list (so won't be able to be selected). The placeholder should be the first option tag inside select just to make your life easier.
But it does mean that when you click the one actual option you'll trigger onChange as internally the select is changing value.

Categories