Main content
Computer programming
Course: Computer programming > Unit 7
Lesson 6: Form processing with jQueryReview: Processing forms with jQuery
To process a form with jQuery, you should add an event listener to the form element for the 'submit' event:
$("form").on("submit", function() {
// process form
});
If you are processing the form entirely in jQuery, then you should call
preventDefault()
to prevent the page reloading: $("form").on("submit", function(event) {
event.preventDefault();
// process form
});
When you want to know what a user filled out for an input in a form, you typically use
val()
: var answer = $("#answer").val();
Inside the callback function, you can reference the form element using the
this
keyword. A common pattern is to call find()
on the form element, to find only inputs inside the form element: $("form").on("submit", function() {
// store the value of the input with name='age'
var age = $(this).find('[name=age]').val();
});
Want to join the conversation?
- what is the difference between
$("form").on("submit", function() {
});
and
$("form").on("submit", function(event) {
});
Is event must be passed if i want to use event.preventDefault(); ?(10 votes)- Yes, specifying a parameter grants yu access to the
event
object for you to perform operations on it.(13 votes)
- I'm having trouble with the Donut Calculator challenge(the previous one). I don't understand how to pass the number into the calcDonuts function provided, so I deleted the calcDonuts function they provided and wrote this instead and still got the same result:
<script>
$("#calculator-form").on("submit", function(event) {
event.preventDefault();
var $winstonAge = $(this).find("[type=number]");
var winstonAge = $winstonAge.val()
var calcDonut = winstonAge * 3 * 365;
$("#calculator-results").text("Winston ate " + calcDonut + " donuts");
});
</script>
But it won't let me pass the challenge. Can someone show me how it's supposed to be done according to the instruction ? It's driving me insane. Thanks.(8 votes)- I used the given function and did:
.html("winston ate" + calcDonuts(winstonage) + " donuts"(3 votes)
- I would say that a 314-line of code game for a simple project is pretty good
BUT IF you do want to improve it MORE might I just suggest that there might even be a (fuzzy) picture of the ANIMAL that you want to have UNSCRAMBLED for
and then that might just HELP in case you NEVER get to understand the WORDS, but it might just help you in case you just need a little MEMORY joooooGGER
:)(4 votes)
- What is a form? What does it do and what is it used for?(2 votes)
- A form is an associated collection of data inputs used to collect data from a user. A wide variety of input types are available used for gathering different types of data, such as text fields for text, checkboxes for booleans, or radio buttons for multiple choice questions. Once submitted, the data can be sent to a server for further processing (or, in this case, intercepted and processed with jQuery instead).
You've used a form already, in Khan Academy's discussion area. You were presented with a form consisting of a text field for a question, and an "Ask your question" button to prompt that data to be submitted to Khan Academy's servers. Neat, huh?(8 votes)
- Hi guys, I am having troubles with the word game project. I think that my code is correct but every time I submit the answer, my whole screen goes blank. here is my code so far:
// when the user submits the form,
$("joke-form").on("submit",function(event){
event.preventDefault();
var $answer = $(this).find("[name = text]")
var answer = $answer.val();
if (answer === "jquery") {
$("#result").text("Correct!")
} else {
$("#result").text("Incorrect")
}
});
// check that their answer is correct
// and show them appropriate message
help appreciated!(4 votes)- Try my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Project: Word game </title>
<style>
body {
font-family: Arial, sans-serif;
}
form {
font-size: 1.5em;
}
.scrambled, input, button {
font-family: monospace;
font-size: 2em;
}
.rslt {
font-family: cursive;
font-size: 20px;
}
.win {
color: green;
}
.lose {
color: red;
}
</style>
</head>
<body>
<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" size="10" name="word">
</label>
<button type="submit">Check</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
// when the user submits the form,
// check that their answer is correct
// and show them appropriate message
$("#joke-form").on("submit", function (event) {
event.preventDefault();
var $result = $("<div>");
$result.addClass("rslt");
var $answer = $(this).find("[name=word]");
var answer = $answer.val();
if (answer === "JQUERY") {
$result
.text("Congratulations! It's the correct answer.")
.addClass("win");
} else {
$result
.text("Oops! It's not right. Try again.")
.addClass("lose");
}
$result.appendTo("body");
});
</script>
</body>
</html>(2 votes)
- I'm so close to completing this challenge, yet I have a minor issue with my code. I was able to get the computer to give the answer, but no matter what I type in, it responds with correct! How do I get it to tell me if I've typed in something incorrect? I've pasted in my code below so it's easier to analyze.
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:<br>
(Please type in all caps)<br>
<span id="scrambled">REYJUQ</span>
<br>
<input type="text" size="10">
</label>
<button type="click">Check</button>
</form>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
// when the user submits the form,
// check that their answer is correct
// and show them appropriate message
$("form").on("submit", function(event) {
event.preventDefault();
var $answer = $(this).find("[text=10]");
var answer = $answer.val();
var answer = "JQUERY"
console.log(answer);
if (answer === "JQUERY") {
$("#result").text("Correct!");
} if (answer !== "JQUERY") {
$("#result").text("You are incorrect");
}
});
$("form").on("submit", answer);(2 votes)- You can replace
if (answer !== "JQUERY") {
$("#result").text("You are incorrect");
}
with anelse
.
The other problem is that you reassignanswer
toJQUERY
. It never changes.
Use another name for the variable and you are good to go!(5 votes)
- I got a question on project word game. How do you manipulate text input forms?
https://www.khanacademy.org/computing/computer-programming/html-js-jquery/form-processing-jquery/p/project-word-game(4 votes) - can anyone pls help me.. I feel im getting close but it still doesn't work.(regarding donuts challenge)
code:
<script>
var $age = $("#calculator-form").find($("[Name = age]"))
var age = $age.val()
var calcDonuts = function(years) {
return years = age * 3 * 365;
};
$("#calculator-form").on("submit", function(event) {
event.preventDefault();
// TODO: Find inputted age, calculate # of donuts
$("#calculator-results").text("Winston ate " + years + " donuts");
});
</script>(2 votes) - what's wrong in this code in word game challenge.
$("#joke-form").on("submit",function(e) {
e.preventDefault()
var $checkAnswer = $(this).find("[name=game]")
var checkAnswer = $checkAnswer.val()
console.log(checkAnswer)
if (checkAnswer === JQUERY) {
$("#result").text("correct")
} else {
$("#result").text("incorrect")
}
});(2 votes) - I just started learning JavaScript, and jQuery. Since I'm doing them back to back (they're essentially the same thing), but I'm getting a bit confused about when to use $ and when not to. I also notice that jQuery uses a lot of " " quotation marks around the elements. Do we put that around variables too?(1 vote)
- $ is used in two different ways:
1. As a function to access jQuery:$(<css selector here>)
finds all elements that match that selector$(DOM_node)
converts a DOM node to a jQuery object.
etc.
2. As a prefix before jQuery objects:$paragraph = $("p");
$object = $(DOM_node);
Also, you should not put quotation marks around variables.(2 votes)