Garth Baker Garth Baker - 7 months ago 48
Javascript Question

Set input attribute based on slected option

Hi guys so I'm a bit lost at the moment. I'm trying to set the SKU of an input field based on the selected option.
I've tried the code below. but it doesn't seem to be working.
Please try provide as much insight as you can.

Here's the html

<select id="track_type_selected">
<option value="0">51 Track 3m</option>
<option value="1">64 Track 3m</option>
<option value="2">103 Track 3m</option>
<input type="number" name="required_tracks_name" id="required_tracks_id" class="sku" sku="" disabled="">

And here's the javascript.

if ('#track_type_selected' == 1) {
}else if('#track_type_selected' == 2) {
}else if ('#track_type_selected' == 3) {

Basically is the option is equal to a set value. i need the sku to be set to the set value.

Answer Source

Before i go on with the solution, i can understand that you have basic to zero knowledge about JavaScript.. make sure you understand how JavaScript syntax works then continue.

To get the selected option use this code:

var e = document.getElementById("track_type_selected"); var selectedIndex = e.options[e.selectedIndex].value;

selectedIndex variable should now include the current selected index. (1,2,3.. etc)

So you can do this:
if(selectedIndex==1){/* some code */}

Now, to get sku attribute (since you confirmed that you use jquery) you can do this:

Make sure you check .attr usage and edit it to your needs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download