通过javascript循环遍历表单字段数组,将表单字段文本替换为php值



我的网站列出了出售的唱片。

我有一个html表单与几个字段如下:

<input type="text"   name="artist" id="artist" class="txt"  />
<input type="text"   name="title" id="title" class="txt"  />
<input  class="tracks"  name="a1" id="a1" >
<input  class="tracks"  name="a2" id="a2" >
<input  class="tracks"  name="a3" id="a3" >
$tit="random title";

我想有一个按钮调用一个javascript函数,取代每个表单字段的文本(如果它包含记录标题($tit)到!!如果字段名与轨道数组中预定义的表单字段名列表匹配,则如下:

var tracks= ['a1', 'a2', 'a3' ];

我看了看://用数组

填充表单字段到目前为止,我得到的代码允许下面的更改按钮将表单字段a1中的标题替换为!!如果标题文本在表单字段a1中找到,但我希望js代码循环遍历数组中的所有表单字段,并替换标题,如果它找到。
<input type="button" class="button-8"  value="change" name="no" onclick="spling('a1','<?php echo $tit; ?>');">
<script>
function spling(v,t) {
// v= side a1
// t= record title $tit
var txt=document.getElementById(v).value;
var uc= t.toUpperCase()
//if (txt.indexOf(t) >= 0){
if (txt.toUpperCase().indexOf(uc) >=0) {
txt =txt.replace(t,'!!');
document.getElementById(v).value=txt;
}
else{
document.getElementById('res').innerHTML = t+" not found in field "+v;  
}
}

</script>

我需要能够替换记录的标题!!如果它出现在a1 a2 a3

我希望js代码循环通过数组中的所有表单字段和改变文本与一个按钮单击,而不是有三个单独的按钮,以取代字段a1,a2和a3的标题文本。

谢谢你的帮助!

按钮将表单字段a1中的标题文本替换为!!如果字段a1已经包含$tit文本

我已经在谷歌上搜索了一个解决方案,但发现自己将代码片段连接在一起并没有得到我想要的结果。

您可以这样做。我们在这里所做的是循环遍历tracks数组并在循环中通过id获取元素。

function spling(t) {
const val = t.toUpperCase();
var tracks = ['a1', 'a2', 'a3'];
let result = "";
for (var i = 0; i < tracks.length; i++) {
const track = document.getElementById(tracks[i]);
const txt = track.value.toUpperCase();
if (txt.indexOf(val) >= 0) {
track.value = '!!';
} else {
result += t + " not found in field " + track.getAttribute('id') + "<br>";
}
}
if (result) {
document.getElementById('res').innerHTML = result;
}
}
<input type="text" name="artist" id="artist" class="txt" />
<input type="text" name="title" id="title" class="txt" />
<input class="tracks" name="a1" id="a1">
<input class="tracks" name="a2" id="a2">
<input class="tracks" name="a3" id="a3">
<input type="button" class="button-8" value="change" name="no" onclick="spling('random title')">
<div id="res"></div>

最新更新