append item to select box with jquery while escaping quotes - javascript

I'm adding options to a select box as follows:
x.append("<option value="+option_to_add+">"+option_to_add+"</option>");
where "option_to_add" can be any value a user has entered.
Of course, a problem arises when adding options that have single or double quotes in them.
Is there a way to escape these values correctly before appending them to a select list
e.g. this will be a problem
user types: he"llo
my code will try to append this as : <option value="he"llo"/> which crashes the html/js

I found a native jQuery way to handle this correctly:
.append($("<option></option>").attr("value",option_to_add).text(option_to_add));

You could you the Javascript replace function to escape or remove the quotes...
http://www.w3schools.com/jsref/jsref_replace.asp

You’ll need to escape the " characters, like this: \"
This can be automated as follows:
'foo"bar"baz'.replace(/"/g, '\\"'); // 'foo\"bar\"baz'
You’ll only need to do this for the value attribute of the <option> element, so the full code snippet would be:
x.append('<option value="' + option_to_add.replace(/"/g, '\\"') + '">' + option_to_add + '</option>');

Related

Jquery doesn't find div to append to when the variable in $('#div'+variable) contains spaces

I tried to append divs using jQuery from a function's input values but noticed that I wasn't getting anything but the main div appended to the body:
var the_key = "AAA AA"; //put here as an example
$('body').append('<div class="chart_canvas" id="div_'+ the_key +'" />');
$('#div_' + the_key).append('<div id="d3_canvas'+ the_key +'" />');
It works if the_key = "AAAAA".
My not so good attempt at adding quotation marks wasn't really successful and did end up with an error (unrecognized expression) as the quotation marks end up in the expression:
$('#div_' + "'" + the_key + "'").append('<div id="d3_canvas'+ the_key +'" />');
Is there any way that I can do this? The object that I'm reading these "the_key" values from do all contain spaces.
id values cannot have spaces in them. It's just about the only restriction on id values in HTML (other than that they must be unique).
Separately, CSS ID selectors cannot contain unescaped spaces either (because a space is a descendant combinator). But that doesn't matter because #1. :-)
Use a valid ID, and provided it doesn't have any characters that are allowed in HTML ids but not CSS ID selectors (or you properly escape those characters), concatenation without quotes will work.
A space in ID is a "problem" for jQuery. Try to Escape it:
<script>
// document.getElementById or similar
document.getElementById('AAA AA');
// document.querySelector or similar
$('#AAA\\ AA');
</script>
You could also use the attribute selector like this:
<script>
$("*[id='AAA AA']");
</script>
Spaces are not legal characters of an id attribute value in HTML.
Even though it might "work" in certain situations there is no guarantee that it always will.
console.log('test', document.getElementById('test'));
console.log('te st', document.getElementById('te st'));
console.log('jQuery test', $('#test').length);
console.log('jQuery te st', $('#te st').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">test</div>
<div id="te st">te st</div>

How to select element with id containing \ in jquery or javascript

we have some legacy code where Html element ID's are populated dynamically from database data (I cant change the data here)
ex. <input type="text" id="2314/test/film/code\branch"/>
when I get the ID from click event like below
var src = window.event.srcElement; I get src.id= "2314/test/film/code\\branch";
I want to use the src.id to find the same element in different function like $(_element).find("[id='" + src.id + "']").get();
which is failing to get any ID since I see "\" is replaced with "\\"
Please suggest me how to get around this ?
I don't think jQuery lets you use / in a selector. It is an illegal character in an id name, but still odd that jquery seems to flat out refuse it. Since JS has no problem with that selector You can select it with JS then pass it off to the jquery wrapper.
$(document.getElementById('2314/test/film/code\\branch'));
Maybe it´s works for you
http://codepen.io/luarmr/pen/vOgoLO
$("[id='" + str.replace(/\\/g,'\\\\') + "']").html(str)
The correct regex for backslash is '\\\\'.

why is ® not working when used with jquery

I am having a problem I want to attach the registered trademark symbol a button and I want it to be done with jquery because there are lots and lots of buttons that require the sign when I used it with html for example(below) it worked.
<input type="button" class="button_a" value="Value ®" />
But when I used jquery as below it returns as plain text:
$('.button_a').each(function(){
$(this).attr("value",$(this).attr("value")+" ®");
});
I don't want to waste my time and space by putting ® in all the button's values so I want it to be done in jquery but what am I doing incorrect.
I know it's a sluggish question but please someone help out me in this question
Javascript may be also used.
For more info please comment and ask
Thanks....
® is being rendered as a text string, but you can use unicode \u00AE
$('.button_a').each(function(){
this.value = this.value +" \u00AE";
});
http://jsfiddle.net/fbuohvm1/
or just ®:
$('.button_a').each(function(){
this.value = this.value +" ®";
});
http://jsfiddle.net/fbuohvm1/1/
Because, while the DOM you are manipulating was initialised from an HTML document, you are now dealing with DOM and not HTML. You are writing the value as text not as HTML.
You need to use either a literal character ("®") or a JavaScript escape sequence ("\u00AE").
You have to encode it first before setting the value of textbox.
$('.button_a').each(function () {
$(this).val("value " + $("<div/>").html('®').text());
});
$("<div/>").html('®').text() will return the encoded value.
Demo: https://jsfiddle.net/tusharj/t2gwptys/
you need to process content by html(), because html entities is manipulate by html() function, try this code.
$('.button_a').each(function(){
$(this).val($("<p/>").html($(this).val()+" ®").html());
});
Use a hidden div.
$('.button_a').each(function(){
var decoded = $('<div/>').html('®').text();
$(this).val($(this).val() + ' ' + decoded);
});
See Sample
In your case plain js is more straightforward:
$('.button_a').each(function(){
this.value += " ®";
});
-- EDIT --
Unfortunately this is still escaped, in fact you need
this.value += " \u00AE";

javascript not passing strings with more than 1 word to HTML

...
results += "href=" + "JavaScript:" + "decrement(" + "'" + requestList[i].name + "'" +")>";
...
document.getElementById("demo").innerHTML=results;
The problem is when in the requestList[i].name is a string with more than 1 word, but with 1 word it works.
And when i inspect element in chrome and firefox, it only appears this:
Example: requestList[i].name = "John travolta";
<a href='JavaScript:decrement("John" travolta")>
And when i hover my mouse over the element:
JavaScript:increment("John
Any idea?
Try this:
results += "href=\"JavaScript:decrement('" + requestList[i].name + "')\">";
Your concatenation is confusing. Try to simplify it. Escape the " with \" in order to use ' inside it, so your text will be nice no matter how much spaces it haves. The result will be:
href="JavaScript:decrement('John Travolta')">
So now you have to add the rest of your tag. Just a tip: Try to use your a tag with custom click like this:
href="javascript:void(0)" onclick="decrement('')"
I hope it helps. Good luck.
If you console.log(results), you will see something like this:
<a href=JavaScript:decrement('John Travolta')>
Does this look like valid HTML to you? ;) Put quotes around attribute values.
You have a syntax error here
<a href='JavaScript:increment("John" travolta")>'
remove the quote mark between 'John' and 'travolta'

Setting the Input Value attribute to a variable with space.

I am trying to set the value of a input button to a string variable.i.e"A Guide to the School Bus"; But when the HTML loads up only the first word comes up in the button. My code is given below. Thanks for the help.
var title="A Guide to the School Bus";
var htmlString= "<div class="+title+ ">"+"<input type="+"button "+"value="+title+" onclick=loadBook()>"+"</div>";
$(htmlString).appendTo(attachPoint);
And the attachpoint is a reference in the HTML that i got using the following.
var attachpoint=document.querySelector('.buttonAttachPoint');
The problem is because you're not putting quotes around the attribute values. Try this:
var htmlString= '<div class="'+title+'"><input type="button" value="'+title+'" onclick="loadBook()"></div>';
You can either escape all the " in your string or, like I have done, just switch between ' and ". " will show up as a normal character and ' is used to mark the start and finish of strings.
As a side point you probably wouldn't want to put the variable title as the class on the div as it would add each separate word as a class, so in your example the div would have 6 classes added to it.

Categories

Resources