2

I have a <a> link and a checkbox, I want to redirect to the href only if the javascript returns true (the box is checked)

Here is my code :

My javascript file :

function fb_checkbox() {
    if (document.getElementById("checkAGB").checked == false) {
        document.getElementById('notAccepted').style.display = "block";
        return false;
    }else{
        return true;
    }

In my PHP file :

<a href="'.$loginUrl.'" onclick="fb_checkbox();">Sign in with Facebook</a>
3
  • use here onclick="return javascript:fb_checkbox();" instead Commented Mar 14, 2016 at 10:09
  • Doesn't work, the javascript is executed but the redirection works even if I don't check the checkbox Commented Mar 14, 2016 at 10:12
  • onclick="return fb_checkbox();" this would help you here. Commented Mar 14, 2016 at 11:00

3 Answers 3

2

Try using this in the javascript:

function fb_checkbox(url) { ... else{ window.location.href = url; }

And in the PHP side:

<a href="'.$loginUrl.'" onclick="fb_checkbox(this.href);return false;">Sign in with Facebook</a>

And it should work.

Sign up to request clarification or add additional context in comments.

2 Comments

This executes the Javascript but even without checking the box, the href is redirected
I missed: return false; after onclick function call. The full, functional code: <input type="checkbox" id="checkAGB"> <a href="http://www.google.com" onclick="fb_checkbox(this.href);return false;">Sign in with Facebook</a> <div style="display:none" id="notAccepted">Check the checkbox!</div> <script> function fb_checkbox(url) { if (document.getElementById("checkAGB").checked == false) { document.getElementById('notAccepted').style.display = "block"; return false; }else{ window.location.href = url; } } </script>
1

You need to add return in onclick attribute's value.

Try this:

<a href="'.$loginUrl.'" onclick="return fb_checkbox();">Sign in with Facebook</a>

Here's working example:

function fb_checkbox() {
    if (document.getElementById("checkAGB").checked == false) {
        document.getElementById('notAccepted').style.display = "block";
        return false;
    }else{
        return true;
    }
  }
<input type="checkbox" id="checkAGB"/>
<div id="notAccepted" style="display:none">Check the checkbox!</div>
<a href="http://google.com" onclick="return fb_checkbox();">Works</a>

Comments

0

Try like this:

<a href="javascript:void()" onclick="fb_checkbox();">Sign in with Facebook</a>

function fb_checkbox() {
    if (document.getElementById("checkAGB").checked == false) {
        document.getElementById('notAccepted').style.display = "block";
        return false;
    }else{
        window.location.href="<?=$loginUrl?>";
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.