Stringifyed onClick event does not work - javascript

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?

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});
});
}

Getting values outside a HTML form

Inside my content.js I am writting a new HTML page with a pre polulated form, which contains var a and var b. Those 2 variables are created before, inside content.js, so I can easily use them inside my HTML page. Now I want to override those variables a and b as the user finishes editing the form and presses the button Accept. Is there anyway I can achieve this?
This is a part of the code
var a="FName";
var b="LName";
var myWindow = window.open("Accept", "myWindow", "width=450, height=300");
myWindow.document.write(
"<html>"+
"<head>"+
'<script> function closeWindow(){ var x = document.getElementById("firstname").value alert(x); window.close();}'+
"</script>"+
"</head>"+
"<body>"+
"<form>"+
"<div id=leadinformation>"+
"<p id=titleParagraph>You are about to create a new Lead:</p>"+
"First Name....."+ "<input type=text id=firstname value="+a+">" +"<br>"+
"Last Name....."+ "<input type=text id=lastname value="+b+">" +
"</div>"+
"<div>"+
"<button id=Accept onClick=closeWindow() >Accept</button>"+
"<button id=Close onClick=closeWindow() >Close</button>"+
"</div>"+
"</form>"+
"</body>"+
"<html>"
);
myWindow.document.getElementById('Accept').onclick=Accept;
myWindow.document.getElementById('Close').onclick=Close;
function Accept(){
alert(myWindow.document.getElementById('firstname').innerText);
}
function Close() {//do smthing
}
Sorry for bad formating.
Currently the output of the Accept(); is empty at the moment. How can I get first name input result?
What I want to achieve:
1) I am creating a button on a page
2) When I click on the button a new html page pops out (the one that I am hardcode writing it)
3) I pre populate the form with some variables that I created before
4) When Clicking The Accept button on the form the Accept() function is triggered where I would want to use those input values the user has written.
This should help you: Sharing global javascript variable of a page (...).
The question is about "How to share a variable to another page in an iframe", but this works for a new windows as well.
i.e.:
myWindow.document.write(
"<html>" +
"<head>" +
'<script>' +
'function closeWindow(){' +
'var x = document.getElementById("firstname").value;' +
'alert(x);' +
'// do something to parent.a and parent.b here, just because you can:' +
'parent.a = "Oh, would you look at it, it works!";' +
'parent.b = "And it is so pretty too!";' +
'window.close();' +
'}' +
"</script>" +
"</head>" +
" Your body code here, etc " +
"</html>"
);
Also, please note that your code lacks a semicolon (;) after inserting value to var x in your new window's JavaScript code. That will most probably make your code malfunction. The closing </html> tag lacks the slash, but I don't know if that's gonna break anything; you'd better fix that as well, just in case.

How to add Call a phone number link in innerHTML

I am trying to add a call specific phone number using <a href> tag inside innerHTML. I've tried with double and single quotes.
1st Case is not firing at all.
2nd Case it does appear but when clicking on the phone number rather than dialing it closes.
var popDiv = document.createElement('span');
popDiv.setAttribute('class', 'popDiv');
popDiv.innerHTML ="It seems you are looking for: " + "<span style='color:#FF0000'>" + getTitle + "</span>" + "<br />" + "Why don't you call me?" + "<a href='tel:01234567890'>01234 567 890</a>";
Please find link to the JSFiddle
Does anyone know what a possible solution would be?
You need to check the mouseup event's target and if it's h1, then only remove the popDiv. This should work :
$("#"+parentContainerId).on('mouseup', function(e){
if(event.target.tagName.toLowerCase() === 'h1') {
$('span.selectedText').contents().unwrap();
$(this).find('span.popDiv').remove();
}
});
Updated jsFiddle
Just try with that :
var popDiv = document.createElement('span');
popDiv.setAttribute('class', 'popDiv');
popDiv.innerHTML ="It seems you are looking for: " + "<span style='color:#FF0000'>" + getTitle + "</span>" + "<br />" + "Why don't you call me?" + "01234 567 890";
and be sure you have not any meta like that :
<meta name = "format-detection" content = "telephone=no">

Passing object to onclick

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.

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