HTML JavaScript Dropdown selectedIndex
75,588
Solution 1
Probably just:
var a = dropdown1.selectedIndex;
if you're trying to check that the zeroth option is selected.
Either that, or give your options values in the HTML and check the values themself.
Solution 2
You need to select the value property as follows:
var a = dropdown1.options[dropdown1.selectedIndex].value;
Solution 3
this should work. Please note that 'a' is the DOM element (Option)
function chkind(){
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
var a = dropdown1.options[dropdown1.selectedIndex];
if(a.index == 0){
textbox.value = "hi";
} else if(a.index == 1) {
textbox.value = "bye";
}
}
or
function chkind(){
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
if(dropdown1.selectedIndex == 0){
textbox.value = "hi";
} else if(dropdown1.selectedIndex == 1) {
textbox.value = "bye";
}
}
Solution 4
I'd advice you to do it this way:
<head>
<title>DropDown</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.20" />
<script type="text/javascript">
function chkind(){
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
textbox.value=dropdown1.value;
}
</script>
</head>
<body>
<select onchange="chkind()" id="dropdown1"><option value='Hi'>Hi</option><option value = 'Bye'>Bye</option></select><br /><input id="textbox" type="text" />
</body>
the changes to the code:
- First of all, take a look at the select box, all the option tags now have a 'value' attribute. This tells the browser what the value the input should have when a certain option is selected. You can also use this to your advantage to set shorter values than the content of the option, for example, when you have a country selection tool, one of your options could be
<option value='US'>United Stated</option>
. - In your script, you don't have an if-statement anymore, we just set the value of the text box to the value of your select box.
Author by
yanike
Updated on July 19, 2022Comments
-
yanike almost 2 years
I'm trying to get the dropdown to change the textbox, but seem to be having issues.
<head> <title>DropDown</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="generator" content="Geany 0.20" /> <script type="text/javascript"> function chkind() { var dropdown1 = document.getElementById('dropdown1'); var textbox = document.getElementById('textbox'); var a = dropdown1.options[dropdown1.selectedIndex]; if(a == 0){ textbox.value = "hi"; } else if(a == 1) { textbox.value = "bye"; } } </script> </head> <body> <select onchange="chkind()" id="dropdown1"> <option>Hi</option> <option>Bye</option> </select><br /> <input id="textbox" type="text" /> </body>
-
yanike almost 13 yearsThis is another way I can go about it. Thanks!