I have a loop that creates links with a javascript function call in the onClick events and uses the text returned from a database as one of the parameters. My issues I am having is that sometimes this text being returned has parenthesis in them which is causing a syntax error in my code.
Example:
code:
formResults += "<a onclick='openForm(" + this.displayText + "," + this.ID + ");'>" + this.displayText + "</a>";
HTMLDisplay:
<a onclick="openForm(Example Form (Example Form 1) Application Instructions ,1108);">Example Form (Example Form 1) Application Instructions </a>
as you can see the name of the form contains a set of parenthesis. Is there anyway I can include these? The reason I need to is because the function points to another system that uses the ID and displayText in order to render the proper form.
thank you
The parenthesis aren't the problem, it's the lack of quotes inside the function.
formResults += "<a onclick='openForm(\'" + this.displayText + "," + this.ID + "\');'>" + this.displayText + "</a>";
This below snippet (from yours)
`openForm(Example Form...`)
Will throw an error because it's looking for variables Example and so on, quote that string!
I strongly suggest
code:
formResults += '<a class="openForm" data-text="'+this.displayText + '" id="'+this.ID + '">' + this.displayText + '</a>';
HTMLDisplay:
<a class="openForm" data-text="Example Form (Example Form 1) Application Instructions" id="1108">Example Form (Example Form 1) Application Instructions </a>
jQuery:
$(function() {
$(".openForm").on("click",function(e) {
e.preventDefault();
openForm($(this).data("text"),this.id);
});
});
Related
I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(''.$variable.'');"
It will work! (with no Vue), ok ? :)
I have a problem when converting store html code to javascript variable, I know we can convert using converter tools, but I can't use this converter in my situation.
I am trying the following code
var t_cls="font-effect-anaglyph rotator";
var randompostsurl="www.allinworld99.blogspot.com";
var randompoststitle="Open Inspect Element And see the Code";
var default_script = "<script> document.write('<div><a class="+t_cls+" href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>'); <\/script>\n";
$("#apnd").append(default_script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="apnd"></div>
The above one will produce the following output
<a class="font-effect-anaglyph" rotator="" href="www.allinworld99.blogspot.com" rel="nofollow">Open Inspect Element And see the Code</a>
Why the rotator class will created as new attribute?
Because there are no quotes around the class attribute in the result. You need to add them, since you have a space in the attribute's value:
default_script = "<script> document.write('<div><a class=\""+t_cls+"\" href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";
// Here --------------------------------------------------------^^---------^^
Replace your default_script code
default_script = "<script> document.write('<div><a class='"+t_cls+"' href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";
As there are no quotes in class, it produce rotator as a new attribute. But you can achieve rotator as a class by the following way. i.e replacing single quotes with escape sequence.
<script>$(document).ready(function(){
var t_cls="font-effect-anaglyph rotator", randompostsurl="www.allinworld99.blogspot.com",
randompoststitle="Open Inspect Element And see the Code",
default_script = "document.write(\"<div><a class=\""+t_cls+"\" href=\"" + randompostsurl + "\" rel=\"nofollow\">\" + randompoststitle + \"<\/a><\/div>\");<\/script>\n";
$("#apnd").append(default_script);
});
</script>
In javascript I am creating a li element as per below which contains only the problem I am seeing.
The data-videoUrl is showing the full url, so all good there.
The issue is the entry.link and entry.title, while debugging, I verified the strings are within quotes. i.e. "This is a pod cast." The data-videoTitle and data-videoDesciption are being truncated though. i.e. "This" will show from the previous example.
I'm not sure what is occuring in the latter two data assignments as I've verified the text is not double quoted etc. What is occuring with the html5 data elements? I can provide a more complete example if needed.
var podItem = document.createElement("li");
podItem.innerHTML = entry.title
+ "<a data-videoUrl=" + entry.link + " "
+ "data-videoTitle=" + entry.title + " "
+ "data-videoDescription=" + entry.contentSnippet + " "
+ "</a>";
document.getElementById("podCastList").innerHTML += podItem.innerHTML;
Here is a the html being generated.
<a data-videourl="http://rss.cnn.com/~r/services/podcasting/studentnews/rss/~3/d3y4Nh_yiZQ/orig-sn-060614.cnn.m4v" data-videotitle="CNN" student="" news="" -="" june="" 6,="" 2014="" data-videodescription="For" our="" last="" show="" of="" the="" 2013-2014="" school="" year,="" cnn="" takes="" a="" look="" back,="" ahead,="" and="" at="" stories="" making="" ...="" <=""></a>
I'm sure there's something I'm not fully understanding. Why would the first data element get the text correctly, and the next two data elements break up the text as in: [data-videotitle="CNN" student="" news=""]. The text is a straight forward sentence quoted i.e. "CNN student news..."
Why would videoUrl work correctly and the other two not?
You need to add some quotes around the attributes...
podItem.innerHTML = entry.title
+ "<a data-videoUrl=\"" + entry.link + "\" "
+ "data-videoTitle=\"" + entry.title + "\" "
+ "data-videoDescription=\"" + entry.contentSnippet + "\" "
+ "</a>";
You'll also want to make sure you escape any quotes that are inside the attributes as well.
The code dynamically creates a listview which works but i want to make it so when a listview item is clicked it sends the a url paramater to another method. When i set a paramater it doesnt alert the paramater, but when i give no parameter it works.
var output =
"<li onclick='openURL()'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";
The above works - No parameter in openURL();
var output =
"<li onclick='openURL('" + results.rows.item(i).url + "')'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";
The above doesnt work - I have done alert(results.rows.item(i).url) and it has a value.
function openURL(url) {
alert("opening url " + url);
}
Could someone explain what i'm doing wrong, i've been trying to solve the problem for hours.
Cheers!
You are using single quotes to open the HTML attribute, you can't use it as JavaScript String because you'll be closing the HTML attribute, use double quotes:
var output =
"<li onclick='openURL(\"" + results.rows.item(i).url + "\")'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";
How do i fix this link in javascript.
Link
Its missing single quotes around 'Business'
Javascript:
html += "<option value='javascript:clientGalleryLink(" + titleArray[x] + ")'>" + titleArray[x] + "</option>";
use \ to escape the quotes
html += "<option value='javascript:clientGalleryLink(\"" + titleArray[x] + "\")'>" + titleArray[x] + "</option>";
<a href='javascript:clientGalleryLink("Business")'>Link</a>
html += "<option value='javascript:clientGalleryLink(\"" + titleArray[x] + "\")'>" + titleArray[x] + "</option>";
Could you please try this one out.
Thanks.
Try this to escape the attribute quotes and thus giving you the single inner quotes like you show in your example.
html += "<option value=\"javascript:clientGalleryLink('" + titleArray[x] + "')\">" + titleArray[x] + "</option>";
Escaping problems like this is why it's best to avoid creating JavaScript-in-HTML dynamically in strings. The javascript: pseudo-URL scheme should also never be used.
Instead, consider an ‘unobtrusive scripting’ approach: move the data out of an embedded JS string and into normal attributes, such as class or, if the link corresponds to a particular element on the page, the href itself:
<a class="gallerylink" href="#Business">Link</a>
for (var i= document.links.length; i-->0;) {
if (document.links[i].className==='gallerylink') {
document.links[i].onclick= function() {
clientGalleryLink(this.hash.substring(1));
return false;
};
}
}
The second example:
html += "<option value='javascript:clientGalleryLink(" + titleArray[x] + ")'>" + titleArray[x] + "</option>";
is just a mess. Aside from the lack of \' quoting around the titleArray value, and the lack of HTML-escaping or JS-string-literal-escaping on the titleArrays (so if you have '"<& characters in the title you've got problems).
Are you expecting the script to get executed when the option is chosen just because you've put it in the value? It won't.
Better to use the DOM objects than trying to mess around inserting JavaScript inside HTML inside JavaScript inside HTML. For example, if you're looking for a select box that calls clientGalleryLink every time the selected option is changed:
<div id="PlaceWhereYouWantToPutTheSelectBox"></div>
<script type="text/javascript">
var s= document.createElement('select');
for (var i= 0; i<titleArray.length; i++) {
s.options[i]= new Option(titleArray[i], titleArray[i]);
}
s.onchange= function() {
clientGalleryLink(this.options[this.selectedIndex].value);
};
document.getElementById('PlaceWhereYouWantToPutTheSelectBox').appendChild(s);
</script>
No ugly escaping necessary, no cross-site-scripting security holes.
add slashes:
\"" + titleArray[x] + "\"