Carl Ortiz
Carl Ortiz

Reputation: 465

How do I make the checkbox contain value :checked (boolean)?

I would like to make checkbox input to have dynamic value depending on :checked.

If checkbox is checked, then the value is "true"

<input type="checkbox" value="true" checked="checked">

or If checkbox is unchecked, then the value is "false"

<input type="checkbox" value="false">

I'm doing this because I'm submitting form through ajax and I'm using jQuery.searialize()

This field is more like a switch.

Is it possible? Thanks!

Upvotes: 0

Views: 2427

Answers (3)

Kinglish
Kinglish

Reputation: 23664

The jQuery way

$('[data-switchval]').change(function() {
  $(this).val($(this).prop('checked'));
  console.log('current value of checkbox:', $(this).val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-switchval value="true" checked="checked">

[Postscript] Just realized this question was tagged as jQuery... here's the vanillaJS version.

document.querySelector('[data-switchval]').addEventListener('change', e => {
  e.target.value = e.target.checked
  console.log('current value of checkbox:', e.target.value)
})
<input type="checkbox" data-switchval value="true" checked="checked">

Upvotes: 2

Salvatore Leto
Salvatore Leto

Reputation: 56

If I understand the question, you want to change the value of the checkbox depending if it is checked or not? This can be done with AJAX. You'll have to add an id ('#checkbox1') for your checkbox input.

Here is one solution:

$('#checkbox-value').text($('#checkbox1').val());

$("#checkbox1").on('change', function() {
  if ($(this).is(':checked')) {
  $(this).attr('value', 'true');
  } else {
  $(this).attr('value', 'false');
  }

 $('#checkbox-value').text($('#checkbox1').val());
});

And then adding this in your code to get the value:

<div id="checkbox-value"></div>

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89404

You can add an event listener for the change event.

let checkbox = document.querySelector('input[type=checkbox]');
function setValue(checkbox){
  checkbox.value = checkbox.checked;
}
setValue(checkbox);
console.log(checkbox);
checkbox.addEventListener('change', ()=>{
  setValue(checkbox);
  console.log(checkbox);
});
<input type="checkbox">

Upvotes: 0

Related Questions