简体   繁体   中英

Submit checkbox value to PHP without submit button

I have a form with only a checkbox:

<form action="escreve.php" method="post">
    <label><input type="checkbox" autocomplete="off" checked="checked" name="autosave">Autosave</label>
    <input type="submit" name="formSubmit" value="Submit" />
</form>

This will trigger escreve.php. It works fine, but the question is how can I trigger escreve.php without the submit button? It doesn't seem to make sense in this case since this form has only one input (the checkbox).

I'd like to have escreve.php reading the value of the checkbox whenever the user clicks in or out. Since I'm also using jQuery, would that be possible?

Thanks for any help!

you can use some javascript to trigger the submit.

<form id='form' action="escreve.php" method="post">
    <label><input type="checkbox" autocomplete="off" checked="checked" name="autosave">Autosave</label>
</form>

<script>
$(document.ready(function (e) {
     $("input#autosave").click(function (e) {
         $("#form").submit();
     });
});
</script>

Use jquery form submit method

Try like this

<form action="escreve.php" method="post" id="myForm">
    <label><input type="checkbox" autocomplete="off" checked="checked" name="autosave" id="autosave">Autosave</label>
    <input type="submit" name="formSubmit" value="Submit" />
</form>

$(document).ready(function(){
  $("#autosave").click(function(){
      $("#myForm").submit()
  });
});

Don't get rid of the button, get rid of the checkbox.

<form action="escreve.php" method="post">
    <input type="submit" name="autosave" value="Autosave" />
</form>

sure you can. see jQuery onChange() or onClick() and submit the form with jQuery with .submit()

   var form = $('form');  

  $('[name="autosave"]').click(function() {
        $.ajax({
          type: form.attr('method'),
          url: form.attr('action'),
          data: form.serialize()
        }).done(function() {
          // Optionally alert the user of success here...
        }).fail(function() {
          // Optionally alert the user of an error here...
        });
        event.preventDefault(); // Prevent the form from submitting via the browser.
    });
  • Give some id to your form
  • Then submit your form using submit() method on change event of checkbox

eg

$('#chkid').change(function() { $('#frmid').submit(); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM