This question already has answers here:
Pass a string parameter in an onclick function
(27 answers)
Closed 3 years ago.
I am building an HTML line in jQuery to append to a table in the HTML and want to capture when the input value changes. I am trying to pass a variable obj.attNewChum in the onchange attibute as follows:
contents = contents + "<input type='text' id='" + obj.cdId + "' name='" + obj.cdId + "' value='" + attMeeting + "' onchange='attendanceUpdateFunction(this.id, this.value, "+obj.attNewChum+")'>";
However, this gives the following error in the console:
Uncaught ReferenceError: N is not defined
at HTMLInputElement.onchange (Attendance.html:1)
attendanceUpdateFunction(this.id, this.value, N)
The variable obj.attNewChum does contain the value N.
I have tried putting the variable in quotes:
contents = contents + "<input type='text' id='" + obj.cdId + "' name='" + obj.cdId + "' value='" + attMeeting + "' onchange='attendanceUpdateFunction(this.id, this.value, "+"\"'obj.attNewChum'\""+")'>";
And that gives the following error in the console:
Uncaught SyntaxError: Invalid or unexpected token
The best alternative would be to attach the listener properly using Javascript instead, without using inline handlers, that way you don't have to deal with any escaping issues:
const input = $("<input>")
.prop({
id: obj.cdId,
name: obj.cdId,
value: attMeeting
});
input.on('change', function() {
attendanceUpdateFunction(this.id, this.value, obj.attNewChum);
});
Note that this results in the input being a jQuery object rather than a string, so rather than concatenating the new HTML, you would want to .append the new element.
If, by chance, you're just using the id to try to pass the obj.cdId to attendanceUpdateFunction, you might consider removing the id entirely and just use the plain reference to cdId:
const input = $("<input>")
.prop({
name: obj.cdId,
value: attMeeting
});
input.on('change', () => {
attendanceUpdateFunction(obj.cdId, input.val(), obj.attNewChum);
});
Use as follows
contents = contents +'<input type="text" id="'+obj.cdId+'" name="'+obj.cdId+'" value="'+attMeeting+'" onchange="attendanceUpdateFunction(this.id, this.value, \''+obj.attNewChum+'\'")">';
Related
I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.
Click event doesn't work on dynamically generated elements
In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.
onClickTest = function(text, type) {
if(text != ""){
// The HTML that will be returned
var program = this.buffer.program;
var out = "<span class=\"";
out += type + " consolas-text";
if (type === "macro" && program) {
var macroVal = text.substring(1, text.length-1);
out += " macro1 program='" + program + "' macroVal='" + macroVal + "'";
}
out += "\">";
out += text;
out += "</span>";
console.log("out " + out);
$("p").on("click" , "span.macro1" , function(e)
{
BqlUtil.myFunction(program, macroVal);
});
}else{
var out = text;
}
return out;
};
console.log of out give me this
<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>
I have tried both this.program and program but it doesn't work.
Obtain values of span element attributes, since you include them in html:
$("p").on("click" , "span.macro" , function(e)
{
BqlUtil.myFunction(this.getAttribute("program"),
this.getAttribute("macroVal"));
});
There are, however, several things wrong in your code.
you specify class attribute twice in html assigned to out,
single quotes you use are not correct (use ', not ’),
quotes of attribute values are messed up: consistently use either single or double quotes for attribute values
var out = "<span class='";
...
out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;
...
out += "'>";
depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.
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!
I'm trying to pass an object to a button's onclick but it doesn't seem to work. This is what I'm trying:
<input type='button' onclick='showTransreqForm(\"" + result.productsArray[i] + "\")' value='Go'>
If I print the object, result.productsArray[i], just above this line, I can see all its attributes in the javascript console.
But when I print it in the showTransreqForm function it comes as [object Object] and the data doesn't seem to be there.
Just for completion this is the showTransreqForm function:
function showTransreqForm(plan) {
console.log(plan);
}
What am I missing?
EDIT: this is the code that the button generated is part of:
var planStr = "<b>Recommended Plans</b>" + "<br><br>" +
"<form id='getTransForm' method='POST'>";
for (i = 0; i < result.productsArray.length; i++) {
console.log(result.productsArray[i]);
console.log(result.productsArray[i].get("Price"));
planStr += "plan " + (i+1) + "<br>" +
result.productsArray[i].get("CarrierName") + ": " +
result.productsArray[i].get("Price") +
"<input type='button' value='Go' onclick='showTransreqForm(\"" + result.productsArray[i] + "\")' >" +
"<br><br>";
}
planStr += "</form>";
$(".success3").append('<br />' + planStr).show();
As mentioned above, the result.productsArray[i] prints out correctly from inside the for loop, and so does the price attribute. But it doesn't get passed correctly to the showTransreqForm function.
This is because the way you have constructed the onclick. Appending string to an object will result to string.
In your case "" + object would result to "[object Object]".
Just change your code to below
<input type='button' onclick='showTransreqForm( result.productsArray[i])' value='Go'
I assume you have defined result variable globally.
I've a Javascript with Jquery.
http://jsfiddle.net/P5gD7/3/
var libelle = 'tes\'te';
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' value='" + libelle + "' />";
$("#test").append(toAdd);
The problem is when I've a quote in "libelle" variable (i've escaped this quote), when I use append, Jquery put only tes in the "value" attribute.
I have to do with simple quote.
For info an alert(toAdd) return me the entire input with no errors.
Any ideas ?
Thanks
If you use jQuery to create the element for you through properties instead of string manipulation you can avoid these kind of problems:
var libelle = 'tes\'te';
var id = 1;
$('<input />', {
type: 'text',
name: 'choix[' + id + ']',
value: libelle
}).appendTo('#test');
Example fiddle
One approach here is to create the element, then set the value on that element. These can be chained together something like:
var libelle = "tes'te";
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' />";
// create the element, show and finally set the value (.val)
$(toAdd).appendTo("#test").val(libelle);
See The Fiddle Here
I have a function that uses:
name = "textBox" + (h) + (j);
id = "textBox" + (h) + (j);
value = hoursEachDay[j-1];
textBox = "<input type='text' maxlength='6' size='6' name='" + name + "'id='"+ id +"' value='" + value + "' onchange='updateHrs()'>";//or parent.updateHrs(j)
(h, i,and j being integers) to call another function that follows directly after the first function. That function is :
function updateHrs()// or updateHrs(dayOfMonth)
{
alert("This is the day changed ");
//or alert("This is the day changed " + dayOfMonth);
return;
}
I get a 'function not defined' error from firebug when I run this and trigger the onchange event handler. I have, on the suggestion of a coworker, changed updateHrs() to parent.updateHrs(), which actually works for some reason, until I try to pass a variable into the updateHrs() function (ass seen commented out above), at which point it declares that updateHrs(j) is not defined.
I am guessing that somehow the updateHrs function is being read as out of scope, although I'm not really sure how. Both of these functions are right after one another and both are right before the tag (yes there is a tag well above them as well), so they should not have a scope issue, not that I'm aware of anyway.
Thanks for any help that you can provide.