0

What would be the best approach to change specific characters in all text input fields of a form, on submit? When the form is submited I want "x" to be replaced with "y" and "0" with "1". I need to place this code inside the form validation script, so that it runs on submit.

So far, found this. Not quite what I need, besides I can't even make it work :)

var change_text = document.getElementById("mytextinput");
change_text = change_text.replace( /x/g, 'y' );
change_text = change_text.replace( /0/g, '1' );

// and so on for all text inputs...
Malasorte
  • 1,153
  • 7
  • 21
  • 45
  • 2
    It's just an idea. Rather than using this idea in client side, why can't you try the same in server side. Rather than getting confused with javascript, there are many server side scripting languages that helps you in string manipulation – Ganesh Babu Apr 10 '14 at 11:27
  • @Ganesh this is a great idea, actually. – DontVoteMeDown Apr 10 '14 at 11:33
  • @Ganesh Good idea. You need server-side validation additionally anyway. – PointedEars Apr 10 '14 at 11:47

1 Answers1

1

When you attach an event handler to the onsubmit event of the form, your handler will be called with an argument of type event:

var submithandler = function (event) {
  var form = event.target; // this is not be cross browser compatible
  // iterate over all form elements:
  var i, l;
  for (i = 0, l = form.elements.length; i < l; i += 1) {
    if (form.elements[i].type === 'text') { // only for type="text"
      form.elements[i].value = form.elements[i].value.replace(/x/g, 'y');
    }
  }

  return true; // return false to prevent form submit
};
phylax
  • 2,034
  • 14
  • 13
  • Thank you! And to also replace 0 with 1 should I add this: form.elements[i].value = form.elements[i].value.replace(/0/g, '1'); ? – Malasorte Apr 10 '14 at 11:41
  • 1
    Instead of `event.target` just write `this`, which is more compatible. Better yet, do not use the DOM to add the `submit` event listener, use the `onsubmit` attribute of the `form` element and pass `this` to your function/method you call there. – PointedEars Apr 10 '14 at 11:44
  • @PointedEars is right. You should write: `
    – phylax Apr 10 '14 at 11:46
  • Not quite what I meant, but also correct. However, a function *expression* is apparently not necessary here; you can write (which again is slightly more compatible) `function submithandler (form) { … }` (I prefer `form_submit (…)` and the like) as it always had. Another advantage of the simpler syntax is that you can call that function from everywhere in your code because source code order does not matter anymore. – PointedEars Apr 10 '14 at 11:50