space_food_
space_food_

Reputation: 830

Sanitizing input to stick into a hidden input value with jQuery

Maybe I am confusing this a bit, but I have a piece of code that works like the following:

$("#myButton").on('click', function(){
    var myValue = $('#myInput').val();
    listSize++;

    var listItem = "<li>" + myValue + "<input type='hidden' name='foo" +
        listSize + "' value='" + myValue + "' /></li>";
    $("ol.myList").append(listItem);
});

If the text input value contains for example, a ', then this code breaks in terms of correctly adding the hidden input value.

I was thinking that using encodeURIComponent would do the trick, but it does not.

What's the proper way to handle this?

Upvotes: 0

Views: 996

Answers (3)

charlietfl
charlietfl

Reputation: 171679

Instead of doing this with html strings, create an actual element and set it's value property using val().

You can sanitize any possible html out of it by first inserting the string into a content element as text and retrieving it as text.

Note that the value property does not get rendered in the html the same as value attribute does so quotes are not an issue

$("#myButton").on('click', function(){
    // sanitize any html in the existing input
    var myValue = $('<div>', {text:$('#myInput').val())).text();
    listSize++;    
    // create new elements
    var $listItem = $("<li>",{text: myValue});
    // set value of input after creating the element
    var $input = $('<input>',{ type:'hidden', name:'foo'+listSize}).val(myValue);
    //append input to list item
    $listItem.append($input);
    // append in dom
    $("ol.myList").append($listItem);
});

Upvotes: 1

Ruben Benjamin
Ruben Benjamin

Reputation: 787

Safest way would be to write a wrapper

function addslashes (str) {
     return (str + '')
    .replace(/[\\"']/g, '\\$&')
    .replace(/\u0000/g, '\\0')
}

var test= "Mr. Jone's car";

console.log(addslashes(test));
//"Mr. Jone\'s car"

Upvotes: 0

Gerrit Luimstra
Gerrit Luimstra

Reputation: 532

I think this is what you are looking for:

$("#myButton").on('click', function(){
    var myValue = $('#myInput').val();
    listSize++;


    var listItemHTML = "<li>" + myValue + "<input type='hidden' name='foo'></li>";
    $(listItemHTML).appendTo('ol.myList').find('input[type=hidden]').val(myValue);
});

The appendTo function returns a reference to the just appended element. Calling the val() function on the element will render the inserting of a quote useless since it will be interpreted as an actual value.

Upvotes: 0

Related Questions