...

View Full Version : Referencing form components



scrappy
06-16-2009, 07:23 PM
Which is typically preferred and why?



var x = document.getElementById("mylist").value;
var x = document.getElementById("mylist").options[document.getElementById("mylist").options.selectedIndex].value;
var x = document.myform.mylist.value;


Do some work on a wider range of browsers? Or just personal preference?

Philip M
06-16-2009, 07:40 PM
These refer to select/option boxes.

They will all work in all browsers, but No.2 is long-winded and unnecessary.

var x = document.myform.mylist.value; is to be preferred if there is a form, as assigning form elements an id is really superflous.


All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

scrappy
06-16-2009, 10:07 PM
I assuming its not as simple to get the text part, as document.myform.mylist.text just gives me "undefined" whereas document.myform.mylist.options[document.myform.mylist.options.selectedIndex].text works as expected?

Philip M
06-17-2009, 07:27 AM
I assuming its not as simple to get the text part, as document.myform.mylist.text just gives me "undefined" whereas document.myform.mylist.options[document.myform.mylist.options.selectedIndex].text works as expected?

Look at these examples:-


<form name='myform'>
<select name = 'list1' id = 'list1' onchange = "rem(this)">
<option selected value=""> Choose A Fruit</option>
<option value='Mango'> Mango </option>
<option value='Apple'> Apple </option>
<option value='Orange'> Orange </option>
</form>

<script type = "text/javascript">
function rem(which) {
var val1 = document.myform.list1.value;
alert ("Value 1: " + val1);

var val2 = which.value;
alert ("Value 2: " + val2);

var val3 = document.getElementById("list1").value;
alert ("Value 3: " + val3);

var si = document.myform.list1.selectedIndex;
var txt1 = document.myform.list1[si].text;
alert ("Text 1: " + txt1);

var txt2 = document.getElementById("list1").options[si].text;
alert ("Text 2: " + txt2);

var txt3 = which.options[which.selectedIndex].text;
alert ("Text 3: " + txt3);
}

</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum