tags:

views:

34

answers:

2

Hello, I'm new to this forum and looking forward to participating.

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 . However, 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(); $(""+$newTag+"").insertAfter("#currentTags"); return true; } $("span").text("Less than 20 characters please.").show().fadeOut(2500); return false; });

A: 

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).

Tom
Great. Thanks Tom. I've been reading Learning jQuery and forgot about that. And thanks for pointing out that every event has an implied parameter. Those little, obvious-to-other details are easily overlooked by a new person like myself who is catching up to speed.
Haruki Code
A: 

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);
        }
    });
});
Ariel
Thanks Ariel. The details about simplifying code are something I'm working on. How to get three lines of code down one? So, the opportunity to compare/contrast is nice to have.One practice I read (and try to apply) is using a $ before variables that are jQuery objects so you don't loose track of that fact. Thanks for all the fast replies. Really great!
Haruki Code
Starting a var with $ is a good practice, however it should only be used if the resulting object is a full jquery object. in your case it was just not. It was just text.
Ariel