Get textbox value in jQuery

This is too easy and one line code to get textbox value in jQuery. With the help of val() function you can easily get textbox value in jQuery.

Suppose I want to get textbox value which has txtName class then code will be like this:

$('.txtName').val()

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnGetName').click(function (event) {
        var name = $('.txtName').val();
        alert(name);
      });
    });
  </script>
</head>
<body>
   <div>
    <input type="text" class="txtName" value="Nirbhay" /><br />
    <button class="btnGetName">Get Name</button>
  </div>
</body>
</html>
DISPLAY

3 comments :

  1. let say i have 2 textbox share the same class name "txtName". How can i access the value of the second textbox?

    ReplyDelete
    Replies
    1. Hello Dear,
      If you sure there are only two textbox with same class then use eq() method of jquery.

      var name = $('.txtName').eq(2).val();


      You can also use :last property of jquery to get last matched element.
      var name = $('.txtName:last').val();

      Delete
  2. Nice blog thanks forr posting

    ReplyDelete