Bastian
Bastian

Reputation: 5855

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

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?

Upvotes: 3

Views: 8350

Answers (3)

Shyju
Shyju

Reputation: 218722

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/

Upvotes: 9

core1024
core1024

Reputation: 1882

$('#id_connected_to_facebook, #id_connected_to_twitter').click(function(){
   $.post('http://target.url', {this.id:this.checked});
});

now you'll get in $_POST either id_connected_to_facebook or id_connected_to_twitter and as a value it would be 1 or 0

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

$('input[type="checkbox"]').change(function() {
  if($(this).is(':checked')) {
     if($(this).attr('id') == 'connected_to_facebook') {
        // possibility: 1
     } else {
       // possibility: 3
     }
  } else {
    if($(this).attr('id') == 'connected_to_facebook') {
       // possibility: 2
     } else {
       // possibility: 4
     }
  }
});

Upvotes: 0

Related Questions