Johan Albertsson
Johan Albertsson

Reputation: 63

Clearing value before submitting form (not canceling submit)

I want to clear my default value in two input fields before submitting them. But this don’t work…

<form action="page.html" id="myForm">
    <input type="text" value="Firstname" name="firstname" id="firstname">
    <input type="text" value="Lastname" name="lastname" id="lastname">
    <input type="submit">
</form>

<script>
    $(document).ready(function() {
        $("myForm").submit(function() {
            if($('#firstname').val() == "Firstname")
                $('#firstname').val() = "";

            if($('#lastname').val() == "Lastname")
                $('#lastname').val() = "";

            return true;    
        });
    });
</script>

I don’t want to clear them both on focus. I cant use html5.

Upvotes: 0

Views: 2551

Answers (3)

SachinGutte
SachinGutte

Reputation: 7055

Your code is incorrect. You have to use # sign before id. So here's it

$(function() {  
    $("#myForm").submit(function(e) {       
    e.preventDefault();
        if($('#firstname').val() == "Firstname")
            $('#firstname').val("");

        if($('#lastname').val() == "Lastname")
            $('#lastname').val("");                       
    });
});

The line e.preventDefault(); will stop event propagation to let you see the effect. You can remove it.

Upvotes: 1

soju
soju

Reputation: 25322

val is a function, you can't use it like this. Try instead :

$('#firstname').val('');
....

Upvotes: 2

gdoron
gdoron

Reputation: 150313

Call the val function with empty string .val("");

$(document).ready(function() {
    $("myForm").submit(function() {
        if($('#firstname').val() == "Firstname")
            $('#firstname').val(""); // <====

        if($('#lastname').val() == "Lastname")
            $('#lastname').val(""); // <====

        return true;    
    });
});

val() with empty parameters just return the value of the element.
So your code is equals to

if($('#lastname').val() == "Lastname")
    'Lastname' = ""; // Won't change the element value.

Upvotes: 0

Related Questions