Get Selected Item in JavaScript Form

Somehow JavaScript mixed objects with attributes. For instance:

document.formName.listBoxName[i].selected

formName and listBoxName are references to two bojects. It might be good, but it just crosses the boundary of reference to object and the attributes. Don't know if this the the reason, to get selected item's value in form seems not easy. Google search shows there are so many people ask the question and not get right answers. Here is the easier way:

; function getValueOfSelectedItem(obj)
{ ; var val = obj.options[obj.selectedIndex].value
; if (val) (use val here)
}

To call this function, put the caller on onchange in HTML codes:

onChange="getValueOfSelectedItem(this)"

The beauty of it is there is no mixture of reference and attribute and you can pass anything of it without worry of crossing boundary issue.


http://www.java2s.com/Code/JavaScriptReference/Javascript-Properties/selectedIndexExample.htm

No comments:

Post a Comment

Labels