Peter
Peter

Reputation: 804

jquery checkbox checked change value

If checkbox is clicked then value of checkbox must be 1. If checkbox is not clicked then its value must be 0. For some reason below code seems not working fine.

// Checkbox values 1/0.
$("#prefForm").submit(function() {
  $("input[type=checkbox]").each(function() {
    var self = $(this);
    if (self.is(":checked")) {
      self.val('1');
    } else {
      self.val('0');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-activity">
  <ul>
    <li>
      <!-- <input type="hidden" name="donate_buskie" value=""> -->
      <input type='checkbox' id='checkbox-1' class='pseudo-checkbox sr-only' name="donate_buskie" value="0" />
      <label for='checkbox-1' class='glyphicon-check-click fancy-checkbox-label'><span><?php echo JText::_('When someone donates to my Buskie'); ?></span>
</label>
    </li>
    <li>
      <!-- <input type="hidden" name="receives_donation" value=""> -->
      <input type='checkbox' id='checkbox-2' class='pseudo-checkbox sr-only' name="receives_donation" value="0" />
      <label for='checkbox-2' class='glyphicon-check-click fancy-checkbox-label'><span><?php echo JText::_('When someone receives a donation'); ?></span>
</label>
    </li>
    <li>
      <input type='checkbox' id='checkbox-3' class='pseudo-checkbox sr-only' name="comment_buskie" value="0" />
      <label for='checkbox-3' class='glyphicon-check-click fancy-checkbox-label'><span><?php echo JText::_('When someone posts a comment on your Buskie'); ?></span>
</label>
    </li>
    <li>
      <input type='checkbox' id='checkbox-4' class='pseudo-checkbox sr-only' name="comment_reply" value="0" />
      <label for='checkbox-4' class='glyphicon-check-click fancy-checkbox-label'><span><?php echo JText::_('When someone replies to my comment'); ?></span>
</label>
    </li>
  </ul>

Upvotes: 0

Views: 923

Answers (1)

WebsitesOntario
WebsitesOntario

Reputation: 104

There is no need to use jQuery to assign 1/0 values for a checkbox, based on wether it is checked or not. The checkbox already holds a boolean value. If you need ones and zeros, you can just use

var number_value = self.val() ? 1 : 0;

Upvotes: 1

Related Questions