我想将复选框数组的值传递给3个输入,如果我签入发送到第一个输入的值,然后将第二个复选框传递给第二个输入,然后将第三个复选框传递给第三个输入,那么如果我选择该复选框的另一个值,除非先取消选中该复选框的值,否则该值不会覆盖
可以放置一个addeventlistener
<form action="#" method="post" class="demoForm" id="demoForm">
<fieldset>
<label><input type="checkbox" name="sports[]" value="cycling" /> cycling</label>
<label><input type="checkbox" name="sports[]" value="running" /> running</label>
<label><input type="checkbox" name="sports[]" value="visit gym" /> visit gym</label>
<label><input type="checkbox" name="sports[]" value="swimming" /> swimming</label>
<label><input type="checkbox" name="sports[]" value="team sports" /> team sport(s)</label>
<label><input type="checkbox" name="sports[]" value="other" /> other</label>
</fieldset>
</form>
<script type="text/javascript">
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
y=document.getElementById("chk1");
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
if ( this.checked) {
y.value=this.value;
} else {
y.value="";
}
}
</script>
<input type="text" name="chk1" id="chk1">
<input type="text" name="chk2" id="chk2">
<input type="text" name="chk3" id="chk3">
我希望看到解决方案。
答案 0 :(得分:0)
我创建了一组条件代码,当我理解您的问题时,它将对您有用,并且在解释过程中会附带注释。
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
x = document.getElementById("chk1");
y = document.getElementById("chk2");
z = document.getElementById("chk3");
/*if a checkbox is checked and the first input is empty, then put the checkbox
value in the first input */
if ( this.checked && x.value =="") {
x.value = this.value;
/*now if the first input is filled already, check if the second is empty and put
the checkbox value into the second*/
} else if (this.checked && y.value =="") {
y.value = this.value ;
/*now if the second input is filled already, check if the third is empty and
put the checkbox value into the third*/
} else if (this.checked && z.value ==""){
z.value = this.value ;
/* if a checkbox is checked and all 3 inputs are filled already so it gets to
this condition, then alert the user and make the checkbox shouldn't be checked*/
}else if (this.checked) {
alert("First un-check another box to check this box");
this.checked = false;
/* if the user unchecked a checkbox, then check in which input the value of this
checkbox was displayed and empty this input */
} else if (!this.checked){
switch(this.value){
case y.value:
y.value="";
break;
case x.value:
x.value="";
break;
case z.value:
z.value="";
}
}
}