多个文本框传值给另外几个文本框的问题

请教老师:

<form  name="form1">
<input type="text"  id="id1" />
<input type="text"  id="text1" />
<input type="text"  id="name1" />
<button  onclick="myfunction()">输出</button></form>

<form  name="form2">
<input type="text"  id="id1" />
<input type="text"  id="text1" />
<input type="text"  id="name1" />
<button  onclick="myfunction()">输出</button></form>

<form  name="form3">
<input type="text"  id="id1" />
<input type="text"  id="text1" />
<input type="text"  id="name1" />
<button  onclick="myfunction()">输出</button></form>

//上面这些文本框是数据库循环输出的,数量不定。

<input type="text" id="recive1" />
<input type="text" id="recive2" />
<input type="text" id="recive3" /> 
//这里文本框只有三个,用来点每个按钮后接收对应文本框传的值

<script>
function myfunction()
{
document.getElementById("recive").value=document.getElementById("id1").value; 
document.getElementById("recive").value=document.getElementById("text1").value; 
document.getElementById("recive").value=document.getElementById("name1").value;  //这里要怎样写才能每个文本框都运行
}   
 </script>
阅读 1.6k
2 个回答

这实际上是一个字符串动态拼接的问题。

如果单纯从你给出的代码上修改的话,既然能从数据库循环输出,并且生成 form1form2form3...,那么你就应该为文本框生成同样的带标识的 id,并在 onclick 方法中也传入该标识:

<!-- 1 -->
<input type="text"  id="id1" />
<input type="text"  id="text1" />
<input type="text"  id="name1" />
<button  onclick="myfunction(1)">输出</button>

<!-- 2 -->
<input type="text"  id="id2" />
<input type="text"  id="text2" />
<input type="text"  id="name2" />
<button  onclick="myfunction(2)">输出</button>

<!-- 3 -->
...

之后让 myfunction() 方法按传入的标识处理即可:

function myfunction(sig)
{
 // `id${sig}` 与 'id'+sig 相同
  document.getElementById("recive1").value=document.getElementById(`id${sig}`).value; 
  document.getElementById("recive2").value=document.getElementById(`text${sig}`).value; 
  document.getElementById("recive3").value=document.getElementById(`name${sig}`).value; 
}

还有,按钮在form中点了后为什么都会打开链接。我这里其实可以不要form,只要文本框。

因为 <form> 标签中只存在一个 <button> 时会自动成为 <button type="submit">,因此点击时会触发提交操作,而默认的提交操作就是会刷新页面。

按钮在form中点了后为什么都会打开链接?

先回答你这个问题,你应该是走默认的 submit 了。你可以给按钮加个 type="button"

然后就是拼合了

// 如果是每次都要保留肯定是 += 了
document.getElementById("recive").value+=document.getElementById("id1").value; 
// 你可以把他们都累加起来
document.getElementById("recive").value+=document.getElementById("id1").value+document.getElementById("id2").value+document.getElementById("id3").value; 
// 你还可以使用选择器。
document.getElementById("recive").value+= Array.from(document.querySelectorAll('[id]')).map(v=>v.value).join('\n')

里面选择器都是瞎写的,换成你自己要的就可以了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题