简体   繁体   中英

How to pass quotation marks to javascript function

I have a javascript function which accepts strings which include quotation marks and displays in a input field. But this function does not accept the string after the quotation mark

function searchFormatter(cellvalue, options, rowObject) {
    return '<input id="txt' + cellvalue + '" type="text"  disabled="disabled"  value="' + cellvalue + '" />';
}

Eg. 21" Inch ==> 21

Is there anyway I can pass quotation marks to the function and print them. I don't want to replace them. I want to display them.

You must escape special HTML characters like " , < , > . Eg:

function searchFormatter(cellvalue, options, rowObject) {
    cellvalue = cellvalue.
                replace(/&/g,'&amp;').
                replace(/>/g,'&gt;').
                replace(/</g,'&lt;').
                replace(/"/g,'&quot;');
    return '<input id="txt' + cellvalue + '" type="text"  disabled="disabled"  value="' + cellvalue + '" />';
}

You have to pass the value of the cellValue as shown below ( var cellValue = 21"(Should be given as 21 followed by &quot followed by ;(semicolon))

You can get the value as 21" in the input box. Hope this helps.

You need to replace " with &ampquot;

Use this helper method:

function htmlEncodeInputDisplay(string) {
    if (string == null || jQuery.trim(string) == "") return string;
    string = string.replace(/&lt;/g, "<");
    string = string.replace(/&gt;/g, ">");
    string = string.replace(/&amp;/g, "&");
    string = string.replace(/&nbsp;/g, " ");
    string = string.replace(/\"/g, "&quot;");
    return string;
}

You can use the Javascript Functions escape() to encode a sting and then unescape() to decode them if needed.

You can also manually escape them like in the example below.

var name = prompt("Please write your \'name\' in the box\r Write it with \"quotes\" like this.","");

The quote escaped using \\ goes through as a part of the string.

just escape the value when creating the input element, and then unescape the value to display it correctly.

Simplified example:

function make_input(val) {
    return '<input value="' + escape(val) + '" />';
}

// add to dom

$('input').each(function(){
   var current_value = $(this).val()
   var new_value = unescape(current_value)
   $(this).val(new_value)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM