0

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>

2
  • You code snippet works fine! Commented Jun 30, 2017 at 14:10
  • What's the point of this code? It goes against the standard pattern for working with checkboxes in that if the box is not checked then no value will be sent in the request. Therefore the value being 0 when unchecked is moot. If you want to know which checkboxes are/are not checked it would make far more sense to use map() to create a boolean array of the checked state of each checkbox Commented Jun 30, 2017 at 14:10

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.