Reputation: 1450
For example, if the field value was "John Wayne" I would want it to be replaced with "John_Wayne"
I'm thinking I can accomplish this through jQuery, basic idea is below:
$('#searchform').submit(function() {
//take current field value
//replace characters in field
//replace field with new value
});
Any help is appreciated.
Upvotes: 4
Views: 3400
Reputation: 11
Use the onkeyup HTML element attribute and regular expressions:
<input type="text" onkeyup="this.value=this.value.replace(/[Search Expression]/flag,'New String');">
This solution prevents the user from typing a value outside the pattern established by the regex.
For your case, use:
<input type="text" onkeyup="this.value=this.value.replace(/[\s]/g, '_');">
Upvotes: 0
Reputation: 126052
You could use the overload of val
that takes a 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'll probably want your selector to be more specific than input:text
)
Example: http://jsfiddle.net/nTXse/
Upvotes: 10
Reputation: 107536
If you want to look at all of your form elements without specifying them individually, you could do something like:
$('#searchform').submit(function() {
$.each($(':input', this), function() {
$(this).val($(this).val().replace(' ', '_'));
});
});
You might have to pay attention to the type of the element, and that it's visible, enabled, a certain type, etc.
EDIT: I would use Andrew's answer. This was just the first solution that popped into my head. This one might ultimately give you slightly more control over each field in your form, but Andrew's is short and sweet.
Upvotes: 1