10

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?

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
OmniOwl
  • 5,477
  • 17
  • 67
  • 116

3 Answers3

9

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>
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
4

When you click your label, may it be there is event click runs also on checkbox? Try to add event.stopPropagation() inside your function.

Brissy
  • 349
  • 1
  • 2
  • 10
1

Add onclick event handler in only on input. Also the input is nested inside label .

Hope this snippet will be useful

HTML

<input type="checkbox" name="HidePrivate" id="HidePrivate" value="no" onclick="ValidateHidePrivate()" />

<label for="HidePrivate">
  Hide my Private Phone Number
</label>

JS

function ValidateHidePrivate() {
  // rest of code
}

DEMO

brk
  • 48,835
  • 10
  • 56
  • 78