如何使用ajax提交无线电输入选择?

时间:2013-03-25 11:15:03

标签: php jquery ajax forms radio-group

我在myform.php模板上创建了带有广播组输入类型的表单,并使用onchange="javascript:document.post.submit()"';更新了值。因此,每当我更改选择时,值都会随页面刷新而更新。有没有办法让我可以使用ajax更新我的选择而不用页面刷新?

     <?php
          $foods = array('pasta', 'burger', 'pizza','popcorn');


            foreach ($foods as $food) {
            echo  '<input name="my_favorite_food" type="radio"   onchange="javascript:document.post.submit()"';
            $option = 'id=" ' .$food . '"';
            $option = 'value="' . $food . '"';

            if ($food == $my_favorite_food) $option .= 'checked="checked"';
            $option .= '>';
            $option .= '<label for=" '.$food .' ">' . $food .'  ';
            $option .=  '</label>';
            echo $option;
              }
         ?>

       <div id ="block">
        <?php 

        if ($my_favorite_food == "pasta") : ?>

          <h2>your favorite food is pasta</h2>
           <p> my pasta recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "burger") : ?>

          <h2>your favorite food is burger</h2>
           <p> my burger recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "pizza") : ?>

          <h2>your favorite food is pizza</h2>
           <p> my pizza recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "popcorn") : ?>

          <h2>your favorite food is popcorn</h2>
           <p> my popcorn recipe......   </p>

        <?php endif;?>
<div>

1 个答案:

答案 0 :(得分:2)

为所有选项生成HTML,并有条件地隐藏(style="display:none")当前未选中的选项。 (生成的)HTML看起来像这样:

<input type="radio" value="burger" name="favourite_food" class="favourite"/> Burger
<input type="radio" value="popcorn" name="favourite_food" class="favourite"/> Popcorn
...

<div id="burger" class="favourite-display">
    <h2>your favorite food is burger</h2>
    <p> my burger recipe...</p>
</div>
...

然后是jQuery:

$(document).ready(function() {
    $('.favourite').on('change', function(event) {
        $('.favourite-display').hide();
        $('#' + this.value).show();
    });
});

为了控制显示哪个部分,不应该每次都实际提交表格(有或没有AJAX)。