I have a form and when I have different check boxes for DR., Mr., Mrs., and Miss in my HTML file. How can I make it so if any of those are checked it applies, the appropriate title to the output name, so it is displayed before the first_name and 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;
I think you actually want radio buttons, but maybe not.
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>
Usually form controls are in a form, which makes life much easier. And where you want users to select one of a few items, either a select or set of radio buttons works best.
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>
Note that you need a submit button to submit the values.
Related
I have a text input where user have to enter their surname and I want that surname as they enter it to appear below in a dropdown, using HTML and Javascript. This is my code so far but it does not work:
<form id= 'surnameReg'>
<label for='surname'>Surname:</label>
<input type='text' id="surname">
</form>
<form id='chooseSur'>
<label for="who">Who:</label>
<select id="who">
</select>
</form>
And my JS:
function drop() {
var surnArr=[];
var select = document.getElementById("who");
for(var i = 0; i <surnArr.length; i++) {
var sur= surnArr[i];
var op = document.createElement("option");
op.textContent = sur;
op.value = sur;
select.appendChild(op);
}
}
You can set an event listener on the first form on submit and then create and append the option as follows:
document.getElementById("surnameReg").addEventListener("submit",function(e){
e.preventDefault();
let surname = document.getElementById("surname").value;
if(surname){
var select = document.getElementById("who");
var op = document.createElement("option");
op.textContent = surname;
op.value = surname;
select.appendChild(op);
}
});
<form id= 'surnameReg' >
<label for='surname'>Surname:</label>
<input type='text' id="surname" >
</form>
<form id='chooseSur' >
<label for="who">Who:</label>
<select id="who">
</select>
</form>
I have a script posted down below, and I want the user to add a new field, when the new field gets added I want a new var to be added.
Live example:
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
I don't have an idea of how to do the above honestly.
<!DOCTYPE html>
<html lang="en">
<form name="TRF" method="post">
<p style="color:white">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="jumbotron">
<h1 class="text-center">Accepted Format</h1>
<hr>
<div class="row">
<h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
<table style="width:100%" id="theTable">
<tr>
<td>Applicant's Name:</td>
<td><input type="text" name="accname" size="75" placeholder="" required></td>
</tr>
<tr>
<td>Reason 1:</td>
<td><input type="text" name="R1" size="75" placeholder="" required></td>
</tr>
<tr>
<td id="bla">Reason 2:</td>
<td><input type="text" name="R2" size="75" placeholder="" required></td>
</tr>
</table>
<h3>CODE:</h3>
<textarea id="box" cols="100" rows="10"></textarea>
<p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>
</div>
<button id="newField">
add new field
</button>
</center>
</div>
</div>
</div>
</div>
<html>
<head>
<script>
function generateCode2() {
var AccoutName = document.forms["TRF"]["accname"].value;
var Reason1 = document.forms["TRF"]["R1"].value;
var Reason2 = document.forms["TRF"]["R2"].value;
document.getElementById("box").value =
"[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]"+
"[hr]"+
"\n"+
"[b]Dear[/b] "+AccoutName+
"\n"+
"After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. "+
"\n"+
"Reason One: " +Reason1+
"\n"+
"Reason Two: " +Reason2+
"\n"+
"Welcome to the Family. "+
"\n"+
""
}
var newField = document.getElementById("newField");
var counter = 3;
function createNewField() {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td1.innerHTML = "Reason " + counter + ":";
var inp = document.createElement("input");
inp.type = "text";
inp.size = "75";
inp.name = "R" + counter;
inp.value=document.getElementById("box").value;
td2.appendChild(inp);
document.getElementById("theTable").appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
counter++;
}
newField.addEventListener("click", createNewField);
(function () {
var onload = window.onload;
window.onload = function () {
if (typeof onload == "function") {
onload.apply(this, arguments);
}
var fields = [];
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < inputs.length; i++) {
fields.push(inputs[i]);
}
for (var i = 0; i < textareas.length; i++) {
fields.push(textareas[i]);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
}
if (typeof field.onpaste == "function") {
var oninput = field.oninput;
field.oninput = function () {
if (typeof oninput == "function") {
oninput.apply(this, arguments);
}
if (typeof this.previousValue == "undefined") {
this.previousValue = this.value;
}
var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
if (pasted && !this.onpaste.apply(this, arguments)) {
this.value = this.previousValue;
}
this.previousValue = this.value;
};
if (field.addEventListener) {
field.addEventListener("input", field.oninput, false);
} else if (field.attachEvent) {
field.attachEvent("oninput", field.oninput);
}
}
}
}
})();
</script>
</head>
</color>
</font>
</div>
</div>
</div>
</html>
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
In Javascript it's possible to create html elements at runtime using the createElement() function. In your case we need to create quite a lot of individual elements to replicate the structure of the table. Those are <tr> <td> <input>.
The tr element needs to be added to the table, the td containing the text 'Reason #:' as well as the td holding the input element are childs of tr. To add a dynamically created element to the DOM, the appendChild() function is used.
The input element needs some special treatment because it contains an unique id. The two html-made elements you have are 'R1' and 'R2' - so a new one should follow that pattern and start with 3. This is done by setting up a global variable , appending it to the name and increment it afterwards.
Finally we need to add a 'Create new field' button.
Take a look at this example (you have to scroll down to see the button):
var newField = document.getElementById("newField");
var counter = 3;
function createNewField() {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td1.innerHTML = "Reason " + counter + ":";
var inp = document.createElement("input");
inp.type = "text";
inp.size = "75";
inp.name = "R" + counter;
td2.appendChild(inp);
document.getElementById("theTable").appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
counter++;
}
newField.addEventListener("click", createNewField);
function generateCode2() {
var AccoutName = document.forms["TRF"]["accname"].value;
var reasons = "";
for (var a = 1; a < counter; a++) {
reasons += "Reason " + a + ": " + document.forms["TRF"]["R" + a].value + "\n";
}
document.getElementById("box").value =
"[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]" +
"[hr]" +
"\n" +
"[b]Dear[/b] " + AccoutName +
"\n" +
"After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. " +
"\n" + reasons +
"Welcome to the Family. " +
"\n" +
""
}
<form name="TRF" method="post">
<p style="color:white">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="jumbotron">
<h1 class="text-center">Accepted Format</h1>
<hr>
<div class="row">
<h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
<table style="width:100%" id="theTable">
<tr>
<td>Applicant's Name:</td>
<td><input type="text" name="accname" size="75" placeholder="" required></td>
</tr>
<tr>
<td>Reason 1:</td>
<td><input type="text" name="R1" size="75" placeholder="" required></td>
</tr>
<tr>
<td id="bla">Reason 2:</td>
<td><input type="text" name="R2" size="75" placeholder="" required></td>
</tr>
</table>
<h3>CODE:</h3>
<textarea id="box" cols="100" rows="10"></textarea>
<p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>
</div>
<button id="newField">
add new field
</button>
</center>
</div>
</div>
</div>
</div>
I have a little problem with my template.
I would like to read in a template with jquery and then find all inputs within this object to manipulate them.
Unfortunately, the inputs are not returned.
I already use the function "checkInputs" in another place.
The target is not a template and it works without problems.
Here's my test code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
And here is my template:
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
The thing is that script tag does not parse the HTML and create a DOM out of it.
Its contents are just a string.
To be able to select from it, you should parse it (you can do it with jQuery) and select from the created (parsed) object.
Notice in the code below I first create a "mini (virtual) DOM" out of your template's text contents:
var miniDOM = $($(target).text());
And now use all selectors having it as context/root. E.g.
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
This finds the elements as you wanted.
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var miniDOM = $($(target).text());
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
miniDOM.find("input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
miniDOM.find("input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
Of course, you could, alternatively, turn that script into any renderable element, like div or span, even if hidden, and you could query it with your original code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="IncomingInformationsTemplate" style="display: none">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</div>
you should find inputs with this method
$('#IncomingInformationsTemplate').find(':input').each(function(i,e) {
console.log((i+1)+'. '+$(e)[0].outerHTML);
$(e).addClass('manipulate-it'); //manipulate it
});
I have a textbox where users can enter their name and 2 radio buttons, one for Mr. and one for Mrs. .
When the user hits the submit button I want a function to run that checks which radio button the user checked and add it to their name, then store it in a list.
For example lets say they enter their name as John and click the Mr. box. I want it to add Mr. to john and then store it in a list. So it would store Mr.John is a list.
Im at a loss as to how to do this, Heres what I've got so far:
var UserNames = []
var NameAdd = function() {
var name = document.getElementById("nametextbox").value;
UserNames.push("name");
}
If that code is correct it should take the input from the textbox and store it in a list.
Heres the css for the radio buttons:
#CheckBox1,#CheckBox2 {
float:left;
margin: 600px 20px 20px 60px;
color: #b2aba4;
}
And heres the html:
<div id="CheckBox1"><input type="radio" Name="Mr."/>Mr.</div>
<div id="CheckBox2"><input type="radio" Name="Mrs."/>Mrs.</div>
Any help is appreciated im at a loss here. Ik that it should be a if/else statement but past that im clueless.
I would change your markup to this:
<div id="CheckBox1"><input type="radio" name="salutation" value="Mr." />Mr.</div>
<div id="CheckBox2"><input type="radio" name="salutation" value="Mrs." />Mrs.</div>
and you can then get the value with this JavaScript:
var salutation = document.querySelector('input[name = "salutation"]:checked').value;
If you want it at Client side this may help you:
WORKING:DEMO
JS
$("button").click(function()
{
var curSex = $("input[type=radio]").val();
var curName = $("input[type=text]").val();
document.getElementById("print").innerHTML = "Hello" + " " + curSex + curName;
});
HTML
<div id="CheckBox1"><input type="radio" Name="Mr." value="Mr." />Mr.</div>
<div id="CheckBox2"><input type="radio" Name="Mrs." value="Mrs." />Mrs.</div>
Enter Name : <input type="text" name="name" />
<button>Submit</button>
<p id="print"></p>
<form name="send" method="POST">
<input type="text" name="name" id ="userName" />
<div id="CheckBox1"><input type="radio" id ="mr" value="Mr." Name="title"/>Mr.</div>
<div id="CheckBox2"><input type="radio" id ="mrs" value="Mrs." Name="title"/>Mrs.</div>
<input type="button" name="button" value="Submit" onClick="getInfo(this.form);" />
</form>
<p id="info"></p>
java script code
function getInfo(form) {
var userName = document.getElementById("userName");
var mr = document.getElementById('mr');
var mrs = document.getElementById('mrs');
var data = [];
if (userName.value !== "") {
if (mr.checked) {
data.title = mr.value;
mrs.checked = false;
} else if (mrs.checked) {
data.title = mrs.value;
mr.checked = false;
}
data.name = userName.value;
document.getElementById("info").innerHTML = "Hello:" + data.title + " " + data.name;
}
//console.log(data);
}
demo
i was wondering if i can make the title of an accordion a button as well without the button feeling?
here is a picture of the accordion title and some data inside it?
i want to click on the text that is in the title to navigate to a page...
using phonegap/cordova v1.9. Visual studio 2010 express for windows phone/html,CSS,javascript (c#)
any help will be appreciated :) im open to a solution in anyway, including jquery's
title is
inboxentry1 POS556445
I have made the accordion in a bunch of div's that stacked into eachother...
tell me if i must add anything else to help with the solution!
here is some html for the accordion!
<div id="AccordionContainer" class="AccordionContainer"></div>
<div onclick="runAccordion(1)">
<div class="Accordiontitle" onselectstart="return false;">
<input type="button" href="ItemPages.html">inbox entry1</input>
<br/>
<a>POS556446x</a>
</div>
</div>
<div id="Accordion1Content" class="AccordionContent" style="background-color:white; color:grey;">
<form>
<p>
<label for="create" >Created by :</label>
<input type="text" style="margin-left:60px;" size="22" id="create"/>
</p>
<p>
<label for="createdate" >Created Date :</label>
<input type="text" style="margin-left:43px;" size="22" id="createdate"/>
</p>
<p>
<label for="process" >Process name :</label>
<input type="text" style="margin-left:36px;" size="22" id="process"/>
</p>
<p>
<label for="transtype">Transaction type :</label>
<input type="text" style="margin-left:20px;" size="22" id="transtype"/>
</p>
<p>
<label for="lastact">Last action :</label>
<input type="text" style="margin-left:61px;" size="22" id="lastact"/>
</p>
<p>
<label for="lastuser">Last user :</label>
<input type="text" style="margin-left:73px;" size="22" id="lastuser"/>
</p>
<p>
<label for="lastupd">Last update :</label>
<input type="text" style="margin-left:55px;" size="22" id="lastupd"/>
</p>
<p>
<label for="duration">Duration :</label>
<input type="text" style="margin-left:78px;" size="22" id="duration"/>
</p>
<p>
<label for="saved">Saved :</label>
<input type="text" style="margin-left:93px;" size="22" id="saved"/>
</p>
<p>
<label for="adhoc">Ad hoc user :</label>
<input type="text" style="margin-left:53px;" size="22" id="adhoc"/>
</p>
</form>
</div>
here is my .js file
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
var nID = "Accordion" + index + "Content";
if (openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if (timeLeft <= elapsedTicks) {
if (opening != null)
opening.style.height = ContentHeight + 'px';
if (closing != null) {
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
if (opening != null) {
if (opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if (closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}
You probably want to make some changes here. A few classes have been added and the button tag changed as it wasn't correct. Your want to remove the inline event you have for the accordion and stick it where commmented below.
<div class="AccordionRun">
<div class="Accordiontitle" onselectstart="return false;">
<input class="AccordionLink" type="button" href="ItemPages.html" value="inbox entry1">
<br/>
<a>POS556446x</a>
</div>
</div>
Then you can get it and add a click event to it...
var goToPage = function(elem) {
elem.onclick = function() {
alert('Go to page...');
window.location = elem.href;
};
};
var runAccordion = function(elem) {
elem.onclick = function() {
alert('Run Accordion...');
// Your accordion code goes here...
};
};
var buttons = document.getElementsByTagName('input');
for(var i=0; i < buttons.length; i++) {
if (buttons[i].className == 'AccordionLink') {
goToPage(buttons[i]);
}
}
var divs = document.getElementsByTagName('div');
for(var i=0; i < divs.length; i++) {
if (divs[i].className == 'AccordionRun') {
runAccordion(divs[i]);
}
}
jsfiddle.net/FKt4K/2
If you'd like to navigate to an other page on click of an input field, here's a simpe work-around.. Just bind it to a mouseup-event like so (needs a jQuery implemention):
UPDATED CODE
HTML:
<input class="followThisRel" type="button" rel="http://yoursite.com/">
JS:
$(function() {
$('input.followThisRel').on('click', function() {
var url = $(this).attr('rel');
window.location = url;
});
})