Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Function is run twice?

I'm a little bit confused.

I have a checkbox that a user can click which determines whether a Private Phone number on my page should be visible to all or only the administration. When the box is clicked I wanna make sure you are allowed to first then print the state of it just for testing purposes. And when I run this function, it's run twice.

I read somewhere else that it's because of Callbacks? But I am returning False so this shouldn't be the case right?

I am not a JavaScript wizard so there are many things I still don't know about JavaScript and its interaction with ASP.

/**
* Used to Check whether a Private Phone number should be hidden or shown.
*/
function ValidateHidePrivate() {
    if (scope["pickeduser"] != scope["credential"]) {
        alert("Not allowed");
        return false;
    } else {
        alert(document.getElementById("HidePrivate").checked);
        return false;
    }
}

And the HTML:

<label for="HidePrivate" onclick="ValidateHidePrivate()">
    <input type="checkbox" name="HidePrivate" id="HidePrivate" value="no" />
    Hide my Private Phone Number
</label>

Any help?

like image 470
OmniOwl Avatar asked Apr 20 '17 07:04

OmniOwl


1 Answers

It's because a <label> with a for attribute raises the click event of <input type="checkbox"> element that is associated for when clicked.

You should bind click event handler to input, not to label.

function ValidateHidePrivate() {
      alert();
}
<label for="HidePrivate" >
    <input type="checkbox" name="HidePrivate" onclick="ValidateHidePrivate()" id="HidePrivate" value="no" />
    Hide my Private Phone Number
</label>
like image 153
Mihai Alexandru-Ionut Avatar answered Oct 04 '22 11:10

Mihai Alexandru-Ionut