0

Hi This is a HTML code for a check box. I need to take the value of the checkbox(true/false).

<input id="is-student" type="checkbox" value="Student Related"/>
<input id="open-new" type="button" value="Open New" onclick="openNew();"/>

This is the java script code for take the input value from the checkbox.

var testJson = JSON.stringify({
  reference: [{
     studentRelated: document.getElementById("is-student").checked
  }]
});

function openNew()
{
    window.openNew(testJson);
}

My problem is document.getElementById("is-student").checked always return false. If we click the checkbox, this part returns false, and if we not click the checkbox, then also return false.

I need to fix that and when we click the checkbox, then document.getElementById("is-student").checked part should return true and if we did not click, then should be return false. How can I do that?

ruwan liyanage
  • 419
  • 2
  • 11
  • 24

2 Answers2

1

You need to move testJson inside the openNew method so that the value is updated. Right now the JSON is set on load and the values are not updated on checkbox select. Try this code

function openNew()
{

  var testJson = JSON.stringify({
    reference: [{
       studentRelated: document.getElementById("is-student").checked
    }]
  });
    window.open(testJson);
} 
SPS
  • 147
  • 11
0

Your testJson variable appears to be set before your function is called, so unless your checkbox is pre-checked, studentRelated will always be false. If you want it to reflect the checkbox's status when the button is clicked, you need to evaluate whether it's checked when the function is called, not before.

mykaf
  • 1,034
  • 1
  • 9
  • 12