开发者

Make hidden input value depend on radio button selection using PHP/JavaScript

I'm tr开发者_开发问答ying to figure out how to make the logic in the following form work. Basically if either of the first two radio buttons is checked, make the hidden input named categories have a value of vegetables. Else, make the hidden input named categories have a value of fruits.

I'm not sure if this should be done with PHP or JavaScript, but if it is done with PHP I think the form would have to be submitted to itself to be pre-processed and then the collected, pre-processed information would be sent to external_form_processor.php. If this is how you do it, what would be the PHP code that I need to use to make it work?

<?php
if($_POST["food"]=="carrots" || $_POST["food"]=="peas") {
    $category = "vegetables";
} else {
    $category = "fruits";
}
?>

<form name="food_form" method="post" action="external_form_processor.php" >

<fieldset>
<input type="radio" id="carrots" name="food" value="carrots" />
<input type="radio" id="peas" name="food" value="peas" />
<input type="radio" id="orange" name="food" value="orange" />
<input type="radio" id="apple" name="food" value="apple" />
<input type="radio" id="cherry" name="food" value="cherry" />
</fieldset>

<input type="hidden" name="categories" value="<?php $category ?>" />

</form>

If using jQuery would be easier, how could I call the variable as the value of the hidden input if I use the following in the head of the page?

$(function(){
    $('input[name=food]').click(function(){
        var selected_id = $('input[name=food]:checked').attr('id');
        if (selected_id == 'carrots' || selected_id == 'peas') {
            var category = "vegetables";
        } else {
            var category = "fruits";
        }
    });
});

Any help with this would be greatly appreciated. Thanks!


I think jQuery would work perfect for you, you just need to pass the category value to the input field:

$(function(){
    $('input[name=food]').click(function(){
        var selected_id = $('input[name=food]:checked').attr('id');
        if (selected_id == 'carrots' || selected_id == 'peas') {
            var category = "vegetables";
        } else {
            var category = "fruits";
        }
        $('input[name=categories]').val(category);
    });
});


I would set the category in PHP when the form is submitted.

//validate inputs... always
    $food = "";
    if(isset($_GET['food'])){
        $food = preg_replace("/[^a-zA-Z]+/", "", $_GET['food']);
    }
    $category = ($food=="peas"||$food=="carrots")?"vegetables":"fruits";

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜