18

How can I with js or jQuery change input text value with js or jQuery before submit if the input value is null ?

Thanks for help.

2 Answers 2

40

With jQuery, you can bind a callback to the submit event with the .submit() method.

$("form").submit(function(){
   // Let's find the input to check
   var $input = $(this).find("input[name=whatever]");
   if (!$input.val()) {
     // Value is falsey (i.e. null), lets set a new one
     $input.val("whatever you want");
   }
});

Notice: To ensure that all the elements can be found it should be placed in a domready function.

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

2 Comments

Can you explain the Notice: message more? Are you saying that you need to wrap the entire thing in: $(document).ready(function() { YOURCODEHERE });
@tgharold No, because it's not related to the question. The whole thing is thoroughly explaining in the provided link.
3

With plain DOM (no library), your HTML will look something like:

<form name="foo" action="bar" method="post">
    <!-- or method="get" -->
    <input name="somefield">
    <input type="submit" value="Submit">
</form>

And your script will look something like this:

var form = document.forms.foo;
if (form && form.elements.something)
    // I use onsubmit here for brevity. Really, you want to use a 
    // function that uses form.attachEvent or form.addEventListener
    // based on feature detection.
    form.onsubmit = function() {
        // if (form.elements.foo.value.trim()) is preferable but trim()
        // is not available everywhere. Note that jQuery has $.trim(),
        // and most general purpose libraries include a trim(s)
        // function.
        if (form.elements.something.value.match(/^\s*$/)))
            form.elements.something.value = 'DEFAULT VALUE';
    }; 

1 Comment

I think you meant form.elements.somefield and not form.elements.something.

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.