JQuery | Set the value of an input text field
There is a Input Element, the task is to set its value using JQuery. Here are a few examples discussed.
To understand example first few methods to know.
JQuery val() method:
This method return/set the value attribute of selected elements.
If we use this method to return value, it will return the value of the FIRST selected element.
If we use this method to set value, it will set one or more than one value attribute for set of selected elements.
Syntax:
- Return the value attribute:
$(selector).val()
- Set the value attribute:
$(selector).val(value)
- Set the value attribute using function:
$(selector).val(function(index, curValue))
Parameters:
- value:This parameter is required. It specifies the value of value attribute.
- function(index, currentValue):This parameter is optional. It specifies the function that returns the value to set.
- index: It returns the position of index of element in set.
- currentValue: It returns the current value attribute of the selected elements.
Example 1: In this example the value of the input element is set by val() method by selecting the input element from its ID.
<!DOCTYPE HTML> < html > < head > < title > JQuery | Set value of input text. </ title > < script src = </ script > </ head > < body style = "text-align: center;" > < h1 style = "color: green;" > GeeksForGeeks </ h1 > Input Box: < input id = "input" type = "text" class = "Disable" value = "" /> < br > < br > < button id = "setText" > setText </ button > < script > $("#setText").click(function(event) { $('#input').val("GeeksForGeeks"); }); </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: In this example the value of the input element is set by val() method by selecting the input element from its parent element < body > and then selecting the < input > element.
<!DOCTYPE HTML> < html > < head > < title > JQuery | Set value of input text. </ title > < script src = </ script > </ head > < body style = "text-align: center;" > < h1 style = "color: green;" > GeeksForGeeks </ h1 > Input Box: < input id = "input" type = "text" class = "Disable" value = "" /> < br > < br > < button id = "setText" > setText </ button > < script > $("#setText").click( function(event) { $('body input').val( "GeeksForGeeks"); }); </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Please Login to comment...