Select box onchange event with only one <option> - javascript

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.

Related

How to populate a textbox with value of country dropdown each time user makes a selection?

I have an issue related to an HTML page. Hoping that someone could help resolve it -
I have an HTML page with a Country select and a Text Box. The value attribute of the Option tag contains the Country codes. When the User selects a country, its respective country code should get populated in the Text Box.
This will happen each time the User changes the country.
All of the data is present in the page itself, and no server calls are made to fetch the data.
Could this be done using the delegate method? Can I also use Ajax in this case?
Any help would be very much appreciated.
Many thanks in advance!!
By using Jquery
Try this
HTML
<select id="c_code">
<option value="IN">India</option>
<option value="US">USA</option>
</select>
<input id="code" type="text">
Script
$('#c_code').on('change',function(){
$('#code').val($(this).val());
});
DEMO
You simply need to bind the logic to the change event of select
Here is the html code
<select id="ddl">
<option value="001">India</option>
<option value="002">USA</option>
</select>
<input type="text" id="txt" />
Here is the jQuery
$('#ddl').change(function(){
$('#txt').val($('#ddl').val());
});
Here is the demo

Give textfield a value based on option selected from drop down

What I'm trying to do is give my textfield a value based an an option is select form my drop down. For example: I have 2 fields, a drop down and a textfield. I select Facebook from the dropdown and the value "http://www.facebook.com/" appears in my textfield. How can I achieve this effect? I know that I have to call a function onchange of the drop down but that's pretty much everything I know. Remember that I'm not trying to copy the exact selected value from the dropdown to the textfield here.
example markup
<select>
<option value="http://www.facebook.com">Facebook</option>
<option value="http://www.twitter.com">Twitter</option>
</select>
<input type="text" />
jquery
$('select').change(function() {
$('input[type="text"]').val(this.value);
});
Here's a fiddle
In response to your comment, there are a number of ways to do it (a switch statement, if/elseif statement etc), the easiest would probably be to create an object mapping the text to the corresponding url:
var urlFromText = {
'Facebook' : 'http://www.facebook.com/',
'Twitter' : 'http://www.twitter.com/'
};
Then, in your change handler, you can simply use:
$('input[type="text"]').val(urlFromText[$('option:selected', this).text()]);
Here's an example
HTML
<select id="network">
<option value="http://www.facebook.com">Facebook</div>
<option value="http://www.twitter.com">Twitter</div>
</select>
<input id="network-txt"/>
Jquery
$("#network").change(function(){
$("#network-txt").val($(this).val());
});
Working Example http://jsfiddle.net/nVEEE/

Changing two select options value via javascript

there are two option controls in a website:
<select class="operator" name="operator" id="operator">
<option value="0">Entekhab Operator</option>
<option value="1">Irancell</option>
<option value="2">Talia</option>
<option value="3">HamraheAval</option>
</select>
<select class="card" name="chargeCard" id="chargeCard">
<option value="0">Entekhab Sharj</option>
</select>
When a user changes the first one by clicking on that (and selecting an option), the second one will also change...as you see in the above code, the second option has no value and will get some values after clicking on the first one
My problem is that I have to change them via javascipt in my android program
I tried with the following:
document.getElementById("operator").value=2
and this way i changed the first one.
But the second one does not change and dose not get values! What should I do for the second option to change as well?
maybe i didnt explain my question very well. i changed the value of the option but i needed something like stimulating the change event.
this code solved my problem:
$('#operator').trigger('change');

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 object value

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.

Categories