简体   繁体   中英

Change (immediatly) submit button text if any form input change [JS]

How can I change immediately the submit button text if any form input change?

 //This applies to whole form $('#test').change(function() { $("#send").prop("value","Change"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="test"> <input id="Input1" value="Input1" /> <input id="Input2" value="Input2" /> <input type="submit" id="send" value="Send" /> </form> 

Here, the button text change after the cursor leave the input.

Live example : http://jsfiddle.net/rgg3A/56/

 $('#test').find(':input').on('input', function() { document.getElementById('send').value = this.value; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <form id="test"> <input id="Input1" value="Input1"> <input id="Input2" value="Input2"> <input type="submit" id="send" value="Send"> </form> 

You need to put the listener on the inputs themselves, in this case attach it to the onKeyDown event:

$('input').on("keydown", function() {
  send.value = "Change";
});

Updated Fiddle

A solution requiring minimal change would be to use the keyup event. Ie

$('#test').keyup(function() {
   send.value = "Change";
});

This way, typing in any of the input fields within the #test parent will trigger the event.

You can do it by using jquery input event and selector .

 $('input').on("keydown", function() { $('#send').val(this.value); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="test"> <input id="Input1" value="Input1"> <input id="Input2" value="Input2"> <input type="submit" id="send" value="Send"> </form> 

As your original question did not mention JQuery directly except by it's use as a selector, this one left me hanging for a proper JavaScript answer.

So this answer is the same as the other examples, but using just plain ol' JavaScript. Uses the input event, just as the other answers do.

 document.getElementById('test').addEventListener('input', function(e) { document.getElementById('send').value = e.target.value; }); 
 <form id="test"> <input id="Input1" value="Input1"> <input id="Input2" value="Input2"> <input type="submit" id="send" value="Send"> </form> 

The difference here is that it is listening for bubbled events on the form element proper, registers an event listener only once (instead of applying the same event listener to multiple elements), and using the Event.target property to figure out which element was modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM