私はシンプルなHTMLフォームの対話性に取り組んでいます。テキストフィールドがページに追加されないのはなぜですか?
具体的には、職務役割のためのドロップダウン選択ボックスがあります。 「その他」が選択されている場合は、テキストフィールドが表示され、より具体的にユーザーに確認する必要があります。
私は初心者であり、jQueryなしでこれを実行したいと考えています。ここで
は、私が働いているHTMLの抜粋です:
<fieldset class="basic">
<legend>Basic Info</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
<label for="mail">Email:</label>
<input type="email" id="mail" name="user_email">
<label>Job Role</label>
<select id="title" name="user_title">
<option value="full-stack js developer">Full Stack JavaScript Developer</option>
<option value="front-end developer">Front End Developer</option>
<option value="back-end developer">Back End Developer</option>
<option value="designer">Designer</option>
<option value="student">Student</option>
<option value="other">Other</option>
</select>
</fieldset>
私の直感は、最初のテキストフィールドを構築し、それの属性を追加するために私に語りました。
次に、if条件を使用して、選択したオプションが 'other'であるかどうかをテストします。そうであれば、新しく作成したテキストフィールドをページに追加します。
これまでこれまでは機能していません。これを試してデバッグするために、私は作業しようとしている要素をコンソールに記録しようとしました。私は、「未定義」と「ヌル」を印刷しているので、これがどのように機能するのか理解しているとは思わない。ここで
は私のJSです:
// TASK:あなたはユーザー発射される「変更」イベントをリッスンするイベントリスナーを設定する必要があり
'use strict';
// Hold DOM elements for easy access
var pageBody = document.querySelector('body');
var jobRoleSelect = document.getElementById('title');
console.log(jobSelected);
var jobSelected = jobRoleSelect.options[jobRoleSelect.selectedIndex].value;
var basicSection = document.querySelector('basic');
console.log(basicSection);
// Job Role section of the form. Reveal a text field when the "Other" option is selected from the "Job Role" drop down menu
if(jobSelected === 'other') {
var otherText = document.createElement('input');
// Add an text input field. Use the id of "other-title"
otherText.setAttribute('id', 'other-title');
otherText.setAttribute('type', 'text');
otherText.setAttribute('name', 'other_field');
otherText.setAttribute('placeholder', 'Your Title');
var otherLabel = document.createElement('label');
otherLabel.setAttribute('for', 'other_field');
otherLabel.innerHTML = 'other';
basicSelection.appendChild(otherLabel);
basicSelection.appendChild(otherText);
}
がどこJSコードから呼び出されたのですか?目的のために、select要素のchangeイベントハンドラから呼び出される関数内になければなりません。 '.querySelector()'を使ってクラス "basic"の要素を選択するには、 'document.querySelector( '。basic')'のようにクラス名の前に '.'を置く必要があります。また、select要素の選択値をより簡単に取得することもできます。 'jobRoleSelect.value'を使用するだけで、' .options'コレクションを経由する必要はありません。 (また、問題とは無関係に、あなたのラベルの 'for'属性は、' name'ではなく、関連要素の 'id'に設定する必要があります。) – nnnnnn
querySelectorに欠落した' .'を発見してくれてありがとう、私はそれを忘れてしまった。 身体の下部にJSをHTMLで添付しました。 別の機能が正常に機能しているので、大丈夫です。 私はちょうど使用することができます: 'var jobSelected = jobRoleSelect.value ' そしてif条件で' if(jobSelected ===' other ') 'を使用しますか? – gloopit