我希望能够定位当前输入和兄弟<span>
标记,并将此范围的文本更改为OK或NOT OK,具体取决于输入是否为空。
我现在只能选择键[0]来定位第一个跨度。如何制作此代码以使其针对CURRENT范围?所以跨越1,2或3.
我的jsfiddle不起作用,代码在我的notepadd ++中生效。也许我忘了启动代码的东西?
https://jsfiddle.net/26u5efzc/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Opdracht 2: Onze Taal</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script type="text/javascript">
function checkNotEmpty(formField){ //maak functie aan geef parameters mee
if(formField.value.length > 0){ //als waarde ongelijk is aan 0 dan
console.log("OK"); //log OK
document.getElementsByTagName("span")[0].innerHTML = "OK";
return true;
}
else {
console.log("NOT OK");
document.getElementsByTagName("span")[0].innerHTML = "NOT OK"
return false;
}
}
window.onload = function(){
document.getElementById("naam").onblur = function(){
checkNotEmpty(this);
};
document.getElementById("email").onblur = function(){
checkNotEmpty(this);
};
document.getElementById("vraag").onblur = function(){
checkNotEmpty(this);
};
};
</script>
</head>
<body>
<figure>
<img src="onzeTaal.jpg" alt="Onze Taal" title="Onze Taal" />
<figcaption>Onze Taal</figcaption>
</figure>
<form name="taalvraag" method="get" action="#">
<fieldset>
<legend>Stel uw vraag</legend>
<label for="naam">Uw naam:</label>
<input type="text" name="naam" id="naam" placeholder="naam" />
<span class="melding" id="meldingNaam">1</span>
<br />
<label for="email">Uw e-mailadres:</label>
<input type="email" name="email" id="email" placeholder="e-mail" />
<span class="melding" id="meldingEmail">2</span>
<br />
<label for="vraag">Uw vraag:</label>
<input type="text" name="vraag" id="vraag" placeholder="vraag" />
<span class="melding" id="meldingVraag">3</span>
<br />
<input type="submit" name="verzenden" id="verzenden" value="Verzenden" />
</fieldset>
</form>
</body>
</html>
答案 0 :(得分:2)
您需要从
更新 document.getElementsByTagName("span")[0].innerHTML
到
formField.nextElementSibling.innerHTML
更新了小提琴 - https://jsfiddle.net/26u5efzc/1/
答案 1 :(得分:0)
修复了以下问题,创建了一个新参数并使用它来查找当前输入和span元素
function checkNotEmpty(veld, melding){ //maak functie aan geef parameters mee
if(veld.value.length != 0){ //als waarde ongelijk is aan 0 dan
console.log("OK"); //log OK
melding.innerHTML = "OK";
return true;
}
else {
console.log("NOT OK");
melding.innerHTML = "NOT OK";
return false;
}
}
window.onload = function(){
document.getElementById("naam").onblur = function(){
checkNotEmpty(this, document.getElementById('meldingNaam'));
};
document.getElementById("email").onblur = function(){
checkNotEmpty(this, document.getElementById('meldingEmail'));
};
document.getElementById("vraag").onblur = function(){
checkNotEmpty(this, document.getElementById('meldingVraag'));
};
};