href linked to javascript function not working - javascript

In the simplified code below the href is linked to a custom javascript function (MyFunction). When clicking on the link ('link text') nothing happens (while I'd expect an alert message 'Hello world') and the console shows an error 'Uncaught SyntaxError: Unexpected token !' at the start of the document, which I (also) dont understand.
Just wondering what is wrong in the code below (?)
<script type="text/javascript">
function MyFunction(message){
alert(message);
}
$(document).ready(function(){
var message="Hello world";
$('#myDiv').html('<a id="myLink" href="#" onclick="MyFunction('+message+');">link text</a>'); //looked at the example solution at http://stackoverflow.com/questions/1070760/javascript-function-in-href-vs-onclick
}); //$(document).ready
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
</html>

You string for the creating of the a tag will evaluate to this:
<a id="myLink" href="#" onclick="MyFunction(Hello world);">link text</a>
So it will be thrown an exception. You can quote the parameter like many people said:
onclick="MyFunction(\'' + message + '\');" // onclick="MyFunction('Hello World!');"
Or you can do it the right way:
$('#myDiv').append('<a id="myLink" href="#">link text</a>').on('click', 'a', function(e)
{
alert(message);
});
In this case, message must be declared in the global scope in order to work. Fiddle.
UPDATE: Now, why I think the second one is better:
The html() method espects the following parameter:
A string of HTML to set as the content of each matched element.
And the append() method accepts as the first parameter:
DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
So you can see that append() espects a DOM element/tree to be appended to the element while html() espects only an string, like innerHTML for pure JavaScript. You just don't add elements to a element with innerHTML, you have to create them, that is what append() does.
Then, as the element is now added to the dom tree, you can set it's events with on() replacing your inline event on the HTML tag. See here or here why.

String literal should be quoted, even inside quoted code. The problem is you need it to be quoted too much: String literal (1) inside attribute (2) inside string with HTML (3).
With such deep nesting different problems arise. I faced them literally yesterday. I didn't finish with exact test case, but it seems, that even using " leads to bugs in Chrome.
Hence I'd suggest a workaround: put a message into the attribute:
$('#myDiv').html(
'<a id="myLink" href="#" ' +
'data-message="' + message.replace(/"/g, """) + '"' +
'onclick="MyFunction(this.getAttribute(\'data-message\'));">' +
'link text</a>'
);
Solution by #DontVoteMeDown is even better, and not only because it "attacks" the problem from completely different direction, eliminating the need of escaping/quoting.
My technique is useful, when one need to have different context for different elements even with attaching event handlers via DOM level 2 / jQuery.

Quote the parameter:
onclick="MyFunction('"+message+"');
Else it looks for a variable with the text from message

You're running into two separate quoting issues at the same time. Currently your code will output this:
<a id="myLink" href="#" onclick="MyFunction(Hello world);">link text</a>
Which isn't correct because JavaScript is going to try to interpret Hello world as objects (notice it has no quotes):
MyFunction(Hello world);
Thus, you need to surround it in quotes. However, if you try that:
'<a id="myLink" href="#" onclick="MyFunction("'+message+'");">link text</a>'
Then the resulting markup won't be parseable:
<a id="myLink" href="#" onclick="MyFunction("Hello world");">link text</a>
Because the double-quotes will confuse it. It'll try to end the onclick attribute at the first parenthesis and then encounter an unexpected Hello token.
(Note the syntax highlighting here on Stack Overflow identifies the problems in both examples.)
So you also need to use single-quotes, and in order to do so in an already single-quoted string, you need to escape them:
'<a id="myLink" href="#" onclick="MyFunction(\''+message+'\');">link text</a>'

Related

How do I click this link using nightmare?

Here is everything involving the link:
<a class="" data-images="{"detail_url":"//assets.supremenewyork.com/148393/ma/hBwFmRXhVKI.jpg","zoomed_url":"//assets.supremenewyork.com/148393/zo/hBwFmRXhVKI.jpg"}" data-style-name="Black" data-style-id="19033" data-sold-out="false" data-description="null" href="/shop/bags/lkav6jh17/xfdbgpiea" data-no-tubolink="data-no-tubolink"><img width="32" height="32" src="//d17ol771963kd3.cloudfront.net/148393/sw/hBwFmRXhVKI.jpg" alt="Hbwfmrxhvki"></a>
I use nightmare with node coded in atom and would like to click on the black bookbag from the url: http://www.supremenewyork.com/shop/bags/lkav6jh17/p9ylgt8vm
using the "data-style-name="Black" found in the elements.
I've tried:
.click("data-style-name ='Black'")
which gave me the error:
Failed to execute 'querySelector' on 'Document': 'data-style-name ='Black'' is not a valid selector.
Not sure what to do to click but any help would be great. The link is an image and part of a list element on the webpage.
first grab the DOM node and assign to a variable then click on the node. Also you need to add brackets around the selector and don't need the inner single quotes unless there is a space or other invalid character in the value
var myLink = document.querySelector("[data-style-name=black]");
.click(myLink)
Also what I did was:
.click('a[data-style-name="Tan"]')
I specified it was an attribute and it worked.

html anchor tag's onclick was not working

I was generating a table dynamically.
Inside the td data , there is a hyperlink.inturn it should call a function.
why the below code snippet was not working. Nothing happening when i click on the link.
<a href='#' onclick='function(){alert('hiii');}'>
It's because of conflicting ' and a funciton definition instead of call (thanks #user1389596):
<a href='#' onclick="alert('hiii')">
that should work. The extra 's inside of the onclick made the browser view it as the end of the onclick attribute, which isn't what you want. This way, using two different types of quotes, it works fine.
Or, even better, don't use inline handlers:
<a href='#' id="thethingy">
<!--in a galaxy far, far away:-->
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('thethingy').addEventListener('click',function(){
alert('hiii');
},false);
},false);
</script>
Event handlers added via innerHTML will not trigger in some cases for security reasons. It's also incorrect to include function () since all this onclick would do is define an anonymous function and do nothing else. You also have conflicting quotes.
If you are using jQuery, event delegation would make this simpler. Exclude onclick entirely and use something like:
$(document).on("click", "a", function () { alert("hiii"); });
document and a selectors should be as specific as possible.
You can also bind events to elements added to the DOM as needed.
1st Issue
onclick='function(){alert('hiii');}'
This seriously is wrongly coded as per the use of quotes. The proper usage should be any of the following
Proper use of quotes
onclick='function(){alert("hiii");}'
or
onclick="function(){alert('hiii');}"
This much only about the syntax. But there is still something to be done to actually call the function at runtime. Without proper invocation the function will not be executed. That is the 2nd issue.
2nd Issue
Now there are 2 syntax that you may follow to actually execute the function at runtime.
1st syntax:
(function(){...})();
So the code should be-
onclick="(function(){alert('hiii');})();"
Fiddle Demo1
2nd syntax
new function(){...};
So the code should be-
onclick="new function(){alert('hiii');};"
Fiddle demo2
You are defining a function... not calling it.
try this:
<a href="javascript:alert('hi');">
You should not use onclick="function(){alert('hiii');}". You may try this code:
<a href="#" onclick="alert('hiii');">
<a onclick='function(){alert('hiii');}' href='#' >
try this one it will work without any problem, no need for event listeners
Although this a quotes problem. Following will solve your problem.
<a href='#' onclick="alert('hiii')">
In case you are using Vue.js like me onclick will not work. You can use this.
<a href="javascript:void(0);" #click="alert('hiii')">
Maybe this can be of help to someone,
At first I thought it was due to the fact that href was present, and inserted before the onclick event.
However here is a sample of an a tag that calls a function and passing a parameter.
Both Samples has the onclick event and href properties in different orders.
function helloWorld(message){
alert('Hello world! : ' + message);
};
Click Me (href then onclick)
<br>
<br>
<a onclick="helloWorld('onclick before href')" href="#">Click Me (onclick then href)</a>
};

Passing apostrophe to javascript function

I am not finding a solution on this one using JavaScript (to utilize localStorage) in a JSP.
Trying to pass something with apostrophe. I have done a .replaceAll() and replaced the ' with ' and it still passes it as an '.
I have also tried a .split("'") and replaced the apostrophe with:
(\' , ' , \', '' , ''' and '\'')
All of these just pass an apostrophe to the function (what I see when I hover over the link) like this:
Save job
With a and b being the two split substrings but with no effect. I do notice that spaces are converted into %20, but that's little comfort. Any other ideas?
Your JSP code is irrelevant. Decide what HTML you want to produce and produce it.
The following are all valid HTML markup:
<a href="saveJob('Bob\'s Question')"> …
<a href="saveJob("Bob&apos;s Question")"> …
<a href="saveJob('He said "Go Away"')"> …
<a href='saveJob("He said \"Go Away\"")"> …
… and the following are invalid:
<a href="saveJob('Bob's Question')"> <!-- JS string ends early -->
<a href="saveJob("Bob's Question")"> <!-- HTML attribute ends early -->
<a href="saveJob('Bob&apos;s Question')"> <!-- JS string ends early -->
<a href="saveJob('He said "Go Away"')"> <!-- HTML attribute ends early -->
You cannot use your HTML attribute delimiter in your attribute value except as an HTML entity. You cannot use your JavaScript string delimiter in your JavaScript string unless you escape it, even if you use an HTML entity to describe it.
In general, you should not be putting JavaScript in your HTML (you should attach event handlers to your markup programmatically, from script), and you especially shouldn't be abusing an HTML anchor as a JavaScript trigger (either use an HTML anchor to a valid URL and let JavaScript hijack the link if enabled, or use a <button> or other element to invoke script-only side effects).
As you've noticed, such manual string escape tasks can be quite tricky; covering apostrophes won't even get you all the way: what if there's a newline in the string? That would break the script as well.
I would recommend converting your data to a JSON object, perhaps using JSON-taglib. This should take care of all required escaping for you.
The Phrogz solution
<a href="saveJob("Bob&apos;s Question")">
works fine if you have only apostrophes in your text.
If your text contains both apostrophes and quotes, you can use a hidden div (div with style='display:none;') for the text, pass the id of the div to saveJob instead of passing the text itself, and get the text inside saveJob by using
document.getElementById(myId).innerHTML

Javascript innerHTML with onclick not working

I have some AJAX, it pulls in the following, which is added to a div using innerHTML.
Add
Then when I press the "Add" link, it will add "TEST" into textareax.
If I have it in the HTML of the document from the start, it works perfectly, but when I pull it in using AJAX and using innerHTML to add it to the div the "Add" link does not work.
I think it might be a problem because it has javascript in it and I am just adding it using innerHTML, but don't know how to solve this.
\r\n is a newline, but is parsed by JavaScript already. The innerHTML will be set to:
<a href="#" onclick="javascript:document.getElementById('textareax').value += '
TEST';">Add</a>
which does not work (a syntax error; JavaScript strings cannot have literal newlines).
You'd need to double-escape with \\r\\n so that it becomes \r\n when it is parsed by JavaScript (\\ becomes \ and the r will be unaffected). Then the \r\n will be kept in the onclick handler, so that the newline is indeed added to the textarea: http://jsfiddle.net/r6bhE/.
onclick="javascript:document[...] is incorrect syntax. The onclick attribute is a javascript event, and doesn't need the javascript scheme indication. You can just place the script directly into the attribute value:
Add
It's also a good idea to return a value when intercepting mouse events (true to pass the event on, false to cancel it).

JavaScript within an <a> tag, nested, quote problem

Here is simple <a> tag, which links to an exe file. The onClick JavaScript event redirects the user to another webpage after 3 seconds.
<a href="http://www.example.com/download.exe"
onClick="setTimeout('window.location="/downloading.html"',3000);return true;">
LINK</a>
So it doesn't work because there are too many nested quotes.
The first quotes "" are for the onClick function.
The second quotes '' are for the SetTimeout function.
I need third quotes for the window.location function. I've tried using both ' and " but none work. The above syntax fails.
I can solve it by refactoring the JavaScript into a function, but there are reasons why I cannot implement that. Is there a solution to this?
EDIT:
The answers below did not quite work, but led me to the correct solution:
onClick="setTimeout('window.location=\'/downloading.html\'',3000);return true;"
You need to escape the quotes:
Something
You need to escape the inner double quote with backslash.
Here is the example:
<a href="http://www.example.com/download.exe"
onClick="setTimeout('window.location=\"/downloading.html\"',3000);return true;"</a>

Categories