Replace characters in a field on a submit form

For example, if the field value was "John Wayne", I would like it to be replaced by "John_Wayne"

I think I can accomplish this via jQuery, the basic idea is below:

$('#searchform').submit(function() { //take current field value //replace characters in field //replace field with new value }); 

Any help is appreciated.

+4
source share
2 answers

You can use val overload, which performs the function:

 $("input:text").val(function (i, value) { /* Return the new value here. "value" is the old value of the input: */ return value.replace(/\s+/g, "_"); }); 

(You probably want your selector to be more specific than input:text )

Example: http://jsfiddle.net/nTXse/

+10
source

If you want to view all form elements without specifying them separately, you can do something like:

 $('#searchform').submit(function() { $.each($(':input', this), function() { $(this).val($(this).val().replace(' ', '_')); }); }); 

You may need to pay attention to the type of element and its visibility, inclusion, specific type, etc.


EDIT: I would use Andrew's answer. This was the first decision that appeared in my head. This may ultimately give you a little more control over each field in your form, but Andrew is short and sweet.

+1
source

Source: https://habr.com/ru/post/1387833/


All Articles