user86834 user86834 - 1 year ago 77
jQuery Question

how to get a jquery variable value

I have a jquery variable


In firebug if I hover over the variable at runtime I can see the the variable value "help". How can I get the the value "help" from the jquery variable and assign it to a javascript variable;

I have tried:

var text = $('#myValue')

this jut creates an empty object

I have also tried

var text = $('#myValue').text()

Which returns an empty String "".

And I have tried

var text = $('#myValue').val()

Which returns undefined.

Answer Source

I think this question has been clowning around for long enough. For the benefits of that question, I will clarify something: $('#myValue') is a jQuery selector that points toward an element with ID "myValue", just as it is used in css :

#myValue { display:block;width:100px;height:100px; }

This line will instruct the page that the element with ID "myValue" needs to be displayed as a 100x100 block.


var text = $('#myValue');

will hold the element with ID "myValue", if it ever exists. (IT WON'T GET THE VALUE OF ANY VARIABLE CALLED myValue)

To make sure that the element exists, you may test it like this:

if ($('#myValue').length > 0) {
    // the element exists

There is no wizardry around jQuery selectors, you can take a look yourself at this reference. To get the text / value of an element you have many options depending on what the element is and what you want to access within it.

  • Text inside a tag like div, span, etc. : $('#elementID').text();
  • Value of an option, input, button, etc. : $('#elementID').val();
  • All the html content within a tag : $('#elementID').html();
  • Etc.

If, however, you really want to get the value of a variable, I would ask you this: why do you need to put its value into another variable ?

I hope this will clear things up.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download