Reputation:
I am currently passing the ID on buttons to a function. I want to switch from using buttons to using the td in a jQuery table (as soon as I learn how to do so). I want to change to using a class as I want to make each td in a row clickable. Each td in a row will pass exactly the same variable to the function.
So each td in a row will perform exactly the same as the button. Meaning I want to make the td clickable and to call the function. All the td would have the same id (clear - in the example above) and I read it is bad practice to use the same id more than once and might present problems later in my jQuery code. I did read that it is ok to use a class multiple times, hence the attempt to make the change.
For example one button is set as below:
<input type="button" id="clear" style="width:110px;" onclick="return SetShift(this.id)" value="Clear" />
The SetShift function is:
function SetShift(id) {
// Gets/passes the workday shift to/from the localStorage.
const targetStateValue = localStorage.getItem('shiftstatus');
if (targetStateValue === null) {
localStorage.setItem('shiftstatus', id);
} else {
localStorage.setItem('shiftstatus', id);
}
}
I tried to change the id to class, but I get the following errors:
Uncaught SyntaxError: Unexpected token class
Uncaught ReferenceError: SetShift is not defined
at HTMLInputElement.onclick ((index):36)
Upvotes: 1
Views: 62
Reputation: 8481
Is it possible to pass a class to a Javascipt function?
Yes, you can use className property to do it:
function setShift(className) {
console.log(className);
}
<table>
<tr>
<td class="first" onclick="setShift(this.className)">First</td>
<td class="second" onclick="setShift(this.className)">Second</td>
<td class="third" onclick="setShift(this.className)">Third</td>
</tr>
<table>
Upvotes: 2
Reputation: 12900
As mentioned in the comments, class
is a reserved name in JavaSript (see this)
What you can do is this:
function SetShift(evt) {
console.log('className', evt.target.className);
}
<button class="clear" onclick="SetShift(event)">
Click me
</button>
Note that if you have multiple classes, you'll need to use classList.contains
Upvotes: 2