How to escape a single quote in jQuery? - javascript

I know I can use \', but that's not the point here. Let's say I have the word "can't". It has "'" in it now. This goes in to a var in a function like so:
function active(id,clas,match,hometeam,awayteam){
So let’s say hometeam has the value of "can't". When I try to use this code:
$('#test').html(hometeam + " VS " + awayteam);
It's not working, because essentially it has:
$('#test').html(can't + " VS " + awayteam);
How do I solve this?
EDIT:
I think the problem is not in the jQuery. The line that calls this function is this line:
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','match1','hometeam','awayteam')" />
So how do I escape this?
EDIT: I haven't found the perfect solution, so I just changed the word in my database and added the "\" for now...

This should work. If the contents have double quotes then wrap the string in single quotes and escape single quotes inside.
var hometeam = '"can\'t"';
$('#test').html(hometeam + 'VS' + awayteam)

The values returned by variables do not need to be escaped in javascript. If you are having a problem there is some other underlying issue.
EDIT: Per your question edit you will need to escape the value in the function call, if you were to use can't as one of your parameters you would need
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','can\'t','hometeam','awayteam')" />

The problem is that you are using string operations to build HTML. Use jQuery/DOM methods instead and you won't have issues with this.
Another way would be escaping the quotes but compared to the previous suggestion that's just really ugly.
Since you are creating the HTML in PHP, do something like this:
echo '<input type="button" id="btn" value="1.4" class="butta" onmousedown=\'active("btn","buttdowna","match1",'.htmlspecialchars(json_encode($foo)).', '.htmlspecialchars(json_encode($bar)).');\' />';

You can change the HTML Part like this it will work,
<input type="button" id="btn" value="1.4" class="butta" onmousedown=active("btn","buttdowna","match1","can't","awayteam") />
In an HTML attribute without Quotation also work. Quotation is used to group. Example) title="Click Event" will work and title=Click Event will take the first value(Click) only. That is if a word doesn't contains space then no need of Quotation.

Related

How to get a value of arabic text from input text through change load function jquery

I need to get a value (full names) in Arabic letters from input field so I can run a query using this value. I noticed when I typed in Arabic the javascript code did not work properly and I noticed as well if I make space between the words in English text the javascript code will catch only the first word and the other words will be missed. How can I solve this problem. I looking for the most sample way
HTML Code
<input type="text" name="member" id="member" class="input_field" required />
<div class="modal-body" id="fifth-choice"></div>
Javascript Code
$("#member").change(function() {
$("#fifth-choice").load("menu1.php?member="+$("#member").val());
});
Many thanks
Try to encode the url parameter by encodeURI
$("#member").change(function() {
$("#fifth-choice").load("menu1.php?member="+encodeURI($("#member").val()));
});
If you would like to send more than a value over the same url using jquery load function you can use the below code
$("#myDiv").change(function() {
$("#fifth-choice").load("menu1.php?member=" + encodeURI($("#member").val()) + "&id=" + encodeURI($("#id").val()) + "&doc=" + encodeURI($("#doc").val()));
});
I hope this could help

impossible to escape single quotes in XML

please help me with this issue. I have a php file which generates XML. I have the following code that I can not escape a JS script within XML as follows:
$xml_after='<html>'.htmlspecialchars('
<div class="options" id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'\',hide_element(\'confirmation\');\''.$lang['delete'].'\',remove_table(\''.$tables_row['id'].'\');hide_element(\'confirmation\');\');return false;\" ><img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
The problem is in onclick functions..
Please help, full day losted already , thank you
Be aware that htmlspecialchars() escapes < and >, too. You have to use it on each value separately, not on the complete html fragment.
htmlspecialchars() has an option that escapes all quotes.
var_dump(htmlspecialchars("Escaping: <>&'\"", ENT_QUOTES));
Ouptut:
string(35) "Escaping: <>&'""
But it would be better to use DOM and let it take care of the escaping.
Additionally, I suggest using data-* attributes in HTML. The Javascript can read the attributes and bind the logic to the elements. This separates the actual JS logic from the HTML.
I think your code is incorrectly formatted
$xml_after='<html>'.htmlspecialchars('<div class="options"
id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="
show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'
\', hide_element(\'confirmation\');\''.$lang['delete'].'
\', remove_table(\''.$tables_row['id'].'\');
hide_element(\'confirmation
\');
\');return false;\" >
<img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
after each of the functions inside the show_confirmation functions you have a ; which isn't valid in a function calls parameter list
On the last line of the onClick function:
\');\');return false;\" >
The second \' is unmatched and the double quote \" shouldn't be escaped as far as I can see change that and maybe it will work for you.

Enter param in inline javascript function

How can I add a param to the removeSound function in this JavaScript code?
I cannot get it to work.
var param = "111";
coder = '<a href="javascript:;" onClick="javascript: removeSound(' + param + ');" >Delete</a>'
Update
I do not know why code = was removed! This is needed to explain the problem context.
I just want to add a proper double quoting escape method to the answers as none showed a correct way to escape double quotes inside of an onClick attribute.
In HTML it is not sufficient to use only a backslash when escaping a JavaScript double quote. You need the proper HTML entity which is "
This is a live example:
Delete
However for readability I would recommend using Antony Scott's way by using single quotes.
Delete
To add the param as a variable from whatever script your HTML is generated in you should do this:
code = '<a href="javascript:;" onClick="javascript: removeSound("' + the_param + '");" >Delete</a>';
The other possible way should be:
code = '<a href="javascript:;" onClick="javascript: removeSound(\'' + the_param + '\');" >Delete</a>';
You need to use different quotes. Try something like this ...
<a href="javascript:;" onClick="javascript: removeSound('PARAM HERE');" >Delete</a>
try this
code = 'Delete';
try this
<a href="#" onClick="removeSound('121212')" >Delete</a>

Put JSON data into html form input hidden?

I'm building a rich web application that uses a lot of data. When I'm building it I found that I was repeating myself over and over.
This is the problem. I need to put hidden application logic into HTML elements to represent the data being viewed by the client.
This is a solution I found some time ago:
<a href="bla" data-itemId="1" .... more data.
There are two problems with this method.
I can't represent arrays.
It's just ugly.
I searched for a solution but did not find anything. I also went to facebook, opened firebug,
and found this:
{"actor":"19034719952","target_fbid":"454811929952","target_profile_id":"19034719952","type_id":"7","source":"1","assoc_obj_id":"","source_app_id":"","extra_story_params":[],"content_timestamp":"1324385453","check_hash":"9eabc3553e8a2fb6"}
This json was inside an input[type=hidden] element.
I tried to do the same thing with json_encode();
<input type="hidden" name="track" value="{"_id":{"$id":"4eee908f615c2102e9010000"},"link":"george-wassouf-flag-of-my-heart-longing","file":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","lyrics":null,"freezed":false,"hits":0,"images":{"large":"\/assets\/static\/default.track.large.jpg","thumb":"\/assets\/static\/default.track.thumb.jpg","icon":"\/assets\/static\/default.track.icon.jpg"},"duration":"300","created":{"sec":1324257423,"usec":78000},"albums":[{"_id":{"$id":"4eee8d63615c21f6e7000000"},"names":{"ar":"\u0643\u0644\u0627\u0645\u0643 \u064a\u0627 \u062d\u0628\u064a\u0628\u064a","en":"Kalamak ya Habibi"},"link":"george-wassouf-kalamak-ya-habibi","images":{"original":"\/m\/pics\/albums\/o.4eee8d612c3183.11879972.jpg","poster":"\/m\/pics\/albums\/p.4eee8d63967072.02645896.jpg","large":"\/m\/pics\/albums\/l.4eee8d63a89111.20372767.jpg","small":"\/m\/pics\/albums\/s.4eee8d63b18927.47242533.jpg","thumb":"\/m\/pics\/albums\/t.4eee8d63b7f1f4.11879932.jpg","icon":"\/m\/pics\/albums\/i.4eee8d63bf1304.59902753.jpg"}},{"_id":{"$id":"4eee8d63615c21f6e7000000"},"name":"Kalamak ya Habibi","link":"george-wassouf-kalamak-ya-habibi"}],"name":"Flag of my heart longing","title":"Flag of my heart longing","mp3":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","poster":"\/m\/pics\/artists\/p.4eee85cd7ed579.65275366.jpg","artists":[{"_id":{"$id":"4eee85cd615c21ece6000000"},"name":"George Wassouf","link":"george-wassouf"}]}" />
But when I try getting the value I get this {.
I have tried all constants like JSON_HEX_TAG and did not find any questions of this type.
How can I put JSON into HTML correctly and then get it with jquery/javascript?
Your string is correct, but it cannot be defined in HTML because it contains double quotes.
HTML requires you to escape double quotes when you are defining a String that is itself enclosed within double quotes. The appropriate way of doing this is using the HTML entity:
value="""
From PHP:
Use htmlspecialchars or htmlentities (http://www.php.net/manual/en/function.htmlspecialchars.php). In any case, you normally should be using this over EVERY value you write to the client browser (not doing so may result in security risks).
From Javascript:
If you need to do this from Javascript, you can programatically set the value of the hidden element (provided your JSON string is already contained in a Javascript variable). This way you don't have to worry about encoding the string literal:
hiddenElement.value = yourString;
In order to get an escape function you can use, maybe check this thread: Escaping HTML strings with jQuery .
Best way for me was to use html & quot;
for example i do this:
<input type="hidden" id="v" value="[{"id":"1"}]" >
instead of
<input type="hidden" id="v" value="[{"id":"1"}]" >
in your input tag, the value attribute in which you are trying to put json array. Look at it. you are putting ". Second " is ending the attribute value. thus it is being interpreted as value = "{". you need to escape those ". Use single quotes ' instead. And check then
It seems my answer is late, but I want to contribute to those who come later.
Before coming here you have the concept of HTML.Use single quotes ' , Should not do that, although it still works, it is against the HTML principle .
The best way is: Use htmlspecialchars or htmlentities. #jjmont said above.
I have a small example:
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_COMPAT ); ?>" >
||
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_NOQUOTES ); ?>" >
php
set array in
<input type="checkbox" name="deviceInfo" value="<?php print_r(json_encode(array_filter($array_data), JSON_FORCE_OBJECT));?>" />
?>

JavaScript innerHTML

Why doesn't this work? innerHTML cannot take in something so complicated?
<html>
<head>
<script type="text/javascript">
function addTable() {
var html = "<table><tr><td><label for="name">Name:</label></td><td><input type="text" id="name"></input></td></tr>"; +
"<tr><td><label for="remarks">Remarks:</label></td><td><input type="text" id="remarks"></input></td></tr></table>";
document.getElementById("addtable").innerHTML = html;
}
</script>
</head>
<body>
<input type="submit" value="New Table" onClick="addTable()"/>
<div id="addtable"></div>
</body>
</html>
Something less complicated like this works:
var html = "<table><tr><td>123</td><td>456</td></tr></table>";
You need to either escape double quotes within the string you're assigning to the html variable, or just enclose the string with single quotes. Use a text editor with syntax highlighting and errors like that will jump out at you right away. You also have an extra semicolon in your assignment.
Your quoting is broken. You are using double quotes inside the string:
"<tr><td><label for="remarks">Remarks:</label></td><td><input ....
the Firefox error console should always be your first stop, errors like that are always logged there.
Your string is delimited using double quotes and also uses them within the string. Switch to using single quotes within the string.
var html = "<table><tr><td><label for='name'>Name:</label></td><td><input type='text' id='name'></input></td></tr>"; +
"<tr><td><label for='remarks'>Remarks:</label></td><td><input type='text' id='remarks'></input></td></tr></table>";
instead of double quotes use single quotes as shown below:
var html = "<table><tr><td><label for='name'>Name:</label></td><td><input type='text' id='name'></input></td></tr>' +
"<tr><td><label for='remarks'>Remarks:</label></td><td><input type='text' id='remarks'></input></td></tr></table>";
Enjoy coding!!
You need to either escape double quotes or use single quotes within the string destined for that innerHTML.
There is an error in your string , try this :
var html = "Name:"; +
"Remarks:";
document.getElementById("addtable").innerHTML = html;

Categories