what happen when you use onclick={} instead of onclick=""? - javascript

<script>
function hello(val)
{
alert(val);
}
</script>
<button onclick="hello('hello')"">hello</p> <!-- works and prints hello -->
<button onclick={hello()}>hello 2</button> <!-- works and prints undefined -->
<button onclick={hello("hello3")}> hello 3</button> <!--also works even though intellisence put a squigly red line under the first quote "-->
<button onclick={hello("does not work")}> hello 3</button> <!-- does not work, error is show in console Invalid or unexpected token -->
I know that inline js should be treated carefully, im trying to explain that to other people with this example, however i dont what is happening underneath.
My explnation is that if you change something that is expected you would get undesired results, however i feel that my explanation is superficial and not enough, so could someone explain what is happening underneath that is casuing this wierd behaviour?

If it is only about HTML and no framework is involved, then what you observe is partially explained in HTML attribute with/without quotes
An attribute value can either be enclosed in " or ' or consist of a value that is not enclosed by quotes, and such a value must not contain spaces.
So <button onclick={hello()}>hello 2</button> it is equivalent to <button onclick="{hello()}">hello 2</button> and onclick has the value {hello()}, which is valid JS (the hello() is just within a block).
For <button onclick={hello("does not work")}> the value ends at the first space so it is equivalent to <button onclick="{hello("does" not="" work")}="">, there onclick has the value {hello("does and that's not valid JS.

Related

Reading/Displaying different text files with one function in jQuery

I'm trying to build a notary of sorts. This notary will have different buttons and with the press of each button a different message of plain text will display in a custom div. I want all buttons to display different messages, but display them in the same div and when a different button is pressed, the former message will fade away and the new message will fade in.
I have a basic understanding of the jQuery.get() and this is my JS and HTML code that I've used to read/display one file in that custom div by clicking the button labeled "First":
function Answer() {
jQuery.get("file.txt", function(text) {
$(".answerBox").text(text);
})
};
<body>
<div class="content">
<div class="buttons">
<button class="button" type="button" onclick="Answer()">First</button>
<button class="button" type="button" onclick="Answer()">Second</button>
</div>
<div class="textBox">
<div class="answerBox">Click Any Question Button</div>
</div>
</div>
</body>
The issue comes when clicking the button labeled "Second", it reads the same file.txt and displays the same message. I am puzzled as to how I can expand this single function to encompass all 300 some odd buttons I will need and yes, each button will display a different message and will be tied to a different txt file. I really don't want to rewrite this small function 300 some times and I know there is a better way I just cannot find it.
So I've just asked this question, but I've been digging a bit more and I think I may have found something useful. I've rewritten my JS function and HTML as:
`function Answer(file) {
let list = [];
url = "files/" + file
list.push(url);
if (list.includes(url)) {
jQuery.get(url, function(text) {
$(".answerBox").fadeOut(() => {
$(".answerBox").text(text);
})
$(".answerBox").fadeIn(2000)
});
<div class="buttons">
<button class="button" type="button" onclick="Answer('file.txt')">First</button>
<button class="button" type="button" onclick="Answer('file1.txt')">Second</button>
</div>
`
This kinda solves my initial problem, but now I will need to make 300 instances of buttons in HTML. Is there any other way or is this the best I can do with what I know?

HTML tags inside string literal are not being passed to JS method correctly

So I have read from a JSON file. And I can easily get the name value and photo_url value and some of the bio for each "person".
https://codepen.io/lpmurray16/pen/ExvpQgP
This is where the JSON is:
https://bensdemo.prod.equisolve-dev.com/api/v1/eq-test
So in the JavaScript file found within the codepen linked above (sorry for the formatting it does that every time I save...), but lines 23-40 is a function that gets called onClick for the class "card" and the button tag in these lines below... I pass the arguments into this function as ${person.arg} and you can see it works for some of the people because when you click on the first three people it opens the modal with the correct information in every spot. But in one of the person.bio within the JSON it breaks due to a delimiter on an anchor tag like this --> ".
Am I missing something obvious? This is as close as I get without ripping my hair out. And the error message is just Uncaught "SyntaxError: Invalid or unexpected token" on line 1 of the HTML file. Which doesn't help at all? Am I missing a closing tag or something?
document.getElementById("cards").innerHTML = `
${allData.map(function (person) {
let regex = /[_\*#"]/g;
return `
<div class="card flex-col"
onClick="changeModalContent('${person.name.replace(regex,"")}',
'${person.title}','${person.photo_url}', '${person.bio}'); modal.open();">
<div class="card_top">
<img class="prof_pic" src="${person.photo_url}"
alt="${person.name.replace(regex, "")}"/>
</div>
<div class="card_bottom flex-col">
<h3 class="prof_name">${person.name.replace(regex, "")}</h3>
<p class="prof_title">${person.title}</p>
<button class="view_button"
onClick="changeModalContent('${person.name.replace(regex,"")}',
'${person.title}', '${person.photo_url}', '${person.bio}');
modal.open();">View Bio
</button>
</div>
</div>
`;
}).join("")}
`;
The problem is not the double quotes in the anchor tag, it's the \r\n in your source json. You can tell because the entry for Sam Darnold does not have any "s in it. You'll need to sanitize the carriage return and line-feeds out first.
Update your regex to be:
let regex = /[_\*#"\r\n]/g;
Then replace both instances of:
${person.bio}
with:
${person.bio.replace(regex, "")}
Now your code will render correctly as you can see in the working codepen.

Incorrect JavaScript Parameters Syntax

I'm trying to use JavaScript parameters in a function, but I'm not writing the syntax correctly.
This function is supposed to revert information in objects with the aa tag into whatever is specified with ba.
function myFunction(aa, ba){
document.getElementById(aa).innerHTML = ba;
}
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick="myFunction(demo, My First Javascript)">Click Me!</button>
Add single quotes around the inputs to your function:
Javascript:
function myFunction(aa, ba){
document.getElementById(aa).innerHTML = ba;
}
html:
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>
here's a link to a codepen.io demo:
https://codepen.io/167141162/pen/Vrgvbg
Strings in JavaScript must be wrapped in either "" or ''. In your example, JavaScript will think that you are trying to pass a variable (or a function) called demo for the first argument, and the second one (My First Javascript) will throw a SyntaxError.
So, this will work:
function myFunction(aa, ba){
document.getElementById(aa).innerHTML = ba;
}
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>
Wrap your string parameters in single quotes
<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>
Your parameter << demo >> must be in single quotes, because in the js file the parameters take it as strings
<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

How to highlight Javascript missing brackets calling function

In the following HTML/Javascript snippet, I'm missing the function's brackets in the onclick statement (it should read: onclick="showMessage()").
How could I get the missing brackets highlighted
(a) in Notepad before I display the page.
(b) in my Browser JS console after I display the page?
If this is not possible besides inspection, is there another way I could identify this issue more easily?
<html>
<head>
<script>
function showMessage() {
document.getElementById("messageArea").innerHTML = "Hello World";
}
</script>
</head>
<body>
<input type="button" value="Show message" onclick="showMessage">
<div id="messageArea">---</div>
</body>
</html>
The problem is onclick takes any kind of javascript expression, function execution being one of them. For example:
<script>
var a = 10
</script>
<!--All are valid and don't throw any errors -->
<button onclick="a">Nothing happens</button>
<button onclick="a++">Increment</button>
<button onclick="alert(a)">Check value</button>
<button onclick="undefined">Surely Not?</button>
Executing functions like showMessage() is one of it's primary use. And technically it's not an error to have a showMessage without the () inside the onclick. showMesage is just function definition, If you were to type showMessage and press enter in your browser's console, it will simply return the function definition and won't throw any error. So IDEs don't underline it as an error because it's not an error.
I don't know of any tool that will look at html attributes for possible errors like this.
However, if you move all of your javascript code to a separate file, you can use a tool like eslint to check for common errors.
So in this case, instead of using the onclick attribute in your HTML, you'd use javascript to select the element and add an event listener.

How to fix IE9 throwing SCRIPT1028 error, using AngularJS?

I use AngularJS in my single-page application. Somewhere I have defined a button like this
<button class="btn btn-success" onclick="doSeekTo({{todo.position}});doPlay();">
This button, when clicked, invokes the javascript function with the given parameter in double curly braces, as usual with AngularJS.
This all works well in IE9, but when looking at the error console, it says “Expected identifier, string or number” at the position of my curly braces.
How to get rid of this error? It makes me feel uncomfortable.
In Angular, you're not supposed to use the built in onclick event, but rather Angular's ng-click event. That way you can write
ng-click="doSeekTo(todo.position);doPlay()"
IE9 is parsing the HTML before your angularjs code modifies it. Maybe some indirection like this would help ...
<button class="btn btn-success" paramvalue="{{todo.position}}" onclick="doSeekTo(this.paramvalue);doPlay();">
Another option is to enclose the {{}} in single quotes such that IE interprets it as a string:
<button class="btn btn-success"> onclick="doSeekTo('{{todo.position}}');doPlay();">

Categories