0

I'm shocked, what is happening here, just simple thing what is missing here. Why html input variables can't access in jquery, I tried using id selector, name attribute. it is really weird.

$(document).ready(function(){
  var heading = $('#heading').val();
  var heading1 = $('#heading').text();
  var heading2 = $('input[name=heading]').val();
			$('#submit').click(function(){
      alert(heading);
      alert(heading1);
      alert(heading2);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<form action="">
<table>
<tr>
<th>
Heading
</th>
<td>
<input type="text" name="heading" id="heading">
<input type="submit" id="submit" name="submit">
</td>
</tr>
</table>
</form>
</body>
</html>

2
  • where do you put your jquery code? top or bottom of html code? Commented Aug 4, 2018 at 4:06
  • 1
    This doesn't show what you desire because the code you wrote runs immediately after the page is loaded and there is no input value unless you provided default values. You need to alert it after the input is provided. Commented Aug 4, 2018 at 4:08

1 Answer 1

4

You need to get value inside click event,also text() will not get the input value

$(document).ready(function() {
  $('#submit').click(function() {
    var heading = $('#heading').val();
    var heading1 = $('#heading').text(); //this will not get the value
    var heading2 = $('input[name=heading]').val(); // this will be the same as the heading var
    alert(heading);
    alert(heading1);
    alert(heading2);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="">
  <table>
    <tr>
      <th>
        Heading
      </th>
      <td>
        <input type="text" name="heading" id="heading">
        <input type="submit" id="submit" name="submit">
      </td>
    </tr>
  </table>
</form>

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

1 Comment

oh I missed, shame on me. Thanks

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.