1

so i got this little code and i can't get it working and i simply can't see why. I've copied the code from another code i wrote and only removed and renamed all the stuff that i don't need. I want to give out the value of a variable in an alert box.

The JS:

<script>
     function ready2() {
         var rdy = $("#rdy").value;
         alert(rdy); 
     }
</script>

The HTML:

<body>
   <form id="form2" onsubmit="return false;">
      <div>Ready:</div>
      <input type="text" id="rdy"></input>
      <button id="btn" onclick="ready2()">Ready</button>
   </form>
</body>

If I replace $("#rdy").value; with something like "hello world", it works. So the problem must be the variable or better: the input box. The alert box always says "undefined" and I don't know why.

Any help?

2 Answers 2

4

You need this -

var rdy = $("#rdy").val();

or

var rdy = $("#rdy")[0].value;

you can use value only on DOM element, You are getting undefined because you are using it on jquery object i.e - $("#rdy")

Sign up to request clarification or add additional context in comments.

Comments

0

When you do:

$("#rdy")

You are actually generating a jQuery Object array with all the nodes in it:

[domNode1, domNode2,... domNodeN] 
//note this array is a jQuery object, not an Array

Since it is an ID it should only find one:

[domNodeWithIdrdy]

The DOM node inside the jquery array is the same as if you do getElementById which means that you can access the values directly:

var jArray = $("#rdy");
console.log(jArray[0].value);

jQuery also provides some functions that do this:

$("#rdy").value();

But bare in mind that the val() function will only return the value of the first element in your jquery Array, and ignore the presence of multiple elements on the array.

It is also safer to do .val() than to do jArray[0].value. This because if the array is empty it will try to read value out of undefined. i.e.:

jArray = $("#somethingThatDoesntExist");
assert( jArray.length === 0 );
assert( jArray[0] === undefined );

1 Comment

it's .val() not .value()

Your Answer

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