简体   繁体   中英

Calling Value from Outside a Form when Checkbox is Checked

I've almost got this...hopefully I can lock this up.

This first part is a checkbox outside the form:

<div class='span5' style='margin-left:0px !important;'>
                        <label for='model0'>
                            <input type="checkbox" name="model0" id="model0" value="test" style='margin-top:-5px !important;'> test</label>
                    </div>  .

This is my script for sending value of of model0 (when checked) to send_mail.php in the form area.

$("#final_form").submit(function () {
     $("#model0_is_checked").val($("#model0").is(':checked'));
    return test;
    });

And this is the form area:

<form method="post" class="form-horizontal" id="final_form" action="send_mail.php">
        <input type="hidden" id="model0_is_checked" name="model0_is_checked" value="test" />    MORE FORM STUFF AND SUBMIT BUTTON     </form>

When I call model0_is_checked, all I get is true rather than "test" like I'm trying to call...anyone know why?

You can do sth like here (based on your code): http://jsfiddle.net/SdMAt/ I have rewritten javascript part. Now hidden input (changed to text type to see the results) is changed on every click on this external checkbox.

$("#model0").on('click', function () {
    if ($(this).is(':checked')) {
        $('#model0_is_checked').attr('value','true'); 
    } else {
        $('#model0_is_checked').attr('value','false'); 
    }
});

.is(':checked') returns true or false for whether the checkbox is checked. It does not return the value. You could do something like:

//if checked
if($("#model0").is(':checked')){
    //set the value
    $("#model0_is_checked").val($("#model0").val());
//not checked
} else {
    //set to some other default value
    $("#model0_is_checked").val("not checked");
}

However, if you just include the checkbox in the form, you would get the value of the checkbox on submit and no value if not checked. On submit, in php, you would get $_POST['model0'] equal to test if checked and $_POST['model0'] would not be set if not checked. You can do something like $model0 = isset($_POST['model0'])?$_POST['model0']:null; to get the value without error.

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