Patrick Manser
Patrick Manser

Reputation: 1183

Checkbox is checked, but :checked doesn't work

I have a few checkboxes. I'm setting and resetting the default values of the checkboxes with the .prop() function, based on a JSON response (loading the data via ajax-requests). The problem is, that they apparently don't change this behaviour, if I change them manually. I can't pass the value of the checkboxes via $('#checkbox :checked').val(), a console log says 'undefined'. Is this because of the .prop() function? How can I get the value of the checked checkboxes?

If you need more information, i'll gladly provide them. Here some code:

if (json.event.public_visible == 1) {
  $('#event_public_visible').prop('checked', true);
} else {
  $('#event_public_visible').prop('checked', false);
}

if (json.event.package_event == 1) {
  $('#event_package_only').prop('checked', true);
} else {
  $('#event_package_only').prop('checked', false);
}

Update: more code

var editEvent = function () {
  if ($('#event_public_visible').is(':checked')) {
    console.log('test');
  }
  formData = {
    // ... other fields
    event_package_only: $('#event_package_only :checked').val(),
    event_public_visible: $('#event_public_visible :checked').val(),
    // ... more fields
  };

  $.ajax({
    url: base_url + "admin/events/editAsync",
    type: "POST",
    data: formData,
    dataType: "json",
    success: function (json) {
      // success handling
    }
  });
};

Upvotes: 0

Views: 1582

Answers (2)

Bagata
Bagata

Reputation: 2170

Try this: $('#event_public_visible:checked').val() and $('#event_public_visible:checked').val()

You can try: ('#event_public_visible:checked').length ? $('#event_public_visible:checked').val() : '';

Example: http://jsfiddle.net/infernalbadger/SfcjG/

Upvotes: 2

MasNotsram
MasNotsram

Reputation: 2273

You're setting a property on elements with an IDs of 'event_public_visible' and 'event_package_only' and then trying to read from an element of ID 'checkbox'.

Did you mean to use this?

$('[type=checkbox]:checked').val()

Can see it working here:

http://jsfiddle.net/vRba3/

Upvotes: 1

Related Questions