How to simplify the script for checking purpose

时间:2015-07-28 22:57:13

标签: javascript jquery select checked

how to simplify the next script (jquery).

The first code checks if there exist a "checked" and shows the related field or none field.

The second code is here in case the user changes the option.

$(document).ready(function(){
if ($("#Check_0").is(":checked")){
    $('#field_2, #field_1').addClass('hidden')
}
if ($("#Check_1").is(":checked")){
    $('#field_2').addClass('hidden')
	$('#field_1').removeClass('hidden')
}
if ($("#Check_2").is(":checked")){
    $('#field_1').addClass('hidden')
	$('#field_2').removeClass('hidden')
}

$('#Check_0').change(function() {
  if ($(this).is(':checked')) {
    $('#field_1, #field_2').addClass('hidden');
  }
});
$('#Check_1').change(function() {
  if ($(this).is(':checked')) {
    $('#field_2').addClass('hidden');
	$('#field_1').removeClass('hidden');
  }
});
$('#Check_2').change(function() {
  if ($(this).is(':checked')) {
    $('#field_1').addClass('hidden');
	$('#field_2').removeClass('hidden');
  }
});
});
.hidden {display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<input type="radio" name="Check" value="none" id="Check_0" checked="checked" /> none
<input type="radio" name="Check" value="one" id="Check_1" /> one
<input type="radio" name="Check" value="two" id="Check_2" /> two
<div id="field_1">
<p>one <input type="text" class="input" /></p>
</div>

<div id="field_2">
<p>two <input type="text" class="input" /></p>
</div>

1 个答案:

答案 0 :(得分:2)

$(document).ready(function() {
    var fn = function() {
        for (var i = 1; i <= 2; ++i)
            $('#field_'+i)[$("#Check_"+i).is(":checked") ? "removeClass" : "addClass"]('hidden');
    };
    fn();
    $('#Check_0, #Check_1, #Check_2').change(fn);
});