Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append values with both single and double quotes to textbox

I need to append a value from the result data set to a input that may have any special character like *^&$#>,'" etc. The problem is that I am not able to append the entire var into the input.

Please check this fiddle. What is the thing that I have missed out in it?

Cant I do this without using .find and .append like this one?

like image 781
Vignesh Subramanian Avatar asked Jun 26 '13 06:06

Vignesh Subramanian


2 Answers

This is because you are concatenating strings, which doesn't take escaping of special characters into account. You should instead set the value with .val so that the value is escaped properly. Also, the regex is unnecessary.

$(document).ready(function(){
    var test= "this is vicky\"s \"s 's 's \"s \"S";

    alert(test);

    var input = $("<input style='width:700px;' id='testbox'></input>").val(test);

    $("#test").html("hey this is ").append(input);

});

See updated test case on jsFiddle

like image 102
mekwall Avatar answered Sep 27 '22 23:09

mekwall


So to solve this problem without using .find or appending the var seperately, I found a simple solution for this. I just need to replace the single quote " ' " with its iso latin code &#39; and other special characters with their respective codes and then use that variable in .html

var something= "this is vicky\"s \"s 's 's \"s \"S";
test=something.replace(/'/g,"&#39;").replace(/"/g,'\\"');
$("#test").html("hey this is <input id='testbox' value='"+test+"'></input>");

Have a look at this jsfiddle

like image 24
Vignesh Subramanian Avatar answered Sep 27 '22 23:09

Vignesh Subramanian