Link to home
Start Free TrialLog in
Avatar of Bob-Villa
Bob-Villa

asked on

Javascript to grab Text-Label as a value from a Select Box Option

I have a select box and a hidden field.

I want to use an onchange handler to update the hidden field

<script>
function updHidden {
document.forms[0].TxtLabel=?
}
</script>
<select onchange=updHidden>
<option value=1>John Doe
<option value=2>Jane Doe
</select>
<hidden name=TxtLabel value="">

I can do the value part but this time I need the label and not sure how to get it.

Help.

Avatar of Joe Wu
Joe Wu
Flag of Australia image

something like this:
<script>
function updHidden() {
document.getElementById('txtlabel').value="Your_Value_HERE";
}
</script>
<select onchange="updHidden();">
<option value=1>John Doe</option>
<option value=2>Jane Doe</option>
</select>
<hidden name="TxtLabel" id="txtlabel" value="">

Open in new window

also (not sure if this is what you mean) if you want the hidden value to take after the value selected with the select option box, then something like this will do it.
<script>
function updHidden() {
document.getElementById('txtlabel').value=document.getElementById('select_box').options[document.getElementById('select_box').selectedIndex].value;
}
</script>
<select onchange="updHidden();" id="select_box">
<option value=1>John Doe</option>
<option value=2>Jane Doe</option>
</select>
<hidden name="TxtLabel" id="txtlabel" value="">

Open in new window

Avatar of Bob-Villa
Bob-Villa

ASKER

ok, this works but I have a conflict now. I have more than one of these select boxes on a page and after making multiple selects on multiple select boxes only one change is applies. It seems that since the value is "" that the javascript is only applying the last value when I select more than one box. i.e. I have 3 select boxes and 3 hidden inputs. I select all 3 select boxes but upon form submission only the last select box takes the change in value from "" to John Doe. The best way I can see to remedy this is to actually write the value to page somehow?

Is there a way to make this:
<hidden name="TxtLabel" id="txtlabel" value="">
look like this:
<hidden name="TxtLabel" id="txtlabel" value="John Doe">

after the select is changed using a document.write or text replace or innerhtml or something?
ASKER CERTIFIED SOLUTION
Avatar of Joe Wu
Joe Wu
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial