function add_option(){
var tot_option=parseInt($('#tot_option').val());
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var opt="<input type='text' id='opt"+tot_option+"' onblur='chk(this.value,'"+par+"')' name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(ivalue,rad){
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk(this.value,'radio1')" id="opt1" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" onblur="chk(this.value,'radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>
我有多个输入类型,并且每个输入前面都有一个单选按钮。如果我的输入类型没有值,那么我想从收音机中删除禁用的值,然后将禁用属性添加到收音机。在前两个输入中可以正常工作,但之后不能正常工作
答案 0 :(得分:1)
您的代码中存在一些缺陷,
1,您正在以字符串onblur='chk(this.value,'"+par+"')
的形式发送this.value
onblur function call
中的2中,发送par作为参数时出现问题,
所以我在这里修改了您的代码,现在可以正常工作了
function add_option(){
var tot_option=parseInt($('.totalOption').length);
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var onBlur = 'onblur=chk('+ par.toString() +')';
var opt="<input type='text' id='opt"+tot_option+"' class='totalOption' " + onBlur + " name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(rad){
if(event.relatedTarget == null)
return;
var SelctedTarget = Number(event.relatedTarget.id[event.relatedTarget.id.length - 1]) - 1;
var ivalue = $('#opt' + SelctedTarget).val();
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk('radio1')" id="opt1" class="totalOption" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" class="totalOption" onblur="chk('radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>