3

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?

8
  • You can easily achieve this with use of ajax Commented Nov 30, 2015 at 1:52
  • can you give us the html? Commented Nov 30, 2015 at 1:55
  • PHP isn't present after the page has loaded. You could do this with JS. Commented Nov 30, 2015 at 1:56
  • but there is a way to do it with php @chris85 Commented Nov 30, 2015 at 1:57
  • @JackSmith not without reloading the page or using JS. Commented Nov 30, 2015 at 1:57

2 Answers 2

2

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/
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.