Wednesday, December 9, 2009

Getting Value of Element from a Select Form

Apple-II-Shipping
This gets the value of the selected text and displays it in an alert box. This can be a little confusing (only a little), so some details follow below.

First the HTML code for this:
 
<script type="text/javascript">
function displayLanguage() {
 var selectFromForm = document.forms.languageChoice.
elements["language"];
 var myValue = selectFromForm.options[selectFromForm.
selectedIndex].value;
  alert('Your native language is \"'+ myValue +"\"");
  return true;
}
</script>

<form action="" name="languageChoice">
<select getFieldId="23" name="language">
   <option selected="selected">Select language<
/option>
   <option>English</option>
   <option>French</option>
   <option>Spanish</option>
   <option>German</option>
   <option>Italian</option>
</select>
<input name="executeButton" onclick="displayLanguage()"
 type="button" value="Language" />
</form>

Keep in mind that to understand this, first focus on the form block of the HTML which gathers the data that will be used by the JavaScript block.

With that said, when a choice (English,French ..whatever) is selected and the button is clicked, 'onclick' sends a call for the 'displayLanguage' function to the corresponding script.

The variable var selectFromForm is assigned a value of document.forms.languageChoice.elements["language"] . This gives it the value of the element named 'language' of the form named 'languageChoice' of the current web document.

Next, the variable 'myValue' gets the value (text) of the index number 'selectedIndex' of 'selectFromForm' and then, finally displays it in an alert box.

Look below and this should be fairly clear.

Note: You may have noticed above, that the logic of the variable assigned reads from right to left.

What is shown on the page:


 
Digg 'Learning How to Write JavaScript Code'!


Please leave me a comment on this site.

For a look at using color with HTML go to: http://editing-web-color-html.blogspot.com/

No comments:

Post a Comment