单选按钮结果显示在show / hide div中的body onload上

时间:2012-01-16 06:50:25

标签: php jquery html ajax

显示所选单选按钮的结果。我有一个问题,当页面刷新时没有div显示,也没有显示结果。我想在页面刷新时显示Carsbuy div。

    $(document).ready(function() {
        $("input[name$='mode']").click(function() {
            var test = $(this).val();

            $("div.desc").hide();
            $("#Cars" + test).show();
        });
    });

<input type="radio" name="mode" checked="checked" value="buy"  />

<label>Buy</label>

<input type="radio" name="mode" value="rent" />

<Label>Rent</label>

<div id="Carsbuy" class="desc" style="display: none;">

    Buy Cars Result Display Here On Select Buy

</div>

<div id="Carsrent" class="desc" style="display: none;">

    Rent Cars Result Display Here On Select Rent
</div>

3 个答案:

答案 0 :(得分:1)

您可以在js代码的开头使用以下内容来满足页面加载时的特定DIV:

$("#Carsbuy").show();

修改

对于特定的DIV和单选按钮,请使用以下命令:

var selected = 'rent';
$("div.desc").hide();
$("#Cars" + selected).show();
$('input[value="' + selected + '"]').attr('checked', true);

您可以更改var selected的值以选择特定的单选按钮和DIV

Demo

答案 1 :(得分:0)

尽管我了解您的要求,但您可以按照以下方式进行操作。

<强> HTML:

<input type="radio" name="mode" checked="checked" value="buy"  />
<label>Buy</label>
<input type="radio" name="mode" value="rent" />
<Label>Rent</label>
<div id="CarsDetails" class="desc">
  // include buy type cars initialy while page load.
</div>

<强> JQuery的:

$(document).ready(function() {
   $('input[type="radio"]').click(function() { // detect when radio button is clicked
     var carType = $(this).val(); // get the value of selected radio type
     $.ajax({
      url : "cartype.php", // link to file containing data of cars
      type : "GET",  // request type
      data : "carType="+carType,  // send the selected car type (buy or rent)
      datatype : "html",
      success : function(response){  // get the response
            $('#CarsDetails').html(response);  // put the response in div.
      }
     });
   });
});

答案 2 :(得分:0)

在以下代码中,在页面加载时检查是否选择了单选按钮,然后显示其相应的div。如果使用条件来防止没有选择单选按钮

$(document).ready(function()   {
var selected =  $("input[type='radio']:checked").val();

if(selected !== 'undefined')
{
   $("#Cars" + selected ).show();
}

$("input[type='checkbox']:checked").attr('id')
    $("input[name$='mode']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});