私はこのプロジェクトを進めています。私は編集できないHTMLファイルが提供されました。 JavaSciptで厳密にDOM要素にアクセスする必要があります.JQueryはなく、JavaScriptだけです。今私は検証に取り組んでいます。これまで、ページをロードしてサブミットをクリックすると、最初の検証が機能します。しかし、ユーザーが年齢入力フィールドに値を入力したかどうかを確認するためにifステートメントをループしたいとします。私は下に私のコードを添付しました。最終的には、ユーザーが自分の年齢を入力するときに、送信ボタンをクリックするとリストを追加できるようになり、動的に作成する必要があります。ただし、年齢を入力しなかったり、数字以外の数字を入力したりすると、エラーが表示されます。それをどうすれば実現できますか?javascriptのみを使用してフォームを動的に検証する
var form = document.getElementsByTagName('form');
form.method = "POST";
form.action = "form-handler";
document.getElementsByTagName('button').onclick = checkAge();
function checkAge() {
var age = document.getElementsByName['age'];
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else {
alert("You entered: " + age.value);
return true;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
Here's my code pen for it too:
https://codepen.io/cfay1810/pen/QavNVL
コードあなたは簡単にこのようなコードでそれを行うことができますか? – Scath
_ "自分のコードを_umに添付しました"、 – j08691
コードを追加する前に投稿を提出しました... oops。 – ICode4Fun