【发布时间】:2016-08-31 08:49:00
【问题描述】:
我正在研究一个简单的 HTML 表单的交互性。
具体来说,有一个用于工作角色的下拉选择框。如果选择“其他”,则应出现一个文本字段,要求用户更具体。
我是一个初学者,想在没有 jQuery 的情况下做到这一点。
这是我正在使用的 HTML 的 sn-p:
<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 条件来测试所选选项是否为“其他”。如果是,那么我会将新创建的文本字段附加到页面。
到目前为止,这还没有奏效。为了尝试调试它,我尝试使用控制台记录我正在尝试使用的元素。我不认为我理解它是如何工作的,因为它打印出 'undefined' 和 'null'。
这是我的 JS:
// 任务:向表单添加交互性
'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 元素上的更改事件处理程序调用的函数中。要使用
.querySelector()选择类为'basic'的元素,您需要在类名前加上.,例如document.querySelector('.basic')。此外,您可以更简单地获取选择元素的选定值:只需使用jobRoleSelect.value,无需通过.options集合。 (另外,与您遇到的问题无关,标签中的for属性应设置为关联元素的id,而不是name。) -
感谢您发现查询选择器缺少的
.,我忘记了这一点。我在 HTML 的正文底部附加了 JS。我知道它可以连接,因为另一个功能可以正常工作。所以我可以使用:var jobSelected = jobRoleSelect.value' and then in the if condition, useif(jobSelected === 'other')`?
标签: javascript html forms dom drop-down-menu