1

I want to have a generic .js file which, for each form it encounters on a page, on submit, it strips HTML from all textarea, input and select elements. I feel like I'm missing a basic trick.

$("form").each(function() {
    $(this).find(':input')
    if (!isNaN(this.value)) {
        this.value = this.value
            .replace(/&/g, "&")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
jacob21
  • 171
  • 4
  • 16

2 Answers2

3

You're not doing anything with the return value from .find. this will still refer to the form.

Two things you might want to consider:

  • Use the descendant combinator to access the fields immediately: $('form :input')
  • The val setter handles iteration natively

Thus:

$('form :input').val(function() {
   return !isNaN(this.value) ? this.value : this.value.replace( ... );
});

Demo

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
0

Since you are using jQuery, you may let it do the encoding for you:

function htmlEncode(value){
    //create a in-memory div, set it's inner text(which jQuery automatically encodes)
    //then grab the encoded contents back out.  The div never exists on the page.
    return $('<div/>').text(value).html();
}

function htmlDecode(value){
    return $('<div/>').html(value).text();
}

Then do:

$('form :input').val(function() {
   return this.value = htmlEncode(this.value);
});

Inspired by: https://stackoverflow.com/a/1219983/5528759

See a demo here http://jsfiddle.net/vbwt3828/

Hope it helps

Community
  • 1
  • 1
bkfreddy
  • 1
  • 2