I've looked this up and tried it out but it isn't working. If the user submits a
in the input field, then it should alert it works
but for some reason it isn't working.
What am I doing wrong and how can I fix it?
$(function() { var $list, $newItemForm; $list = $('ul'); $newItemForm = $("newItemForm"); $newItemForm.on('submit', function(e) { e.preventDefault(); // var text = $('input:text').val(); var text = $('itemField').val(); console.log(text); $list.append('<li>' + text + '</li>'); // $('input:text').val(''); if (text == "a") { alert("it works"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="newItemForm"> <input type="text" id="itemField" placeholder="item" /> <input type="submit" id="add" value="add" /> </form>
You forgot to prefix #
in the selector while referencing the form ( $("newItemForm")
) and input value ( $('itemField').val()
) in variables:
$(function() { var $list, $newItemForm; $list = $('ul'); $newItemForm = $("#newItemForm"); $newItemForm.on('submit', function (e) { e.preventDefault(); // var text = $('input:text').val(); var text = $('#itemField').val(); console.log(text); $list.append('<li>' + text + '</li>'); // $('input:text').val(''); if(text == "a") { alert("it works"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="newItemForm"> <input type="text" id="itemField" placeholder="item"/> <input type="submit" id="add" value="add"/> </form>
I think the problem is with the selectors for "newItemForm" and "itemField".
In jQuery, when you want to select elements by ID you need to prepend the # character.
The code should be as follows:
$(function() {
var $list, $newItemForm;
$list = $('ul');
$newItemForm = $("#newItemForm"); // Remember to use # to select by ID.
$newItemForm.on('submit', function (e) {
e.preventDefault();
// Get value from item field.
var text = $('#itemField').val(); // Use # here as well.
// Clear the item field.
$('#itemField').val('');
console.log(text);
$list.append('<li>' + text + '</li>');
if(text == "a") {
alert("it works");
}
});
});
If you don't use #, jQuery expects what follows to be an element type, for instance ul or span or the like. If you want to select by class you need to prepend a . in front of the class name, for instance ".classname".
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.