Reputation: 359
I'm just wondering which of these is correct syntax wise?
<input type = "button" onclick = alert("Hi")>
<input type = "button" onclick = "alert(‘Hi’)"> //this one?
I feel like I've read both formats somewhere, and I'm just wondering which is actually correct? Thanks!
Upvotes: 0
Views: 82
Reputation: 943843
The first example is invalid HTML. "
characters are not allowed in unquoted attribute values.
The second example is invalid JavaScript. Strings must be delimited with '
or "
, not `
Syntactically correct options include, but are not limited to:
<input type="button" onclick="alert('Hi')">
<input type="button" onclick="alert("Hi")">
<input type="button" onclick='alert("Hi")'>
Modern JavaScript (as opposed to late 1990s style JavaScript) would use JavaScript to bind the event handlers.
<input type="button">
with
function myFunction(event) {
alert("Hi");
}
document.querySelector('input').addEventListener('click', myFunction);
With class and/or id attributes added to the input and a more specific selector passed to querySelector
as needed.
Upvotes: 1
Reputation: 396
While binding events inline is no longer advised, there's not really a correct syntax in terms of single quotes vs. double quotes in this attribute.
Either of these would be acceptable (again, using attributes like onclick="" attribs is the old way of binding events):
<input type="button" onclick="alert('hi')">
<input type="button" onclick='alert("hi")'>
Swapping out double quotes with single quotes (or visa versa) is fine.
The more semantic way of doing this would be to dynamically bind an event listener to the element. Your HTML would look something like this:
<input id="mybutton" type="button">
And your JS would look something like this:
function mybutton_function() {
alert('hi');
}
var mybutton = document.getElementById('mybutton');
mybutton.addEventListener('click', mybutton_function, false);
Upvotes: 1