Muhammad Awais Muhammad Awais - 2 months ago 26
Javascript Question

How to get value of checkbox on check or un-check without submit form

I want to change value when someone check or un-check checkbox. Here is my code:

<?php
if($params['status'] == "2"){ ?>
<div class="pull-right" id="confirm-ship">
<input type="checkbox" class="chkone"><br>
if(checkbox == check){
<span>Confirmed</span>
}else{
<span>Not Confirmed</span>
}
</div>
<?php
}
?>


I want to show message confirmed or not confirmed when someone click on checkbox without submit a page or reload a page. Is it possible, anyone help me?

I just added below code on above scenario just for giving an idea.

if(checkbox == check){
<span>Confirmed</span>
}else{
<span>Not Confirmed</span>
}

Answer

First you will need to set an event listener to listen for the change event and trigger a function.

If you give your elements id's you can make things easier to target that element.

You will also want to place your javascript into <script> tags. Some people place them in the body of the page or at the very bottom. Me personally, I like to place my in the <head> tag as using window.onload will only attempt to getElementById() when the page has loaded.

window.onload=function(){ // Trigger when the page is ready
  //Set change event 
  document.getElementById('Confirmation').addEventListener('change', Confirm, false);
}

function Confirm(){
  var Confirmation=document.getElementById('Confirmation').checked;
  var Message;
  if(Confirmation){
    Message="Confirmed";
  }else{
    Message="Not Confirmed"
  }
  document.getElementById('Result').innerHTML=Message;
}
<input type="checkbox" id="Confirmation" />
<span id="Result">Not Confirmed</span>

If you have any questions about the above source code please leave a comment below and I will get back to you as soon as possible.