如何在checkbox
上进行选择后比较值并显示输出?我正在使用 jQuery 来执行此操作。选择完成后,它不会显示输出。它只会显示第一次点击。然后,如果我们再次单击,则不会更改输出。下面是我到目前为止编写的代码,
的jQuery
$("input:checkbox").on('click', function() {
var $box = $(this),
$price = $( "input[name='price_range']:checked").val(),
$nama_pemohon = "<?php echo $nama_pemohon; ?>",
$submited_id = <?php echo $submited_id; ?>,
$jawatan_pemohon = "<?php echo $jawatan_pemohon; ?>",
$jabatan_pemohon = "<?php echo $jabatan_pemohon; ?>",
$submited_by = <?php echo $submited_by; ?>,
$nama = "<?php echo $nama; ?>",
$jawatan = "<?php echo $jawatan; ?>",
$jabatan = "<?php echo $jabatan; ?>";
if($price == "< RM 10,000"){
$("#submited_by option").val($submited_by).text($nama);
$("#jawatan_pemohon").text($jawatan);
$("#jabatan_pemohon").text($jabatan);
} else {
$("#submited_by option").val($submited_id).text($nama_pemohon);
$("#jawatan_pemohon").text($jawatan_pemohon);
$("#jabatan_pemohon").text($jabatan_pemohon);
}
});
HTML
<input type="checkbox" name="price_range" value="< RM 10,000" class="checker"> < RM 10,000.00
<input type="checkbox" name="price_range" value="< RM 200,000" class="checker"> < RM 200,000.00
<select name="submited_by" id="submited_by">
<option value="<?php echo $submited_by; ?>"><?php echo $nama;?></option>
</select>
答案 0 :(得分:1)
正如您在this fiddle中所看到的,您在第一个复选框上的每次点击都会得到更改,但只会在第二个复选框上第一次更改。
这是因为你的逻辑:
if($price == "< RM 10,000"){
$("#submited_by option").val($submited_by).text($nama);
$("#jawatan_pemohon").text($jawatan);
$("#jabatan_pemohon").text($jabatan);
} else {
$("#submited_by option").val($submited_id).text($nama_pemohon);
$("#jawatan_pemohon").text($jawatan_pemohon);
$("#jabatan_pemohon").text($jabatan_pemohon);
}
示例a:
if
。else
。示例b:
else
。else
。答案 1 :(得分:0)
我认为您应该在jQuery函数之外创建一个“全局”变量。
var clicked = false;
$("input:checkbox").on('click', function() {
if(!clicked) {
var $box = $(this),
$price = $( "input[name='price_range']:checked").val(),
$nama_pemohon = "<?php echo $nama_pemohon; ?>",
$submited_id = <?php echo $submited_id; ?>,
$jawatan_pemohon = "<?php echo $jawatan_pemohon; ?>",
$jabatan_pemohon = "<?php echo $jabatan_pemohon; ?>",
$submited_by = <?php echo $submited_by; ?>,
$nama = "<?php echo $nama; ?>",
$jawatan = "<?php echo $jawatan; ?>",
$jabatan = "<?php echo $jabatan; ?>";
if($price == "< RM 10,000"){
$("#submited_by option").val($submited_by).text($nama);
$("#jawatan_pemohon").text($jawatan);
$("#jabatan_pemohon").text($jabatan);
} else {
$("#submited_by option").val($submited_id).text($nama_pemohon);
$("#jawatan_pemohon").text($jawatan_pemohon);
$("#jabatan_pemohon").text($jabatan_pemohon);
}
clicked = true;
}
});