I have selected option:
<form>
<select name="sel" id="sel" onchange="run()">
<option selected disabled>Wybierz...</option>
<optgroup id="user" value="user" label="user">
<option value="1">michal</option>
<option value="2">mateusz</option>
</optgroup>
<optgroup id="warehouse" value="warehouse" label="warehouse">
<option value="1">kosz</option>
<option value="2">zaginione</option>
</optgroup>
</select>
</form>
<input type="text" name="copy" id="copy"></input>
And script to add text in input text:
function run() {
if(document.getElementById("user").label == 'user'){
document.getElementById("copy").value = "user";
} else if (document.getElementById("warehouse").label == 'warehouse') {
document.getElementById("copy").value = "warehouse";
}
}
When user selected option with first optgroup
("user") then in input text script add name "user". When user selected records from second optgroup
, then script change text in input text to "warehouse". But in my script, nothing is added to the input text.
demo
in jsfiddle you have put function inside onload function so it is undifined to outer scope.outherwise you will get user
for both groups
document.getElementById("user").label == 'user'
is always true.so it is not going to else block.you should get label value of selected group and compare it.
var lable=event.target.options[event.target.selectedIndex].parentNode.label // get lable value of clicked group
if(lable == 'user'){
document.getElementById("copy").value = "user";
} else if (lable == 'warehouse') {
document.getElementById("copy").value = "warehouse";
}