Passing object to onclick - javascript

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.

Related

How to reinitialize a script in an HTML document?

I have a document that uses the jscolor.com library, for the user to be able to select and store a color. I'm also using a JQuery function to add rows to the screen, so the user can create and define a number of colors. The problem is, when the new row is added, the Javascript isn't re-initialized for the added elements.
Here is the code in question:
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<div id='addr" + i + "'>" +
"<div class='col-xs-4'>" +
"<input type='text' name='config_color[" + i + "][css]' id='input-color[" + i + "][css]' class='form-control' />" +
"</div>" +
"<div class='col-xs-2'>" +
"<input type='text' name='config_color[" + i + "][value]' id='input-color[" + i + "][value]' class='form-control jscolor' />" +
"</div>" +
"<div class='col-xs-2'>" +
"<input type='text' name='config_color[" + i + "][default]' id='input-color[" + i + "][default]' class='form-control' />" +
"</div>" +
"<div class='col-xs-4'>" +
"<input type='text' name='config_color[" + i + "][notes]' id='input-color[" + i + "][notes]' class='form-control' />" +
"</div>" +
"</div>");
$('#tab_logic').append('<div id="addr'+(i+1)+'"></div>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
}).trigger('change');
</script>
I've made an simplified example of what I'm talking about on JSFiddle - you can see in the first row, if you click in the color cell, it gives you a pop up color palette.
If you add additional rows, the popup picker doesn't work.
However, all of the data stores in the database properly, so i have an instance where some elements added by Javascript work properly and others don't?
(Also full disclosure, I asked on Reddit first - this is therefore a cross-post.
In their examples, jscolor has one called "Instantiating new Color Pickers" which shows you how to do it.
You're adding the new row as a string, which I wouldn't recommend, because if you created each input separately using jQuery it would be easier to call jscolor() on only one element, but this works too.
Just add the following to your click handler:
// Get all the inputs first
var allInputs = $('.jscolor');
// From there, get the newest one
var newestInput = allInputs[allInputs.length - 1];
// And call jscolor() on it!
new jscolor(newestInput);
Here's an updated fiddle
Generally Abe Fehr answer helped me too, but i had slightly other problem. My elements already had default values from database so
new jscolor(newestInput);
initialized them but with default FFFFF
So in my case twig (html) looks like this:
<button class="jscolor {value:'{{ category.color }}'} btn btn-sm disabled color-picker" data-color="{{ category.color }}"></button>
And then I reinitialize all the colors like this:
let all_pickers = $('.color-picker');
if ($(all_pickers).length !== 0) {
$(all_pickers).each((index, element) => {
let color = $(element).attr('data-color');
new jscolor(element, {'value': color});
});
}

How can i set an element's id as a variable?

I have some jQuery script in which I'm adding some rows to a table (when the user press a button). My problem is that I want to change the id of the elements inside the rows dynamically. I have set a global variable i which I set as an id to some elements inside my table. The problem is that after some debugging I found out that the id doesn't change at all and stays as the letter i (and not the variable i set to 0 and increase every time the user press the button). Any ideas?
var i=0;
var a1=i.toString().concat("1");
var a2=i.toString().concat("2");
var a3=i.toString().concat("3");
$("#table1").append("<tr><td><center><input id=\"a1\"></input></center></td><td>
center><button id=\"a2\">Load</button></center></td><td ><img id=\"a3\"></td>
</tr>");
$("#a2").click(function(){
$z=$("#a1").val();
$("#a3").attr("src",$z);
i++;
});
That's because you're writing those directly as strings. You need to concatenate them into the actual string. You can concatenate strings together using +.
$("#table1").append(
"<tr>" +
"<td>" +
"<center><input id=\"" + a1 + "\" /></center>" +
"</td>" +
"<td>" +
"<center><input id=\"" + a2 + "\" /></center>" +
"</td>" +
"<td>" +
"<center><input id=\"" + a3 + "\" /></center>" +
"</td>" +
"</tr>"
);
For what it's worth, the <center> tag is deprecated and should not be used. You may also consider creating some kind of template rather than generating your HTML as strings directly inside of JavaScript.

Cannot Parse String via JavaScript function

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!

Stringifyed onClick event does not work

I have an event which parses a certain string which contains button name and url.
than I assign the data to a button. and add on click event which suppose to open url in a new window. But this on click event doe not work. The window does not show up. If url was wrong it would open a window and prompt a mistake.
But in my case when I click the botton it does not react. Probably something is wrong with on click event here: onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\". But I can't understand what.
here is the code
<script>
...
var checkType = partArray[0].split("+");
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\" /> "
document.getElementById("demo").innerHTML=outPuts;
</script>
<body>
...
<div id="demo"></div>
...
</body>
partArray[1] is not evaluated; the browser should still open window with the URL specified as "partArray[1]" but I doubt that is what you want. Try adding double quotes and concatenating it when you build your HTML.
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('" + partArray[1] + "', '', 'width=300,height=300');\" /> "
If you provide some more context or code it'd be easier to see what might be going on. Are you sure there is not a popup-blocker getting in the way?

Javascript Parameter Passing Not Working

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>";

Categories