I am trying to access each individual element, ie option, defined for a list box (or drop down box).
For some reason the code I am using is not working. It is given below—
$(jQuery('input', $(this).parent('form'))).each(function() {
element= $(this);
textmsg=" Element # " + (count+1) + "...Name of this input element = " + $(this).attr('name') + " multiplechoice-" + $(this).attr('multiple');
textmsg= textmsg + "...Also, for this element, the value is " + $(this).val() + " and type =" + $(this).attr('type');
alert (textmsg);
var listofoptions = new Array();
type=$(this).attr('type');
if(type=="select")//this means we have to go through the children for this select element, to obtain the values for each option
{
var elements= $('option', this);
for(var i=0; i<elements.length; i++)
{
// add $(this).val() to your list
alert("Value of this option=" + $elements[i].val());
});
}
});
How do I make the above code work? Or can you suggest an alternative way of accessing each option value? Thanks…
In order to select all inputs you would need to use the
:inputselector and not just$('input')as this will select inputs by tag name and the select will be excluded.So do
Also, since there’s no
typeattribute on aselectelement. You could use .is() instead to check if it’s a select.Edit: for the if statement i would do the following
Here’s a fiddle