开发者

getting the value of a textbox with jQuery

I have this html code

<html> 
  <head> 
    <title>JQuery Problem 2</title> 
    <sc开发者_开发知识库ript type="text/javascript" src="jquery-1.4.min.js"></script> 
    <script type="text/javascript" src="problem2.js"></script> 
  </head> 
  <body> 
    <div id="game"> 
      <form onsubmit="return false"> 
        <p> 
          Guess:
          <input type="text"/> 
          <input type="submit" value="Go"/> 
        </p> 
        <p> 
          <strong>Number of guesses:</strong> 
          <span>0</span> 
        </p> 
        <p> 
          <strong>Last guess:</strong> 
          <span>None</span> 
        </p> 
        <table border="1" cellpadding="4" cellspacing="1" style="width: 400px"> 
          <tr> 
            <th>Guess</th> 
            <th>Result</th> 
          </tr> 
        </table> 
      </form> 
    </div> 
  </body> 
</html> 

When the user enters his value i want to retrieve the numerical value that they entered in the textbox, with jQuery, how would i go about doing that?


You can select checkboxes using the :text selector but generally I would recommend using an ID or class, as appropriate.

The value of a text box can be obtained using val().

For example, this function listens for change events on all text boxes and alerts the new value:

$(":text").change(function() {
  alert($(this).val());
});


First I would add either a class or an ID to your input. Once you do that, you can retrieve it very easily like so:

var value = $('.yourClass').val();

or if you give it an ID:

var value = $('#yourID').val();


For the unique control in the page, to assign an ID is a good practice. For looped element such as table list, use position selector is better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜