Jasko Koyn Jasko Koyn - 6 months ago 10
jQuery Question

val() does not grab the current input value

I'm trying to grab the value of an input field, but it won't grab it when it's updated. I'm trying to create an ajax log in form. Here's the code

<form method="post" id="contactform">
<label for="name">Username</label>
<input type="text" id="un" placeholder="Username" />

<label for="password">Password</label>
<input type="password" id="pw" placeholder="Password" />

<br/>
<button name="submit" type="submit" class="btn" id="submit" onclick="logUserIn(); return false;">Log In</button>

<script type="text/javascript">
function logUserIn()
{
var un = $("#un").val();
var pw = $("#pw").val();

alert(un);
}
</script>


If I type something in the input field and click the submit button it won't update for me.

If I were to change the input value field manually like this

<input type="text" id="un" placeholder="Username" value="test" />


Then I get alerted "test".

Answer

I recommend that you write your JavaScript unobtrusively, i.e. keep everything JavaScript in a script tag and leave the markup separate. See Unobtrusive JavaScript - Wikipedia

HTML:

    <form method="post" id="contactform">
      <label for="name">Username</label>
      <input type="text" id="un" placeholder="Username" />
      <label for="password">Password</label>
      <input type="password" id="pw" placeholder="Password"
      />
      <br/>
      <button id="btnLogin" name="submit" type="submit" class="btn" id="submit">Log In</button>
</form>

JavaScript:

$(function() {
  $('#btnLogin').click(logUserIn);
});

function logUserIn() {
  var un = $("#un").val();
  var pw = $("#pw").val();

  alert(un);

  return false;
}

Live Demo

Comments