2

I am trying to send a checkbox value via ajax to send data to a external function.

I have the function working using the following javascript, however it is very messy as i am currently writing this javascript function for every instance of script which exisits.

<form>
<input type="checkbox" name="event_status" id="event_status1455" value="1" <?php echo ($event_status == '1' ? 'checked="checked"' : '') ?>>
</form>

<form>
<input type="checkbox" name="event_status" id="event_status1456" value="1" <?php echo ($event_status == '1' ? 'checked="checked"' : '') ?>>
</form>

<form>
<input type="checkbox" name="event_status" id="event_status1457" value="1" <?php echo ($event_status == '1' ? 'checked="checked"' : '') ?>>
</form>

<script>
 $('input:checkbox').change(function(e) {
e.preventDefault();
var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
$.ajax({
          type: 'POST',
          url: '<?php echo $this->url('/profile/list', 'event_status', $cobj->getCollectionID())?>',
        data: { event_status:$("input:checkbox").attr("id"), event_status:isChecked }
});        
});
</script>

As you can see above the javascript will only respond to this particular checkbox. i cannot figure out how to code it so that i have one javascript function on my page that will run for each checkbox i have.

I Have tweaked the code from my original post. I have my ajax doing what i want, however the ajax function only executes for the last checkbox, is their away i can transform the javascript to to do provide the function for each checkbox?

Gismmo
  • 329
  • 4
  • 12

2 Answers2

2

solved my problem i need to grab the id of my checkbox in order to distinguish which checkbox value i was running my function on.

<script>
$('input:checkbox').change(function(e) {
e.preventDefault();

// Determine ID
 var value = $(this).attr('id');
 var EsID = value;

var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
$.ajax({
          type: 'POST',
          url: "<?php echo $this->url('/profile/list', 'event_status')?>"+EsID +"",
        data: { event_status:$("input:checkbox").attr("id"), event_status:isChecked }
});        
});
</script>
Gismmo
  • 329
  • 4
  • 12
0

What about giving your checkbox input a class and raise the change event on the class rather than the checkbox name.

e.g.

Change

$('#event_status<? echo $cobj->getCollectionID()?>').change(function() {

to

$('.CheckboxClassName<? echo $cobj->getCollectionID()?>').change(function() {
keitn
  • 1,288
  • 2
  • 19
  • 43