I want to use the state of a checkbox as a parameter to a call of a website.

I.E. there is a checkbox <input type="checkbox" id="myCheck">
and a hyperlink <a href=“/action.php“>newSite</a>

Depending on the state of the checkbox, an additional parameter should be added to the href parameter,
e.g. when not checked: href=“/action.php“
when checked: href=“/action.php?state=checked“

I don’t want to have an extra submit button, but simply by clicking on the link newSite the call to the new website should have the parameter or not depending on the state of the checkbox.

How do I program this in HTML and JavaScript?

3 Replies 3

Could the link be to any website or is it just linking between pages on the same site/origin? If you keep it to the same origin you could also use localStorage to hold the state instead of passing it in the query string/parameter.

You could use an event listener to detect when the input has been clicked, then modify the link url.

const checkbox = document.getElementById('crocodiles');
const webpage = document.getElementById('google');
checkbox.addEventListener('click', function () {
  if (checkbox.checked === true) {
    google.setAttribute('href','https://google.com/?q=crocodiles');
  } else {
    google.setAttribute('href','https://google.com/');
  }
});
<label for="crocodiles">Search about crocodiles?</label>
<input type="checkbox" id="crocodiles" />
<br />
<a href="https://google.com/" id="google" target="_blank">Go to Google</a>

Just FYI, you could do this without any JavaScript, by simply using a form:

<form action="/action.php">
<input type="checkbox" name="state" value="checked">
<button>newSite</button>
</form>

I don’t want to have an extra submit button

This would not need an extra submit button, but just a submit button. And if desired, you could still format that submit button to look like your other links do.

Your Reply

By clicking “Post Your Reply”, 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.