Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML PHP input checked attribute on checkbox without submitting form

I have a website, and on it I have a form with check-boxes to be filled. In PHP, I am wondering if there is a checked attribute which works when focus is lost on the check-box, not when the submit button us clicked. I have tried

    if (isset($_POST['check1'])) {

    // Checkbox is selected
    } else {

   // Alternate code
   }   

but it only works when the submit button is clicked. Is there any other way to do this?

like image 934
Felix Avatar asked Nov 29 '25 14:11

Felix


2 Answers

Since PHP is a server-side script (https://en.wikipedia.org/wiki/Server-side_scripting), there's no way to instantiate code on a client-side (https://en.wikipedia.org/wiki/Client-side_scripting) event (such as loss of focus). To check if the checkbox is checked BEFORE the form is submitted, you will need to run a javascript/JQuery script.

For instance, you could use AJAX with JQuery to trigger the event.

$(function(){ 
    $('.checkbox').focusout(function(){ 
        $.ajax({ 
            ... 
        }); 
    }); 
}); 

Then you would have the $.ajax(); function point to a PHP script to execute whatever you need done.

You can find more here:

  1. $.ajax(): http://api.jquery.com/jquery.ajax/
  2. focusout(): https://api.jquery.com/focusout/
like image 86
SanguineEpitaph Avatar answered Dec 01 '25 04:12

SanguineEpitaph


You can easily achieve this with use of ajax. Fire a function when user interact

<input type='checkbox' onblur='checkbox()' />

function checkbox(){
    var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            console.log(xhttp.responseText);
        }
      };
      xhttp.open("GET", "checkbox.php", true);
      xhttp.send();
    }

Using onblur wont give you the desired results try changing it to different events see which matches your need

Here is the list of all events in HTML DOM EVENT

like image 35
Skyyy Avatar answered Dec 01 '25 02:12

Skyyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!