Archit Arora
Archit Arora

Reputation: 2636

Make Anchor tag work conditionally using Javascript

I have a Radio button. I want to implement a validation on "Submit" Anchor tag that displays an error if no selection is made on the radio button and redirects to the URL provided in the href attribute if the radio button selection is made.

Below is the code for radio button -

<div>
    <input required="" type="radio" id="group02-0" name="group02" value="Yes" onclick="yesnoCheck();">
    <label for="group02-0" >Yes</label>
    <input type="radio" id="group02-1" name="group02" value="No" onclick="yesnoCheck();">
    <label for="group02-1">No</label>
</div>

<script>
    var radio_value = "";
    function yesnoCheck() {
        radio_value = document.querySelector('input[name="group02"]:checked').value;
    }
</script>

In the same HTML file, I have code for the Submit Anchor tag -

<a href="https://www.google.com" onclick="return submitCheck();"><span>Submit</span></a>

<script>
    function submitCheck() {
        if (radio_value === "") {
            //Display an error. The user should not be taken to the next page
            return false;
        } else {
            //User should be taken to the URL in the href attribute
            return true;
        }
    }
    </script>

Irrespective of whether I make a selection on the radio button, the anchor tag always takes me to the next page. Please help!

Upvotes: 1

Views: 1420

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206344

  • You don't need two radio buttons. Only one Checkbox.
  • Use Event.preventDefault() to prevent default browser navigation
  • Use the input element's checked state to determine the outcome
  • Finally use document.location to navigate to a EL_submitBtn.getAttribute('href')
  • PS: Don't use inline JavaScript (in HTML). JS should be in one place and that's your JS file or inside a <script> tag. It's easier to debug and maintain.

Single checkbox

const EL_submitBtn = document.querySelector('#submitBtn');
const EL_acceptCkb = document.querySelector('[name="accept"]'); 

function submitCheck(ev) {
  ev.preventDefault(); // prevent follow link
  
  if (!EL_acceptCkb.checked) {              // Unchecked
    alert("You will not get a better UX");
  } else {                                  // Checked
    alert("Yes! Buckle up!")
    document.location = EL_submitBtn.getAttribute('href');  
  }
}

EL_submitBtn.addEventListener('click', submitCheck);
<div>
  <h3>Would you like a better UX?</h3>
  <label>
    <input type="checkbox" name="accept"> Yes I do
  </label>
</div>

<a id="submitBtn" href="https://www.google.com">Submit</a>

Two radio buttons

  • Use document.querySelector('[name="accept"]:checked') to get the checked one, if any.

const EL_submitBtn = document.querySelector('#submitBtn');

function submitCheck(ev) {
  ev.preventDefault(); // prevent follow link
  
  const EL_acceptCkd = document.querySelector('[name="accept"]:checked'); 
  
  if (!EL_acceptCkd) {                      // None checked
    alert("You must select Yes or No.");
  } else if (EL_acceptCkd.value === 'no') { // "NO" checked
    alert("You will not get a better UX");
  } else {                                  // "YES" checked
    alert("Yes! Buckle up!")
    document.location = EL_submitBtn.getAttribute('href');
  }
}

EL_submitBtn.addEventListener('click', submitCheck);
<div>
  <h3>Would you like a better UX?</h3>
  <label>
    <input type="radio" name="accept" value="yes"> Yes
  </label>
  <label>
    <input type="radio" name="accept" value="no"> No
  </label>
</div>

<a id="submitBtn" href="https://www.google.com">Submit</a>

Upvotes: 2

Mister Jojo
Mister Jojo

Reputation: 22345

use css pointer-events: none; -> https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

If you absolutely want to use button radios (even if it's a bit twisted as an idea) here is the code:

const aHrefGoogle = document.getElementById('aHrefGoogle');

document.querySelectorAll('input[name=group02]').forEach(el=>
  {
  el.onchange=_=>{ if (el.checked) setLinkOnOff(el.value) }
  })

function setLinkOnOff(val)
  {
  if (val==='yes') { aHrefGoogle.classList.remove('adisableHref') }
  else             { aHrefGoogle.classList.add('adisableHref')    }
  }
.adisableHref {
  color: grey; 
  pointer-events: none;
  cursor: default;
  text-decoration-line: none;
}
make link Google active ?
<label ><input type="radio" name="group02" value="yes">Yes </label>&nbsp;
<label ><input type="radio" name="group02" value="no" checked>No! </label>

<br><br>

<a href="https://www.google.com"  id="aHrefGoogle" class="adisableHref"><span> Google </span></a>

for memo here is the initial code with a checkbox :

const yesnoCheck  = document.getElementById('yesnoCheck')
  ,   aHrefGoogle = document.getElementById('aHrefGoogle')
  ;

// init
yesnoCheck.checked = false
aHrefGoogle.classList.add('adisableHref') 

yesnoCheck.oninput =_=>
  {
  if (yesnoCheck.checked)  { aHrefGoogle.classList.remove('adisableHref')    }
  else                     { aHrefGoogle.classList.add('adisableHref') }
  }
#yesnoCheck  { display: none; }
#yesnoCheck + label { display: inline-block; background: #cd3c3c; color: white; padding: .17em .2em; cursor: pointer; }
#yesnoCheck:checked + label { background: #378b2c; }
#yesnoCheck + label::before { content: 'NO'; display: inline-block; width:2.6em; text-align: center; }
#yesnoCheck + label::after  { content: '';   display: inline-block; width:0;     text-align: center; }
#yesnoCheck:checked + label::before { content: '';    width:0; }
#yesnoCheck:checked + label::after  { content: 'YES'; width:2.6em; }

.adisableHref {
  color: grey;
  pointer-events: none;  
  cursor: default;
  text-decoration-line: none;
}
make link Google active ?
<input type="checkbox" id="yesnoCheck"><label for="yesnoCheck">▉</label>

<br><br>

<a href="https://www.google.com"  id="aHrefGoogle" class="adisableHref"><span> Google </span></a>

Upvotes: 0

Related Questions