我会将多个字段的值传递给文本字段。有一个问题,复选框。如果用户选中复选框(allowance)只将值传递给文本字段,如何确保?
HTML:
<select id="Salary_para1">
<option value="">Choose...</option>
<option value="MYR" selected>MYR</option>
<option value="SGD" >SGD</option>
</select>
<input id="Salary_value" type="text"/>
+ <input type="checkbox" id="Salary_para2" name="Salary_para2" value=" + Allowance" />Allowance<br/>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99" value="">
CODE:
$(function() {
$("#Salary_para1").change(function(){
setTarget()
});
$("#Salary_para2").change(function(){
setTarget()
});
$("#Salary_value").keyup(function(){
setTarget();
});
});
function setTarget(){
var tmp = $("#Salary_para1").val();
tmp += $("#Salary_value").val();
tmp += $("#Salary_para2").val();
$('#targetTextField').val(tmp);
}
答案 0 :(得分:2)
检查复选框是否为checked
:
$(function() {
setTarget();
$("#Salary_para1,#Salary_para2").change(setTarget);
$("#Salary_value").keyup(setTarget);
function setTarget() {
var tmp = $("#Salary_para1").val();
tmp += $("#Salary_value").val();
tmp += $("#Salary_para2:checked").val() || '';
$('#targetTextField').val(tmp);
}
});
http://jsfiddle.net/oceog/e2ScF/62/
(我还对orinal代码进行了一些重构)
答案 1 :(得分:0)
对不起,你的意思是这样吗?
function setTarget(){
var tmp = $("#Salary_para1").val();
tmp += $("#Salary_value").val();
tmp += $("#Salary_para2").val();
if($("#Salary_para2").is(":checked")){
$('#targetTextField').val(tmp);
}
}
示例: