Change input text value with js or jQuery before sending if value is null

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

Thanks for the help.

+8
javascript jquery
source share
2 answers

With jQuery, you can bind a callback to a send event using .submit() .

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

Note. To ensure that all items can be found, it must be placed in domready .

+27
source share

With a simple DOM (without a library), your HTML would look something like this:

 <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'; }; 
+2
source share

All Articles