Vikrant Gupta Vikrant Gupta - 4 years ago 258
Javascript Question

getting data from input box in form using jquery

This is a form I have:

<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id = "userinput" size="10">
</label>
<button type="submit">Check</button>
</form>




And here is a jquery function I am running on it. My problem is that I don't know how to get the value that the user inputs in the textbox when they press submit. I am relatively new to jquery but have had no luck in researching this topic, including reading similar questions on this site.

<script>

$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('this input: first').val();
console.log(words);
});

if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}

</script>

Answer Source

You have the code in the wrong place, and the selector you are using is incorrect for the input.

See this codepen on how this could work:

http://codepen.io/KempfCreative/pen/JGRzwm

$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#joke-form #userinput').val(); 
console.log(words);
  if (words === "ANSWER") {
    $('#result').text("You have the right answer");
}
else {
    $('#result').text("Guess again!");
}
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download