user8481790 user8481790 - 2 months ago 20
HTML Question

How to open different URLs by checkbox?

This is my HTML and JavaScript code

<input type="text" id="text" />
<input type="button" id="btn" value="Submit" onClick="javascript: window.open('http://example.com/' + document.getElementById('text').value);" />


If you input
anytext
in the form box and click on the Submit button, it will open
http://example.com/anytext
.
I want to add three checkbox named
page1
page2
and
page3
under the form. If I click on the checkbox
page1
and click on submit button, it will open
http://example.com/page1/anytext


How can I do it?

Answer Source

You could create a function that processes the value of the checkboxes and returns the string that you need to insert into the window.open call. Something like this:

onClick="javascript: window.open('http://example.com/' +getRadioValue() + document.getElementById('text').value);"

Also, note that the snippet won't redirect you when you click submit due to the sandbox restrictions on it, but you can see the error in browser console and the page the code attempts to redirect you to.

function getRadioValue () {
  var cb1 = document.getElementById("cb1");
  var cb2 = document.getElementById("cb2");
  var cb3 = document.getElementById("cb3");
  
  if(cb1.checked) {
    return "Page 1/";
  } else if(cb2.checked) {
    return "Page 2/";
  } else if(cb3.checked) {
    return "Page 3/";
  } else {
    return "";
  }
}
<input type="text" id="text" />
<br/>
<label>
<input type="checkbox" value="Page 1" id="cb1" />
Page 1
</label>
<br/>
<label>
<input type="checkbox" value="Page 2" id="cb2" />
Page 2
</label>
<br/>
<label>
<input type="checkbox" value="Page 3" id="cb3" />
Page 3
</label>
<br/>
<input type="button" id="btn" value="Submit" onClick="javascript: window.open('http://example.com/' +getRadioValue() + document.getElementById('text').value);" />