Val vs Text in jQuery

I got the impression that "val ()" should be used for the input element, and "text ()" should be used for all other elements.

However, when I do the following:

$("<input/>").val("test")

I get

[<input>​]

and when I go to the following:

$("<input/>").text("test")

I get

[<input>​test​</input>​]

The last is what I am looking for.

Is there anything else when using jquery to create an element that I am missing? My actual situation is much more complicated than this, but I simplified it for the purposes of this question.

+3
source share
3 answers

.val () for the HTML attribute "value"

.text () for innerHTML (similar to .html ())

+4
source

.text() ( p, div ..) .val() (, , ..),

.text() input elements.

.

: javascript, :

HTML:

<input type='text' id='myinput' />

Javascript:

:

document.getElementById("myinput").value = 'Your value here'

var myinputval = document.getElementById("myinput").value
0

If you pass in the value .text()or .val(), it will send this data to the corresponding element. If you are trying to target this:

<input type="text" val="the value" />

Try using this in jQuery:

var $testRes = $('input').attr('val');

console.log($testRes); // the value
0
source

All Articles