我有一个表单,当我在我的HTML文件中有DR,先生,夫人和小姐的不同复选框时。如果选中其中的任何一个,它将适用,输出名称的相应标题,如何在first_name
和last_name
之前显示。
<div class="tRow">
<div class="tCell"><label for="dr">Doctorate?</label></div>
<div class="tCell"><input type="checkbox" id="dr"></div>
</div><!--ROW STOPS-->
var employee = {
first_name: first_name,
last_name: last_name,
};
console.log(employee);
// Create the ouptut as HTML:
var message = employee.first_name + ", " + employee.last_name + "<br>";
// Display the employee object:
output.innerHTML = message;
答案 0 :(得分:0)
我认为你真的想要单选按钮,但也许不是。
var first_name = "Bob";
var last_name = "Dobbs";
var employee = {
first_name: first_name,
last_name: last_name,
};
var message = employee.first_name + ", " + employee.last_name;
var checkboxes = document.querySelectorAll('[type=checkbox]');
var output = document.querySelector('#output');
for (var ix = 0; ix < checkboxes.length; ix++) {
checkboxes.item(ix).addEventListener('click', onClick);
}
output.innerHTML = message;
function onClick() {
var newMessage = message;
for (var ix = checkboxes.length -1; ix > -1 ; ix--) {
if (checkboxes.item(ix).checked) {
newMessage = checkboxes.item(ix).id + " " + newMessage;
}
}
output.innerHTML = newMessage;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
<label><input type="checkbox" id="dr"><span class="label-body">Dr</label>
<label><input type="checkbox" id="mr"><span class="label-body">Mr</label>
<label><input type="checkbox" id="mrs"><span class="label-body">Mrs</label>
<label><input type="checkbox" id="miss"><span class="label-body">Miss</label>
<div id="output" style="text-transform: capitalize;"></div>
</div>
答案 1 :(得分:0)
通常表单控件采用一种形式,这使生活变得更加容易。在您希望用户选择其中一个项目的地方,选择或一组单选按钮效果最佳。
E.g:
function showFullName(el) {
// Get the parent form from the element that was clicked
var form = el.form;
// Get the value of the selected title radio button
var title = Array.prototype.filter.call(form.title, function(radio){
return radio.checked;
})[0].value;
// Write the full name to the span
document.getElementById('fullName').textContent =
title + ' ' + form.firstName.value + ' ' + form.lastName.value;
}
<form id="nameForm">
<table>
<tr>
<td>First name:
<td><input name="firstName">
<tr>
<td>Last name:
<td><input name="lastName">
<tr>
<td>Title:
<td><input name="title" type="radio" value="Ms" checked> Ms<br>
<input name="title" type="radio" value="Mr"> Mr
<tr>
<td colspan="2"><input type="button" value="Show full name" onclick="showFullName(this);">
<tr>
<td colspan="2"><span id="fullName"></span>
</table>
</form>
请注意,您需要提交按钮才能提交值。