2

I have had a hunt but can't get this to work. If an input on a form is empty, it needs to have a value added to it, and then be submitted, if it already has a value, then it is submitted with that value.

Code so far

    <form name="form1" action="http://csster.com/generate.php" method="post" id="formit">
Name: <input name="name" type="text" /><br/>
Mothers Name: <input id="desti" name="mname" type="text" /><br/>
Fathers Name: <input name="fname" type="text" /><br/>
<input name="submit" type="submit" value="Submit" />
</form>


    $("#formit").submit(function(){
        if($("#desti:empty").text('Australia'));
});

Check the fiddle

EDIT - Is it possible to make it so the added value is not visible before submitting, it may confuse people on the particular form.

0

4 Answers 4

5

try this:

$("#formit").submit(function(){
     if ( $("#desti").val().length === 0 ) 
            $("#desti").val('Australia');
 });

Here is JSFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers it always makes sense when you see it ;)
4

You should use val method for form elements.

$("#formit").submit(function(){
    $("#desti").val(function(i, v){
        return $.trim(v) === '' ? 'Australia' : v;
    })
});

$("#formit").submit(function(){
    var $e = $("#desti");
    if ($e.val() === '') $e.val('Australia').addClass('aClass')
});

5 Comments

Please see my edit, is possible to make it not visible before submitting?
@Nik No, maybe you can hide the input, if you want to have a default value for the input, why no doing this on server-side?
I don't have access to the server, only client side :/ Could I just add a class to the input if it's empty that makes the text white?
@Nik Yes, you can change the color to white, or add a text-indent property.
that adds the class if it's not empty as well
2

you can get the input value with val() and set with val()

$("#formit").submit(function(){
    if($("#desti").val() === '')$("#desti").val('Oz')  
});

Comments

0

try this

$("#formit").submit(function(){

if ($('#desti').is(":empty")) { $('#desti').val('Australia'); } });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.