"JQuery". html (),. Text () and. Val () Overview and Usage--2015-08-11

Source: Internet
Author: User


How to use the. html (),. Text (), and. Val () Three methods in jquery to read, modify the HTML structure of an element, the text content of an element, and the value of a FORM element


This section focuses on how to use the. html (),. Text (), and. Val () Three methods in jquery to read, modify the HTML structure of the element, the text content of the element, and the value of the form element. jquery gives us a variety of ways to manipulate the HTML structure of elements and the textual content of elements, for example, you can add new elements to the inside, around, front, or back of an existing element, or replace another element with one element; You can also read or modify the content or structure of an element. Sometimes we tend to be fuzzy and don't know whether to add content to an element or add an element, for example, we need to add the element's content to an existing element effectively.



Here we share with you how to add, remove and replace elements, jquery gives us three ways to manipulate the structure and content of elements:


    1. . HTML (): Read and modify the HTML content of an element, details. html ();
    2. . Text (): Read and modify the text content of an element, details. text ();
    3. . Val (): Reads and modifies the value of a form element, details. val ().


As you will see, these methods allow you to easily read or modify the original contents of an element or read and modify any HTML values, or you can easily read or modify the Value field values in the form.



HTML structure of the manipulation element ——. HTML ()



The. html () method in jquery allows you to read and modify the contents of an element's HTML, which is mainly used in three ways:. html (),. html (htmlstring),. html (function (index,html) {...}), Let's look at how they're used in turn.



1. Read HTML structure of an element ——. HTML ()



Grammar:




return value:string



Description



The. HTML () method is used to get the HTML content of any element, and if the selector selects more than one element at the same time, it can only read the HTML content of the first element. In addition, this method is not valid for XML side files.



To read the HTML content of an element, you first select the element and then call the. HTML () method in jquery, for example, in the following code, we select the P element in Div.demo and then read the HTML content of the element through. html (), such as:



HTML Code:


The code is as follows:
<div class= "Demo" >
<p> This is a paragraph element that contains a LINK element <a href= "#" >W3CPLUS</a></p>
</div>



jQuery Code


The code is as follows:
$ (document). Ready (function () {
Alert ("The HTML structure of the P element in Div.demo:" +$ ("Div.demo P"). html ());
});



Results






The above code pops up an alert box that shows the elements within the original HTML markup, as shown in. Above is div.demo only one P element, if there are multiple? There will be something happening, we do not fang in the look of one back:



HTML Markup


The code is as follows:
<div class= "Demo" >
<p> I was the first P element in Div.demo: <a href= "#" > I was inside the first P </a></p>
<p> This is a paragraph element that contains a LINK element <a href= "#" >W3CPLUS</a></p>
</div>




JQuery Code


The code is as follows:
$ (document). Ready (function () {
Alert ("The HTML structure of the P element in Div.demo:" +$ ("Div.demo P"). html ());
});



Effect






From the above we can clearly see that the same section of the jquery code, the results are different. This proves again that if you invoke the. HTML () method of multiple selected elements, it reads only the first element, in other words: If the selector matches more than one element, only the HTML content of the first matching element is fetched.



2. Modify the HTML content of an element ——. HTML (htmlstring)



Grammar:




return Value:jquery Object



Description



Re-sets the HTML content of the first matching element, and any content of those elements is completely superseded by the new content. Based on the above example, the HTML content of the original paragraph is completely replaced:



HTML Markup


The code is as follows:
<div class= "Demo" >
<p> I was the first P element in Div.demo: <a href= "#" > I was inside the first P </a></p>
<p> This is a paragraph element that contains a LINK element <a href= "#" >W3CPLUS</a></p>
</div>



JQuery Code:


The code is as follows:
$ (document). Ready (function () {
$ ("Div.demo p"). html ('

});



Effect:






We learned from the above effect that if you use the. html (Htmlstrong) method to match on more than one element, then the HTML content of multiple matching elements will be replaced and replaced with the same HTML structure as specified in the. html (htmlstring) method. Htmlstring "structure. In other words, if you use the. html (htmlstring) method to select multiple elements, the HTML content of the selected elements will be replaced by the "htmlstring" in the. html (htmlstring) method. as shown.



3. Use a callback function to replace the HTML content of an element



Grammar:




return Value:jquery Object



Description



Used to return a function that sets HTML content. Receives the index position of the element and the element's old HTML as an argument.



Using a callback function to replace the HTML content of an element, the following two conditions must be met:


    1. The index value position of the current element (index value is calculated starting from 0);
    2. The old HTML content of the current element.


The return value of the function is then used as an alternative to HTML. This is convenient, if you want to replace the contents of multiple elements, and do not want to change the same content as above, but instead of replacing the same contents, then we can use this method, depending on the element's own location or the existing content (or both) to replace multiple elements into different HTML content. Let's look at an example:



HTML Markup


The code is as follows:
<div class= "Demo" >
<p><a href= "#" > I in the first p inside </a></p>
<p><a href= "#" >W3CPLUS</a></p>
</div>



JQuery Code:


The code is as follows:
$ (document). Ready (function () {
$ ("Div.demo p"). html (function (index,oldhtml) {
Return "I am the paragraph" + (Index+1) + ":" + oldhtml;
});
});



Effect:





The plain text content of the manipulation element ——. text ()


The preceding. HTML () method allows you to read or modify the HTML content of an element-including the HTML tag of an element-while the. Text () method in jquery is simply an operation on the plain text of an element. He and the. html () method contain three ways to use:



1, read the text content ——. ()



Grammar:




return Value: returns a string;



Description



Gets the text content of each element in the collection of matching elements combined, including their descendants: the text () and the. html () methods are different, and the. Text () method can be used in both XML and HTML documents: text () The result of a method is the text that is combined by all the text content that the matching element contains (because different browsers differ from the HTML parser, the text wrapping and other spaces that are returned may vary.) )



Using the. text () and. html () methods are almost identical, such as:



HTML Markup


The code is as follows:
<div class= "Demo" >
<p><a href= "#" >W3CPLUS</a></p>
</div>



JQuery Code:


The code is as follows:
$ (document). Ready (function () {
Alert (". Text () reads the contents:" + $ ("Div.demo p"). text ());
});



Effect:






From the above effect we know: using the. Text () method, we only read the plain text content of the element, including his descendant elements, and the HTML tag in this element (including the HTML tag of its descendant elements) is stripped out, leaving only the textual content.



The. Text () and. HTML () methods can select multiple elements at the same time, but with a different point:. html () matches multiple elements, only the first of the matching elements is read, and the. Text () method differs, when he matches multiple elements, it reads the contents of multiple elements at the same time, such as:



HTML Markup


The code is as follows:
<div class= "Demo" >
<p><a href= "#" >W3CPLUS</a></p>
<p> I am paragraph two: <a href= "#" >W3CPLUS</a></p>
</div>



JQuery Code


The code is as follows:
$ (document). Ready (function () {
Alert (". Text () Method:" + $ ("Div.demo p"). text ());
Alert (". HTML () Method:" + $ ("Div.demo p"). html ());
});



Effect:






2, replace the text content ——. text (textstring)



Grammar




return Value:jquery Object



Description



The. Text (TextString) method and the. html (htmlstring) method are all the same to replace the contents of an element, and their different types are:. The HTML (htmlstring) method replaces the original content with the HTML tag as a new HTML tag, while the. Text (TextString) converts the HTML tag to plain text instead of the old content of the element. In other words, if you include a label for HTML in the. Text (TextString) method, this method replaces < with <,> instead of >. We replace. html () with. Text () on the basis of the previous. HTML (htmlstring) instance.



HTML Markup


The code is as follows:
<div class= "Demo" >
<p><a href= "#" >W3CPLUS</a></p>
<p> I am paragraph two: <a href= "#" >W3CPLUS</a></p>
</div>



JQuery Code


The code is as follows:
$ (document). Ready (function () {
$ ("Div.demo p"). Text ('

});



Effect:






It can be learned that the. Text method replaces the old content of an element with an HTML tag as plain text content, which is completely different from the. html (htmlstring) method, and you can compare it with the previous. html (htmlstring) textstring. But they have one thing in common: If multiple elements are matched, using. Text (TextString) replaces the contents of the matched element with the same content.



3. Use a callback function to replace the text content of an element



The. Text () method, like the. html () method, also uses a callback function to dynamically replace the contents of multiple elements without replacing multiple elements with the same content as the. Text (TextString).



Grammar




return value:jquery pair Image



Description



Used to return a function that sets the text content. Receives the index position of the element and the element's old text value as an argument. To replace the contents of an element with a callback function, the following two conditions must be met:


    1. The index value position of the current element (index value is calculated starting from 0);
    2. The old text content of the current element.


The return value of the function is then used as the plain text content of the replacement element. This is convenient, if you want to replace the contents of multiple elements, and do not want to change the same content as the above, but instead of replacing the same contents, then we can use this method, depending on the element's own location or existing content (or both) to replace multiple elements of a different waking text content. Let's look at an example:



HTML Markup


The code is as follows:
<div class= "Demo" >
<p><a href= "#" > I in the first p inside </a></p>
<p><a href= "#" >W3CPLUS</a></p>
</div>



JQuery Code:


The code is as follows:
$ (document). Ready (function () {
$ ("Div.demo p"). Text (function (index,oldtext) {
Return (index+1) + "." + OldText;
});
});



Effect





Action form field value value ——. val ()


The. html () and. Text () that are described earlier cannot be manipulated on the input element, so let's look at A. Val () method. This method, like the. Text () method, can be read to modify the value of the form field "value".



1. Get the form element value ——. val ()



Grammar




return Value: A string or array will be returned



Description



The. Val () method is primarily used to get the value of a form element. As for the "<select multiple=" multiple ">" element, the. Val () method returns an array containing each selected option, for the next selection box "< select>" and the check box, radio ([type=] CheckBox "],[type=" Radio "]) you can use the": Selected "and": checked "selectors to get the values. Let's take a look at a few examples:



HTML Markup


The code is as follows:
<div id= "Colorradio" >
<input type= "Radio" name= "Color" id= "Rd1" value= "Red"/>red
<input type= "Radio" name= "Color" id= "Rd2" value= "Yello"/>yello
<input type= "Radio" name= "Color" id= "Rd3" value= "Blue"/>blue
</div>
<div id= "Sizecheck" >
<input type= "checkbox" name= "Size" id= "Ch1" value= "Ten PT"/>10 PT
<input type= "checkbox" name= "Size" id= "CH2" Value= "PT"/>12 PT
<input type= "checkbox" name= "Size" id= "CH3" Value= "PT"/>14 PT
</div>
<input type= "button" id= "submitbtn" value= "Get value"/>



JQuery Code


The code is as follows:
$ (document). Ready (function () {
$ (' #submitBtn '). Click (function () {
Alert ($ (' #colorRadio Input:radio '). Val ());
Alert ($ (' #sizeCheck Input:checkbox '). Val ());
});
});



Effect






. val () returns the first of the matching elements in the collection, sometimes you want to return the value of the selected radio or CheckBox, if at this point you only use the. Val () method, then the return will be the first value, with no relationship selected, as shown, if you want to return the value of your choice, You need to do something like this to get the selected value:

The code is as follows:

$ (document). Ready (function () {
$ (' #submitBtn '). Click (function () {
Alert ($ (' input:radio[name=color]:checked '). Val ());
Alert ($ (' input:checkbox[name=size]:checked '). Val ());
});
});



At this point, the Radio (radio) will return the value in your selection, but the checkbox is not, if you select multiple checkboxes at the same time. Val () returns only the value in the first selection, and if no value is selected, the "undefined" is added at this time. Just now, when there are multiple checks for "checkbox", the rebate will only be the first value, and if you need to return it all, we need to traverse the checkbox with each ().


The code is as follows:
$ (document). Ready (function () {
$ (' #submitBtn '). Click (function () {
Alert ($ (' input:radio[name=color]:checked '). Val ());
$ (' input:checkbox[name=size]:checked '). each (function () {
Alert (This). Val ());
});
});
});



In addition, Val () also has two cases in "select" when the . Val () method is applied on the <select> element, the selected value is returned, and the other is when the. Val () method is applied to the <select multiple= " Multiple "on the > element, the returned will be an array containing each selected option. See below for an example.



HTML Markup


The code is as follows:
<form action= "" method= "POST" >
<select id= "Dropdown" >
<option>Red</option>
<option>Yellow</option>
<option>Blue</option>
</select>
<select id= "ListBox" multiple= "multiple" >
<option>Red</option>
<option>Yellow</option>
<option>Blue</option>
</select>
<input type= "button" id= "Getselectvalue" value= "Get value"/>
</form>



JQuery Code


The code is as follows:
$ ("#getSelectValue"). Click (function () {
Alert ($ ("#dropdown"). Val ());
var colors = $ ("#listbox"). Val ();
for (var key in colors) {
Alert (Colors[key]);
}
});



2. Replace the value of the form element ——. Val (value)



Grammar




return value jquery object



Description



This method is commonly used to set the values of form fields, and for "<select multiple=" multiple ">" Elements, multiple options can be selected by an array: Val (value) can change the value of the selected element at the same time. And the values are the same, such as:

The code is as follows:

$ ("input"). Val ("Test");



The above code will eventually replace all Inupt value values with "test", which we generally do not use in normal applications. Val (value) is often applied to the focus and blur of input[type= "text", such as:



HTML Markup


The code is as follows:
<input type= "text" id= "TextBox" value= "hello,jquery!"/>



JQuery Code


The code is as follows:
$ ("Input:text"). focus (function () {
var $inputTextVal = $ (this). Val ();
if ($inputTextVal = = This.defaultvalue) {
$ (this). Val ("");
}
});
$ ("Input:text"). blur (function () {
var $inputTextVal = $ (this). Val ();
if ($inputTextVal = = "") {
$ (this). Val (This.defaultvalue);
}
});



3. Use a callback function to replace the value of the form field "value"



The preceding. Val (value) can change the value of the selected form element to the same one, so we often need to set it to a different value, and we need to use this method to set the value by a function. This function passes two parameters, the current element's value and its current value.



Grammar




return value jquery object



Description



Using the return value of this function to set the value of each matched INPUT element, let's look at a checkbox and an instance on radio:



HTML Markup


The code is as follows:
<form action= "" >
<div id= "Colorradio" >
<input type= "Radio" name= "Color" id= "Rd1" value= "Red"/><span id= "Color1" >Red</span>
<input type= "Radio" name= "Color" id= "Rd2" value= "Yellow"/><span id= "Color2" >Yellow</span>
<input type= "Radio" name= "Color" id= "Rd3" value= "Blue"/><span id= "Color3" >Blue</span>
</div>
<div id= "Sizecheck" >
<input type= "checkbox" name= "Size" id= "Ch1" value= "Ten pt"/><span id= "size1" >10 pt</span>
<input type= "checkbox" name= "Size" id= "CH2" Value= "PT"/><span id= "Size2" >12 pt</span>
<input type= "checkbox" name= "Size" id= "CH3" Value= "PT"/><span id= "Size3" >14 pt</span>
</div>
<input type= "text" id= "Txtbox" disabled= "disabled"/>
<input type= "button" id= "SetValue" value= "Set value"/>
</form>



JQuery Code


The code is as follows:
$ (document). Ready (function () {
$ ("Input:radio[name=color]"). Val (function (index,oldval) {
Return "color-" + (index+1) + ":" + oldval;
});

$ ("input:checkbox[name=size]"). Val (function (index,oldval) {
Return "size-" + (index+1) + ":" + oldval;
});
$ ("#setValue"). Click (function () {
var $msg = $ ("input:radio[name=color]:checked"). Val () + ",";
$ ("input:checkbox[name=size]:checked"). each (function () {
$msg + = $ (this). Val () + ",";
});
$ ("#txtBox"). Val ($msg);
});
});



For the multi-select Next box, we can change this:



HTML Markup


The code is as follows:
<select id= "Dropdown" >
<option>Red</option>
<option>Yellow</option>
<option>Blue</option>
</select>
<select id= "ListBox" multiple= "multiple" >
<option>Red</option>
<option>Yellow</option>
<option>Blue</option>
</select>



JQuery Cody


The code is as follows:
$ (document). Ready (function () {
$ (' #dropdown '). Val (' Yellow ');
$ (' #listbox '). Val ([' Red ', ' Blue ']);
});



The specific use of. Val () is described above, so what can we do with the. Val () method?


    1. You can use. val () to read and modify <select> selected list items. As shown in the example above, of course these values are already present in the list item;
    2. You can use. val () to read <select multiple= "multiple" > Selected values, if you select more than one option value, at this point. Val () will return an option array, but you cannot use. val () to set him multiple values;
    3. You can use. val () to read the values of the radio and checkboxes, or you can match the checked= "checked" property to read the selected values, but for a checkbox to traverse with each (), you can only read the first selected value;
    4. You can use function to dynamically change the value of multiple elements in a form.


This section focuses on the use of the. html (),. Text (), and. Val () Three methods in jquery, and finally summarizes these three methods:


    1. . HTML () HTML tags for reading and modifying elements
    2. . Text () to read or modify the plain text content of an element
    3. . Val () is used to read or modify the value of the form element.


The comparison of the functions of the three methods


      1. . HTML (),. Text (),. Val () Three methods are used to read the contents of the selected element; HTML () is used to read the HTML content of the element (including its HTML tags),. Text () is used to read the plain text content of the element, including its descendant elements,. Val () Is the "value" value that is used to read form elements. The. and. Text () methods cannot be used on form elements, whereas. val () can only be used on form elements; the. html () method only reads the first element when used on more than one element, and the. Val () method is the same as. html () If it is applied on more than one element. Only the value of the first FORM element can be read, but. Text () is different from theirs, and if. Text () is applied on more than one element, the textual content of all the selected elements is read.
      2. . HTML (htmlstring),. Text (TextString), and. Val (value) Three methods are used to replace the contents of the selected element, and if three methods are applied on more than one element at the same time, the contents of all the selected elements will be replaced.
      3. . HTML (),. Text (),. Val () can use the return value of the callback function to dynamically change the contents of multiple elements.


"JQuery". html (),. Text () and. Val () Overview and Usage--2015-08-11


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.