How can I check a input field exists in the form when I submit it to the server?

15,406

Solution 1

I'm guessing you need to check on the server side after the form is submitted. If that's the case, you can check like so...

<?php
if (isset($_POST['mem_follow']))
{
    // Work your server side magic here
} else {
    // The field was not present, so react accordingly
}
?>

Hope this helps!

Solution 2

In the following script the form will not submit unless the checkbox is ticked. And If you do try, the hidden div with an error message is shown, to let you know why.

<form action="test.php" method="post" id="myform">
    <input type="checkbox" name="checkbox" id="checkbox" value="YES" />
    <input type="submit" name="submit" value="submit" />
</form>
<div id="error_message_div" style="display:none">You must tick the checkbox</div>
<script>
    $('#myform').submit(function() {
        if($('#checkbox').attr('checked')) {
            return true;
        } else {
            $("#error_message_div").show();
            return false;
        }
    });
</script>

Cheers Matt

Solution 3

It'd HAVE to be Javascript. PHP can't reach out from the server into the browser's guts and check for you. It could only check if the fieldname is present in the submitted data.

In jquery it's trivial:

if ($('input[name="nameoffield"]')) { ... field exists ... }

Of course, this raises the question... why do you need to know if a field exists or not? Presumably you're the one who's built the form. You should know already if the field exists or not.

Solution 4

you can do this in two way:

By Server Side: In php

<?php
if (isset($_POST['mem_follow'])
{
    // Work your server side magic here
} else {
    // The field was not present, so react accordingly
}
?>

By Client side: In Jquery

$('#submit_button').click(function() {
  if ($('input[name="box_name"]')) {
    if($('input[name="box_name"]').attr('checked')) {
        return true;
    } else {
        return false;
    }
  }
});
Share:
15,406
Run
Author by

Run

A cross-disciplinary full-stack web developer/designer.

Updated on July 17, 2022

Comments

  • Run
    Run almost 2 years

    How can I check a input field exists in the form when I submit it to the server?

    For instance, I want to check whether a check box named 'mem_follow' exists or not in the form.

    Or do I have to use javascript (jquery)?

  • Run
    Run over 12 years
    thaknks. actually I need it from the server side. sometimes I have a checkbox in the form and sometimes not. so I want to make it dynamic in the server side.
  • Marc B
    Marc B over 12 years
    if (isset($_REQUEST['nameoffield'])) { ... it was submitted ... }
  • tttony
    tttony over 12 years
    Use if (isset($_POST['mem_follow'])) { // do something }