3

I was under the impression that "val()" should be used for 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 the following:

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

I get

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

The latter is what I'm looking for.

Is there something different when using jquery to create an element that I'm missing? My actually situation is much more complex than this, but I simplified it for the purpose of this question.

Adil
  • 146,340
  • 25
  • 209
  • 204
kralco626
  • 8,456
  • 38
  • 112
  • 169
  • OK, after further research, it seems as though, the value "test" is actually set, for example I can see it when I append the item to the screen. `$('body').append($("").val("test"))` I just thought it was not working because that value of the input element does not show in the console window in chrome... guess I would have thought it would have shown as `` – kralco626 Feb 12 '14 at 04:40

3 Answers3

4

.val() is for the HTML attribute "value"

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

Mardie
  • 1,663
  • 17
  • 27
  • I guess my point was that I was under the impression that `val()` was the correct one to us for `input`. – kralco626 Feb 12 '14 at 04:33
  • @kralco626, it *is* the correct on to use for `` elements. `test` is invalid HTML. – zzzzBov Feb 12 '14 at 04:39
  • ah yes, see my comment. It just seems as though Chrome doesn't actually attach the value as an attribute when you print it to the console. So it was there, it was just hiding. – kralco626 Feb 12 '14 at 04:42
0

.text() return the combined text contents of all matched elements (such as p, div, and so on) .val() is used to obtain the value of an input element (such as input, select, and so on)

according to the official documentation .text() should not be used with input elements.

here is a reference.

UPDATE: Try to achieve this through pure javascript, this way:

HTML:

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

Javascript:

To give value to an input element:

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

and get value this way

var myinputval = document.getElementById("myinput").value
Community
  • 1
  • 1
immayankmodi
  • 8,210
  • 9
  • 38
  • 55
0

If you pass in a value to .text() or .val(), it will send that data to the matched element. If you're 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
danwarfel
  • 890
  • 1
  • 6
  • 13