Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change input text value with js or jQuery before submit if value is null

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.

like image 711
Ahmed Ala Dali Avatar asked Mar 30 '12 13:03

Ahmed Ala Dali


People also ask

How can check input value is not empty in jQuery?

Answer: Use the jQuery val() Method You can use the val() method to test or check if inputs are empty in jQuery.

How can check input value is number or not in jQuery?

version added: 1.7jQuery. The $. isNumeric() method checks whether its argument represents a numeric value. If so, it returns true . Otherwise it returns false .


1 Answers

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';
    }; 
like image 69
Thomas Allen Avatar answered Sep 21 '22 13:09

Thomas Allen