3

html:

 <input id='myTxt' type='text' value='hello'/>

javascript:

$("#myTxt").val('Blah'); // works

var bla = document.getElementById("myTxt"); bla.value = "Blah"; // works

$("#myTxt").value = "blah"; // doesn't work

Why doesn't the last example work??

2 Answers 2

1

That is because $("#myTxt") is a jQuery object with does not have anything called value.
What you can do is something like:

$("#myTxt").get(0).value = "blah";
Sign up to request clarification or add additional context in comments.

5 Comments

so is get(0) always the way to get an html object?
no. its is an array so you can also do $("#myTxt")[0].value
why would my textbox be an array? isn't there a generic way to get from a jquery object to an html object?
Why would the jquery object be an array though?
@foreyez Your $("#myTxt") will select only one DOM object (and wrap it in a jQuery object) because the selector is a unique ID - but in general, jQuery's $("someSelector") can return multiple things, such as $("div.collapsed") which will select every div that has a class of "collapsed". That is why $(...) always returns an array.
0

$("#myTxt") is an array of jQuery objects that wrap the selected DOM objects.

Since you're using an ID in your selector #myTxt you will get an array with only one element in it.

You can set the value of the selected item(s) with jQuery's .val() method:

$("#myTxt").val("blah");

You don't have to retrieve the underlying DOM object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.