Im trying to use document.write in order to create a html element that will link to a function. However I am getting:
SyntaxError: missing ) after argument list"
The document.write is also inside a for loop as it needs to dynamically create links for each piece of data.
standardArray[i] = '<a href ="javascript:void(0);" onclick = "showDetails(null, null, ' + stdata.rows.item(i).Title + ');">' + stdata.rows.item(i).StandardNumber + ' ' + stdata.rows.item(i).Title;
document.write(standardArray[i]);
Any ideas?
I assume CORNEAL CALCIUM CHELATION is a string, so you need to format your onclick as follows:
showDetails(null, null, 'CORNEAL CALCIUM CHELATION');
Related
I want to place an onclick event inside a dynamically generated list. I can't use it as it is, like updateRoomID(arg), because it would fire immediately. So I placed it inside an anonymous function, as advised by various sources online: function (){updateRoomID(arg)}. But this results in: "Uncaught SyntaxError: Unexpected token (". Developer tools says the problem is at function().
The section of code it's in:
socket.onmessage = function(event) {
var msg = JSON.parse(event.data);
for (let i = 0; i < msg.length; i++) {
if (msg[i].beingserved == false) {
listRooms.innerHTML += '<li id=' + msg[i].roomid +
// Problem on following line.
' onclick=' + function () { updateRoomID(msg[i].roomid) } +
'>' +
'<a href="#">' +
msg[i].roomid +
'</a></li>';
} else {
document.getElementById(msg[i].roomid).remove();
};
};
};
I've tried it with the function as a string inside quotations marks: <li id=' + msg[i].roomid +' onclick="function(){updateRoomID(msg[i].roomid)}">'. I've tried placing the onclick handler in href link instead, and also replaced it with addEventListener. But I got the same error with these attempts.
If I try function(){updateRoomID(arg)}() with the parentheses behind, it fires immediately as expected.
I've been looking through it all day and can't figure out where the syntax error is. I'm quite unfamiliar with JavaScript. What am I doing wrong?
You can't put a function in the onclick attribute. It contains JavaScript source code that should be executed.
What you should do in this case is put the function call as a string, but substitute in the value of the argument.
Using a template literal makes this easier.
listRooms.innerHTML += `
<li id="${msg[i].roomid}" onclick="updateRoomId(${msg[i].roomid})">
${msg[i].roomid}
</li>`;
I am trying to pass the value of a dynamically generate URL to a javascript function
htmlstr += '<li class="class_name"><a href="javascript:void(0)"' + 'onclick="javascript_name(' + url_fullimage + ')"' + '><img class="photos_class" src="photo1.jpeg" alt="thumbnail" /></a></li>'
The url_fullimage has a value - http://lh3.googleusercontent.com/7ukYJKDRVH0kEgnTIhqwR20GxsXf_t2_rqQDHN1n8-5x9mu1dDomTjJZMUWb6oHlVUurh-o3m_DI8ZMXU5C86yanWGg_XQ81
When I click on the image, I get a
SyntaxError: missing ) after argument list
error.
I have researched various places. I am very sure the problem is with the value of the URL passed in a variable. For instance, if the variable had a value of say "sample" (instead of the URL) the function is called correctly.
Should I "escape" the special char in the URL? How do I do this, since it is dynamically generated in a variable?
I have spent 2 days on this...
To simply answer the problem in question, you're missing quotes for the string in the click handler. Fixed:
htmlstr += '<li class="class_name"><a href="javascript:void(0)"' + 'onclick="javascript_name(\'' + url_fullimage + '\')"' + '><img class="photos_class" src="photo1.jpeg" alt="thumbnail" /></a></li>'
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 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);
});
});
I'm dynamically generate tables row (buttons) using JS- Ajax.when i parse a numeric value removeProduct function return the alert. but i cant get alert if i parse a String. can anyone help me to solve this problem
problem is in this line :
onclick='removeProduct( " + prcode + " )'
how to parse a String via function? (as a JavaScript String)
var single = alldata[i].split("##");
var rows = "";
var prcode = single[1];
rows += "<td><a class='btn' onclick='removeProduct( " + prcode + " )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
$(rows).appendTo("#tblproductslist tbody");
Function :
function removeProduct(str) {
alert(str);
}
Thanks in advance!
Because you are trying to pass a string literal, so try to enclose the value in ""
onclick='removeProduct(\"" + prcode + "\")'
Since you are working with jquery, I would recommend you use event delegation to handle event and the data-api to store the data.
You need this:
rows += "<td><a class='btn' onclick='removeProduct( \"" + prcode + "\" )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
If "prcode" is a string you must to quote it or it will be treated as (undefined) variable and will trigger an error.
Good luck!