Thứ Tư, 14 tháng 10, 2009

Lấy giá trị của các đối tượng trong form (How to get the value of a form element using JavaScript)

 

Please refer article: how to get JavaScript form object for information on getting a reference to the form object.

In this article we demonstrate the use of Javascript for accessing the values of form elements. Later, we will demonstrate all the concepts using a real world example.

Getting a text input element and it's value

To obtain a reference to a text input element, we can use a construct like this:

oText = oForm.elements["text_element_name"]; OR
oText = oForm.elements[index];

In the code above, "index" is the position of the element in the 0-based elements array, and oForm is the form object reference obtained using the document.forms collection:

oForm = document.forms[index];

To get the value of the text input element, we can use the value property of the text input object:

text_val = oText.value;

As an example, if we have the following text input element:

<input type="text" name="name" id="txt_name" size="30" maxlength="70">

We can access the value of the element like this:

name = oForm.elements["name"].value;

Getting a textarea element and it's value

The syntax for obtaining a reference to a textarea element is very similar:

oTextarea = oForm.elements["textarea_element_name"];

To get the value entered by the user in the textarea field:

textarea_val = oTextarea.value;

As an example, if we have a textarea element like this:

<textarea name="address" id="txta_address" rows="3" cols="35"></textarea>

We can access the value entered by the user in this way:

address = oForm.elements["address"].value;

Getting a hidden element and it's value

The syntax for obtaining a reference to a hidden input element:

oHidden = oForm.elements["hidden_element_name"];

To get the value of this element, we use the familiar code construct:

hidden_val = oHidden.value;

As an example, if we have a hidden input element in the form defined like this:

<input type="hidden" name="number_of_skillsets" value="1">

We can get the hidden input element's value like this:

number_of_skillsets = oForm.elements["number_of_skillsets"].value;

Getting a select-one element and the selected option

As before, we can obtain a reference to this type of element using its name:

oSelectOne = oForm.elements["select_one_element_name"];

To get the index of the selected option in the javascript options array of the select element, we can use the selectedIndex property of the select element object:

index = oSelectOne.selectedIndex;

We can now use this index to determine the value of the selected option:

var selected_option_value = oSelectOne.options[index].value;

If we needed to get the text corresponding to the selected option, we would need to use the textproperty of the option element, instead of the value property:

var selected_option_text = oSelectOne.options[index].text;

Let us say we need to find out the country selected by the user from a select-one list:

<select size="1" id="slt_country" name="country">
<option value=""> - Select - </option>
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
...
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>

The Javascript code that can be used to get the user-selected country:

var selected_index = oForm.elements["country"].selectedIndex;
if(selected_index > 0) {
var selected_option_value = oForm.elements["country"].options[selected_index].value;
var selected_option_text = oForm.elements["country"].options[selected_index].text;
} else {
alert('Please select a country from the drop down list');
}

Getting a select-multiple element and all the selected options

If a select element has the additional attribute 'multiple', it allows users to select more than one option. Have a look at this HTML fragment:

<select name="job_category" id='slt_job_category' size="4" multiple='multiple'>
<option value="">- Select (Max 3) -</option>
<option value='1'>Software Development</option>
<option value='2'>Sales & Marketing</option>
<option value='3'>Customer Support & Communications</option>
<option value='4'>Advertising</option>
<option value='5'>Public Relations and Event Management</option>
...
<option value='22'>Oil & Gas</option>
<option value='23'>Construction</option>
<option value='24'>Other</option>
</select>

We can write a Javascript function to get all the user-selected options:

function getSelectedOptions(oList) {
var sdValues = [];
for(var i = 1; i < oList.options.length; i++) {
if(oList.options[i].selected == true) {
sdValues.push(oList.options[i].value);
}
}
return sdValues;
}

To use this function, we must first obtain a reference to the select-multiple object:

oList = oForm.elements["job_category"];

We now pass this object reference to the getSelectedOptions function above. In this function, we iterate over all the options in the options array. Whenever an option is selected, the option object'sselected property will be true. So, in the function we use this condition to get the indices of all the options selected, and then push the values of all these options onto the array sdValues which is returned by the function. We can use this generic function to capture the values of selected options for any select-multi element in a form.

Getting a radio element and it's checked value

Radio buttons in a form can be grouped together using the same name attribute, such that, if one of them is checked, all the others are automatically un-checked. Let us look at an example:

<input type="radio" name="work_abroad" value="y">Yes
<input type="radio" name="work_abroad" value="n">No

In order to retrieve the value of the checked radio button, we can write a simple javascript function:

function getRadioCheckedValue(radio_name) {
var oRadio = document.forms[0].elements[radio_name];
for(var i = 0; i < oRadio.length; i++) {
if(oRadio[i].checked) {
return oRadio[i].value;
}
}
return '';
}

The code is self-explanatory. We obtain a reference to the group of radio buttons using the name of the group, and then iterate over all the radio button objects to test which one of them is checked.

Getting a checkbox element, it's value and determining whether it is checked or not

A checkbox in a form has only two states (checked or un-checked) and is independent of the state of other checkboxes in the form, unlike radio buttons which can be grouped together under a common name. Let us look at the HTML code showing two checkboxes:

<input type="checkbox" name="email_alerts" id="chk_email_alerts" value="ON" checked>Email me matching jobs everyday
<input type="checkbox" name="recruiter_contact" id="chl_recruiter_contact" value="ON">Enable Recruiters to directly contact me

In order to access these checkboxes, their values, and their states, we can use the following javascript function:

function testCheckbox(oCheckbox) {
var checkbox_val = oCheckbox.value;
if(oCheckbox.checked == true) {
alert("Checkbox with name = " + oCheckbox.name + " and value =" + checkbox_val + " is checked");
} else {
alert("Checkbox with name = " + oCheckbox.name + " and value =" + checkbox_val + " is not checked");
}
}

We can then use this function in the following way:

oCheckBox1 = oForm.elements["email_alerts"];
oCheckBox2 = oForm.elements["recruiter_contact"];
testCheckbox(oCheckBox1);
testCheckbox(oCheckBox2);

Example

In order to demonstrate the concepts, let us look at an example form. Please fill out the form completely, so that we can discuss certain features.

Some observations:

  1. The textarea field which requires you to provide information about acquiring work permit / visa gets disabled if you choose the option labeled 'No' for the field labeled 'Willing to work abroad ?', and gets enabled, if you then choose the option labeled 'Yes'. This is done before the form is submitted, and so we cannot use the radio button's values in the onClick event handler for the form's submit button to provide this functionality. Instead, we need to write an onClick event handler for each option. First have a look at the HTML:
    <label for="work_abroad">Willing to work abroad ? </label>
    <input type="radio" name="work_abroad" value="y" onClick="enableElement(this.form.work_permit);">Yes
    <input type="radio" name="work_abroad" value="n" onClick="disableElement(this.form.work_permit);">No
    <label for="work_permit">Information about acquiring work permit / visa: </label><textarea name="work_permit" rows="3" cols="35"></textarea>

    Writing these functions is very simple:
    function disableElement(obj) {
    obj.value = ' - N.A. - ';
    obj.disabled = true;
    }
    function enableElement(obj) {
    obj.value = '';
    obj.disabled = false;
    }
  2. In the demo, you must have seen how skills are added one at a time to the skillset list, and there is also a provision for removing items added to the list. In order to implement this, we need to write a couple of Javascript functions:
    function addOption(oList, optionName, optionValue) {
    var oOption = document.createElement("option");
    oOption.appendChild(document.createTextNode(optionName));
    oOption.setAttribute("value", optionValue);
    oList.appendChild(oOption);
    }
    function removeOption(oList, index) {
    oList.remove(index);
    }

    In Javascript we can create elements dynamically using the createElement method of thedocument object. So to create an option, we simply pass the argument "option" to this method, being that it is the name of the element we want to create (please don't confuse this with the name attribute of an element - which is different). To set the name of the optionelement that is displayed to the user, we use the method appendChild to create a child node. This is because in the DOM tree, the displayed text for an option element is a child of theoption element. However, to set the value attribute, we can simply use the setAttribute method of the option element object, because the value attribute is not a child of the option element, but simply it's attribute. Finally, we append this newly created option element to the list as a child element itself.
    Removing an option from a list is very simple. If we know the index of the option in the list, we can simply use the remove method of the list object to remove the option in question.

The rest of the functionality is quite typical and has already been explained in this article, and you can download the code to learn more.

Related:

Không có nhận xét nào: