Retrieving the value of an input is a very basic form technique and is useful in many situations. It's incredibly easy to set up and can be used for a number of applications. I commonly use this technique when submitting forms using Ajax when I need to pass over the values from all of the form fields.
1. Set up the HTML form input element that will contain the value that you would like to retrieve from the form element.
<input type="text" name="special" id="my-input" value="Very Cool!"/>
2. Select the #my-input input element and attach the val() method.
$("#my-input").val();
In order to see if the value is being retrieved, you need to set up a variable and assign it to the value of the my-input field. Then you can set up an alert to test whether this input is passing the value.
3. Add a variable called inputVal and assign as the value of this variable to the statement that you created in step 2.
var inputVal = $("#my-input").val();
If you would like to get the value of the my-input element as it changes, you can wrap the statement in a change event.
4. Wrap the previous statement in a selector statement that selects the my-input element and attaches a change event to it. This ensures that as data is entered into the field, the value of the variable changes as new data is input.
$('#my-input').change(function() {
var inputVal = $('#my-input').val();
alert(inputVal);
});
In some browsers (including Opera), when the change event is bound to a text input field, the event will only fire on blur, not immediately when the change happens.
0 comments:
Post a Comment