jquery : insert new DOM element disappears
I am practicing with jQuery and trying to write a little interaction where
a user submits a word (a tag) and then it displays as a new DOM element within <div id="currentTags"></div>
. However,开发者_Go百科 the newTag flashes and then disappears immediately.
What am I missing?
$("form").submit(function() {
var $newTag = $("input:first").val();
if ($newTag.length < 20) {
// adds an a success alert in an empty span
$("span").text("Added. Add more?").show();
$("<div class='insertedTag'>"+$newTag+"</div>").insertAfter("#currentTags");
return true;
}
$("span").text("Less than 20 characters please.").show().fadeOut(2500);
return false;
});
Your return true statement is probably causing the form to submit. You want to return false in every case (or use preventDefault() to stop the action). I can see where you think you want to return true when the user does things right and false when it's wrong, but you're actually returning a value to the submit event telling it either:
true = yes, submit this form
false = no, don't submit the form
Try this instead:
$("form").submit(function(e) {
e.preventDefault();
// rest of logic
}
Every event has an implied parameter (typically referred to as "e" like I'm doing here) and you can call preventDefault() on it to stop the normal action (in this case, stopping the form from submitting).
Why are you wrapping something so simple in a form? The only reason I'd do that is when using ajax and needing it to degrade gracefully in case javascript is disabled.
What you're looking for can be simplified like this:
$(document).ready(function() {
$("#id_of_add_button").click(function() {
var newTag = $("input:first").val();
if (newTag.length < 20) { // adds a success alert in an empty span
$("span").text("Added. Add more?").show();
$("#currentTags").after(" " + newTag);
} else {
$("span").text("Less than 20 characters please.").show().delay(2500).fadeOut(500);
}
});
});
精彩评论