jquery gets textarea text value in detail

Source: Internet
Author: User

Today, using jquery to get textarea text values, you encounter such a problem:

The first error with the Val () method, followed by the text (), can be run, but the obtained value is always empty, and finally changed to Val (), can be used normally.

So: In order to get this problem clear, began a remote interpretation of the jquery source of the journey

Steps:

1. Set default values for textarea, output text () and value () values separately

2. Change the text value of the textarea, outputting text () and value () values separately

Example:

Code:

1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4     <MetaCharSet= "Utf-8">5     <title>Dom Property test</title>6 </Head>7 <Body>8     <DivID= "Js-div">9         <textareaID= "Js-textarea" >HHhH</textarea>Ten         <Buttontype= "button"ID= "Js-button">Display text</Button> One  A         <inputvalue= "Hello World"ID= "Js-input"> -     </Div> - <Scripttype= "Text/javascript"src=".. /demo-plugin/public/js/jquery.js "></Script> the <Scripttype= "Text/javascript"> -     var$textArea= $('#js-textarea'), - TextArea=$textArea. Val (); -  + Console.log ('Val:', TextArea); - Console.log ('Text:', $textArea. Text ()); +  A         $('#js-button'). Click (function () { at  - Console.log ('changed Val:', $textArea. Val ()); - Console.log ('changed text:', $textArea. Text ()); -         }); - </Script> - </Body> in </HTML>
View Code

Operation Result:

As can be seen from the above example:

1. The text () method can only get the initialized text value to textarea.

2. The Val () method not only obtains the initialized text value of the textarea, but also gets it normally when the text value changes.

Next, look at the jquery source code:

1. Text () Method:

Textfunction(text) {if(typeofText! = "Object" && Text! =NULL )            return  This. empty (). Append (( This[0] && This[0].ownerdocument | |document). createTextNode (text)); varret = ""; Jquery.each (Text|| This,function() {Jquery.each ( This. ChildNodes,function(){                if( This. nodeType! = 8) ret+= This. nodeType! = 1? This. NodeValue:jQuery.fn.text ([ This ] );        });        }); returnret; },
View Code

As can be seen from the jquery source code, the text () method is passed through the childnodes of the element, gets the nodevalue of each child node, and stitching it back into a string.

2. Val () Method:

Valfunction(value) {if(Value = =undefined) {            if( This. Length) {                varElem = This[0]; //We need to handle select boxes Special                if(Jquery.nodename (Elem, "select" ) ) {                    varindex =Elem.selectedindex, Values=[], Options=Elem.options, one= Elem.type = = "Select-one"; //Nothing is selected                    if(Index < 0 )                        return NULL; //Loop through all the selected options                     for(vari = one? index:0, max = one? Index + 1:options.length; i < Max; i++ ) {                        varoption =options[i]; if(option.selected) {//Get The specifc value for the optionValue = JQuery.browser.msie &&!option.attributes.value.specified?Option.text:option.value; //We don ' t need an array for one selects                            if(one)returnvalue; //multi-selects return an arrayValues.push (value); }                    }                                        returnvalues; //everything else, we just grab the value}Else                    return( This[0].value | | ""). Replace (/\r/g, ""); }            returnundefined; }        return  This. each (function(){            if( This. nodeType! = 1 )                return; if(Value.constructor = = Array &&/radio|checkbox/.test ( This. Type))  This. Checked = (Jquery.inarray ( This. Value, Value) >= 0 | |Jquery.inarray ( This. Name, value) >= 0); Else if(Jquery.nodename ( This, "select" ) ) {                varValues = Value.constructor = = Array?value: [value]; JQuery ("Option", This). each (function(){                     This. Selected = (Jquery.inarray ( This. Value, Values) >= 0 | |Jquery.inarray ( This. text, values) >= 0);                }); if( !values.length) This. SelectedIndex = 1; } Else                 This. Value =value;    }); },
View Code

Because it is getting the value, we just need to see if (value = = ' undefined ') {...} Branch

According to the code, it is possible to know that when an element is input, it is the Else branch, by the statement:

Return (This[0].value | | ""). Replace (/\r/g, "");

As you can see, returns the value of the element.

Said a bunch, must be very puzzled to analyze this what use, don't walk away, next more wonderful:

When the page is initialized: print $ (' #js-textarea ') and see what the console outputs:

As can be seen in the above two graphs, the value of textarea = initial value, NodeValue value is Null,text () when changing the text value of textarea The ChildNodes method returns a string with the NodeValue value of each node inside the box, which is distinguished by attention.

Then look at the contents of ChildNodes:

As you can see, textarea has a text node, the NodeValue = initial value of the text node.

Next: Change text box text value, Output $ (' #js-textarea '), witness the moment of miracles to:

First look at the value of the TextArea property:

Value change, then the NodeValue value of the text of the child node is not changed, see

As you can see: Unfortunately, the nodevalue value of the text node inside the textarea childnodes has not changed.

Why this happens, I don't know yet, but this test shows why the Val () method can take a normal value, and the text () value can cause problems.

PostScript: After research, found that the self-closing label childnodes length of 0, while the other labels have at least one text text node, as to the principle, is not very clear, and so make it clear that again, haha.

jquery gets textarea text value in detail

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.