Is the JavaScript function executed twice?

I'm a little confused.

I have a flag that the user can click, which determines whether the personal phone number on my page should be visible to everyone or just for administration. When the box clicked, I want to make sure that you are allowed to first print the status of it only for testing purposes. And when I run this function, it runs twice.

I read somewhere else, what is it because of Callbacks? But I return False, so it should not be right?

I am not a JavaScript master, so there are many things that 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 HTML:

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

Any help?

+7
javascript function html events asp.net-mvc
source share
3 answers

This is because the <label> attribute with the for attribute raises the click event of the <input type="checkbox"> element, which is clicked.

You must bind the click event handler to input , not label .

 function ValidateHidePrivate() { alert(); } 
 <label for="HidePrivate" > <input type="checkbox" name="HidePrivate" onclick="ValidateHidePrivate()" id="HidePrivate" value="no" /> Hide my Private Phone Number </label> 
+6
source share

When you click on your shortcut, maybe there is also a flag on the event flag? Try adding event.stopPropagation() inside your function.

+2
source share

Add an onclick event handler to input only. In addition, input nested inside the label.

We hope this piece 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

+1
source share

All Articles