Q:

Problem changing the value of a checkbox dynamically using JavaScript

I have a checkbox on a form which works fine. When the form s clicked I am trying to change the value to 1, when not clicked the value should be zero. I am filling the field dynamically using JavaScript. The problem is, when I log it in console I get an empty value..
Checkbox field

function checkMark() {
  var checkBox = document.getElementById("spouse");

  if (checkBox.checked == true){
    checkBox.value = '1';
  } else {
    checkBox.value = 'O';
  }
}

var spouse = $('#spouse').val();
console.log(spouse);

    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="spouse" value="" class="spouse" onclick="checkMark()">

A:

The reason of your issue is that you're logging just when the page is initially loaded. You have to log the result every time you change the checkbox value.
Also, you can use ternary operator in order to simplify the solution.

function checkMark() {
     var checkBox = document.getElementById("spouse");
     checkBox.value = checkBox.checked ? '1' : '0';
     log();
}

function log(){
     var spouse = $('#spouse').val();
     console.log(spouse);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="spouse" value="" class="spouse" onclick="checkMark()">

