jQuery, how do I call a url by checking a checkbox

javascript, jquery

Solution

I am not sure what you are going for. If you want to redirect to a page on clicking on the check box you can do this

Specify what url you want to call in your checkbox element using data attribute

<input type="checkbox" data-target="http://www.facebook.com" />

Script is

$(function(){
  $("input[type='checkbox']").change(function(){
  var item=$(this);    
  if(item.is(":checked"))
  {
    window.location.href= item.data("target")
  }    
 });
});

Sample JsFiddle : http://jsfiddle.net/45aZ8/2/

EDIT : If you want to open it in a new window, use `window.open` method instead of updating the current url

Replace

window.location.href= item.data("target")

with

window.open(item.data("target")

http://www.w3schools.com/jsref/met_win_open.asp

EDIT 3 : Based on comment : If you want to load one url on Checked state and load another url on uncheck, you can do like this

Give 2 data attributes for each checkbox. One for checked state and one for unchecked

Facebook<input type="checkbox" data-target="http://www.facebook.com" data-target-off="http://www.google.com"  /> <br/>
Twitter<input type="checkbox" data-target="http://www.twitter.com" data-target-off="http://www.asp.net"  /> <br/>

And the script is

$(function(){
  $("input[type='checkbox']").change(function(){
  var item=$(this);    
  if(item.is(":checked"))
  {
       window.open(item.data("target"))   
  }
  else
  {
      window.open(item.data("target-off"))   
  }        
 });
})

Working sample : http://jsfiddle.net/45aZ8/5/

Problem

I have this: ``` <span id="social"> Facebook: <input id="id_connected_to_facebook" type="checkbox" name="connected_to_facebook"> <br> Twitter: <input id="id_connected_to_twitter" type="checkbox" name="connected_to_twitter"> <br> </span> ``` and with jQuery I would like to call a different URL for all the 4 possible actions (1: check facebook, 2: uncheck facebook, 3: check twitter, 4: uncheck twitter). How would I do that?

Original source