我有这个问题:
用户仅输入性别(男/女),代码必须自动填写"系数" 1和"系数2"在两个不同的输入字段中。我设法为Coefficient 1做了这个,但我的Coefficient 2代码不起作用。 或者也许有一个更好的方法。
function getC2 () {
var cc = parseFloat($("#kog").val());
if (cc == 1){
$('#kocc').val(1);
}
else {
$('#kocc').val("0.85");
}
}
$(document).ready(function() {
$('#kog').change(function(event) {
getC2();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="demo09a" class="gender" type="radio" name="gender" value="0.75" onClick="document.getElementById('kog').value=this.value">
<label for="demo09a">female</label>
<input type="radio" name="gender" id="demo09b" class="gender" value="1" onClick="document.getElementById('kog').value=this.value">
<label for="demo09b">male</label>
<br />
<input id="kog" type="text" name="Co1" readonly="true" placeholder="Coefficient 1 ">
<label for="kog">Coefficient 1 </label>
<br />
<input id="kocc" type="text" name="kocc" readonly="true" placeholder="Coefficient 2">
<label for="kocc">Coefficient 2</label>
<br />
&#13;
答案 0 :(得分:4)
你使用jquery使用$('input[name=gender]').click(function(e) {});
很容易处理单选按钮更改,请参阅此示例:
function getC2 () {
var cc = parseFloat($("#kog").val());
if (cc == 1){
$('#kocc').val(1);
}
else {
$('#kocc').val("0.85");
}
}
$(document).ready(function() {
$('input[name=gender]').click(function(e) {
$('#kog').val($(this).val());
getC2();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="demo09a" class="gender" type="radio" name="gender" value="0.75">
<label for="demo09a">female</label>
<input type="radio" name="gender" id="demo09b" class="gender" value="1">
<label for="demo09b">male</label>
<br />
<input id="kog" type="text" name="Co1" readonly="true" placeholder="Coefficient 1 ">
<label for="kog">Coefficient 1 </label>
<br />
<input id="kocc" type="text" name="kocc" readonly="true" placeholder="Coefficient 2">
<label for="kocc">Coefficient 2</label>
<br />
答案 1 :(得分:1)
你走在正确的轨道上。但是使用jQuery,您可以始终提高效率。看看:
//lets set the event handlers
$('input[type=radio].gender').click(function(e){
//if the click comes from the female radio set coefficients differently
if ($(this).attr("id") == "demo09a")//female
{
$("#kog").val(0.75);
$("#kocc").val(0.85);
}
else
{
//male, select both id's and set to 1.
$("#kog, #kocc").val(1);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="demo09a" class="gender" type="radio" name="gender">
<label for="demo09a">female</label>
<input type="radio" name="gender" id="demo09b" class="gender" >
<label for="demo09b">male</label>
<br />
<input id="kog" type="text" name="Co1" readonly="true" placeholder="Coefficient 1 ">
<label for="kog">Coefficient 1 </label>
<br />
<input id="kocc" type="text" name="kocc" readonly="true" placeholder="Coefficient 2">
<label for="kocc">Coefficient 2</label>
<br />