Reputation: 135
I have a form at which 2 fields are generated by one drop down menu. Now the problem is I have generated one field and trying to get two fields, in first field price is shown and in second tag product_id is shown. My script is just showing price but not id. Due to lack of knowledge I am stuck. I just need help from someone.
JavaScript:
function setOptions(chosen) {
var selbox = document.myform.opttwo;
selbox.options.length = 0;
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); }
selbox.options[selbox.options.length] = new Option('100 Directory Submission', '$9.99', '1');
selbox.options[selbox.options.length] = new Option('200 Directory Submission', '$19.99', '2');
selbox.options[selbox.options.length] = new Option('300 Directory Submission','$29.99', '3');
}
document.myform.amount.value="";
document.myform.hidden.value="";
}
HTML:
<select name="opttwo" size="1" onchange="this.form.amount.value=this.value;">
<option value=" " selected="selected">Select any option of the above first</option>
</select>
Amount Payable:<input type="text" readonly="readonly" name="amount" />
Product id:<input type="text" name="hidden" readonly="readonly" />
Upvotes: 0
Views: 176
Reputation: 47172
First off there are some obvious problems with your code such as closed and unclosed braces.
One example of that is on this line:
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); }
Edit: this is not no longer the case.
Secondly, the Options object that you're trying to create does not have the "id" property that you're trying to get unfortunately.
So your code
selbox.options[selbox.options.length] = new Option('100 Directory Submission', '$9.99', '1');
is not getting '1' as its id.
The constructor is
new Option([text], [value], [defaultSelected], [selected])
You can however get the index of an element by doing this in your onchange handler:
this.form.hidden.value=this.selectedIndex;
Thirdly, if you wanna continue on the path of using script in your onchange tags, which generally is discouraged, you have to set the value of the hidden input as well.
Like this:
onchange="this.form.amount.value=this.value; this.form.hidden.value=this.value;"
Note: this line above will give you the wrong value, just saying, but you get the gist of it.
I made a fiddle for you to toy around in and to see how it's done.
Some API documentation is always in order I believe:
Update: In order to set the id dynamically on every Option you have to loop over the elements in the select list like this:
for (var i=0; i<selbox.length; i++){
selbox.options[i].setAttribute('id', 'hello'+i);
}
Then in the line where you set in your onchange()
you add this
this.form.hidden.value=this[selectedIndex].id;
Now your input should show, when you select an option, "hello0", "hello1", "hello2", "hello3".
Also, I updated the fiddle for you.
Upvotes: 1