I have 2 buttons that both use the same function, I need it to be able to tell which button I pressed.
On button 1 I put onclick "myFunction(1)" and on button 2 I put myFunction(2) then on myFunction(a) I put if a=1 but it's not working.
<!DOCTYPE html>
<html>
<body>
<!-- CSR -->
<label onclick="myFunction(a.value=1)">CSR</label>
<input type="text" value="Hello World" id="CSRNm"><br>
<!-- Acct# -->
<label onclick="myFunction(a.value=2)">Acct#</label>
<input type="text" value="Hello Other World" id="AccNo">
<script>
function myFunction(a) {
if (a.value=1){
navigator.clipboard.writeText(CSRNm.value);
/* Alert the copied text */
alert("Copied the text: " a.value);
}
else if (a.value=2){
navigator.clipboard.writeText(AccNo.value);
/* Alert the copied text */
alert("Copied the text: " AccNo.value);
}
}
</script>
</body>
</html>
CodePudding user response:
Why are you passing a.value
just pass it as a
as follows:
<button id="btn1" onclick="myFunction(a=1)">one</button>
<button id="btn2" onclick="myFunction(a=2)">two</button>
const myFunction = (a) => {
if (a === 1) {
console.log("a");
}
if (a === 2) {
console.log("b");
}
};
CodePudding user response:
Instead of:
myFunction(a.value=1)
you can use this:
myFunction({value: 1})
The function declaration for myFunction
already refers to the parameter as a
.
So, when you pass the object literal {value: 1}
as the function parameter, the executing function will return 1
when asked for a.value
.