send javascript link when selecting checkbox

Asked

Viewed 297 times

0

Guys I have a checkbox, and I need javascript to send the link according to the checkbox selected.

Example

html:

<input type='checkbox' id='1'>
<input type='checkbox' id='2'>
<input type='checkbox' id='3'>

Javascript

Well the javascrip has to call the following link

http://link do site/index.php?id=(id igual ao do checkbox) 

Does anyone know how to do this with javascript?

  • When do you want the link sent and where? When do you select the checkbox? Can you explain it better?

1 answer

1


You can capture the value of the selected element by navigating the DOM tree.

var elementA = document.getElementById("a");
var elementB = document.getElementById("b");
var elementC = document.getElementById("c");

var urlComplement = "id=";

elementA.addEventListener("click", display);
elementB.addEventListener("click", display);
elementC.addEventListener("click", display);

function display(){
    if(this.checked){
	alert(urlComplement + this.value);
    }
}
<input type="checkbox" id="a" value=1>
<input type="checkbox" id="b" value=2>
<input type="checkbox" id="c" value=3>

There are several better alternatives than the one posted in the example, I strongly recommend reading http://www.w3schools.com/js/js_htmldom.asp, look also on DOM tree manipulation via Javascript will help highly in projects.

  • OK thank you very much

  • ok thank you very much, but the more input I put in the more I have to add in javascript, there is some way to do this automatically, ie no need to add more lines in javascript?

  • There is, you can search for a parent element and navigate through all the child elements by adding the eventListener you want. Doing this right through the DOM tree is a bit of a hassle, Jquery can solve this in a much simpler way than direct DOM manipulation.

  • @Hugoborges It’s actually quite easy to do this, e.g. attribute to inputs the same class and then add the Event handlers in all of them at the same time with document.getElementsByClassName('eventCheckbox').addEventListener("click", display);. If you need a more complex selector use document.querySelector.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.