Populate a dropdown with previous user input - javascript

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>

Related

How to insert user selected value from datalist dropdown into a template string to be shown as a message to the user when submitted?

I have 2 datalists in the form below. I'm trying to get selected variable values (let input1 & let input2) to show in the message that appears when submitted via template string variable let message but it's not working. I'm not getting any errors.
Any idea why it does not work? And can event listeners be simplified so that I don't have to write out a new variable for each one since I have 4 datalists?
const victory = document.createElement('audio'),
form = document.querySelector('form'),
nameInput = document.querySelector('#name-input'),
surnameInput = document.querySelector('#surname-input'),
footer = document.querySelector('#footer');
const messageBox = document.createElement('div');
messageBox.setAttribute('class', 'message-box');
victory.src = 'sound/victory.mp3';
let input1 = nameInput.addEventListener('input', () => {
const nameValue = surnameInput.value;
});
let input2 = surnameInput.addEventListener('input', () => {
const surnameValue = surnameInput.value;
});
form.addEventListener('submit', (e) => {
e.preventDefault();
let message = `You have succesfully ordered ${input1} ${input2}`;
messageBox.appendChild(document.createTextNode(message));
victory.play();
footer.parentNode.insertBefore(messageBox, footer);
messageBox.style.backgroundColor = 'green';
messageBox.style.textAlign = 'center';
messageBox.style.margin = '0 1rem 2rem';
messageBox.style.padding = '1rem';
messageBox.style.borderRadius = '5px';
});
<form action="">
<fieldset>
<legend>Choose your skater</legend>
<div>
<label>Name</label>
</div>
<div>
<input id="name-input" list="name" type="text" title="Select desired name of your skater">
<datalist id="name">
<option value="Tony" data-id="1"></option>
<option value="Joe" data-id="2"></option>
<option value="Paul" data-id="3"></option>
<option value="Scott" data-id="4"></option>
</datalist>
</div>
<div>
<label>Surname</label>
</div>
<div>
<input id="surname-input" list="surname" type="text" title="Select desired surname of your skater">
<datalist id="surname">
<option value="Hawk" data-id="1" label="james"></option>
<option value="Carter" data-id="2"></option>
<option value="Philmore" data-id="3"></option>
<option value="Venice" data-id="4"></option>
</datalist>
</div>
</fieldset>
<button class="btn" type="submit" title="Submit your choice">Submit</button>
</form>
<footer id="footer"></footer>
The way you capture your input values is wrong. This will work.
let input1 = '';
nameInput.addEventListener('input', () => {
input1 = nameInput.value;
});
let input2 = '';
surnameInput.addEventListener('input', () => {
input2 = surnameInput.value;
});

unable to get check boxes value from table

I am not able to get the checkboxes values from checkboxes to Firebase.
How will I be able to get each value from each box from each row?
Table:
Check boxes:
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
Table
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
full form
<div class="form-popup" id="myFormDetails">
<div class="shipDetailsRequest">
<form action="" method="post" class="form-container" >
<button type="button" onclick="closeForm()" id="close">x</button>
<input name="RR" type="RRField" id="date" disabled>
<input name="RR" type="RRField" id="RRField" placeholder="RR Field" disabled>
<p>Customer Details</p>
<input onclick="sampleFunction()" type="number1" placeholder="Customer Account Number" name="customerAccountField" id="customerAccountField" required>
<input type="number1" placeholder="Customer Name" name="customerNameField" id="customerNameField" disabled>
<p>Shipper Details</p>
<input type="number1" placeholder="Shipper Name" name="senderName" id="shipperName" required>
<textarea name="collectionAddress" placeholder="Collection Address...?" id="collectionAddress"></textarea>
<p>Shipment Details</p>
<input type="text" placeholder="Enter Origin" name="shptOrigin" id="shipmentOrigin" maxlength = "3" required>
<input type="text" placeholder="Enter Destination" name="shptDest" id="shipmentDest" maxlength = "3" required>
<input type="number" placeholder="Enter Weight" name="shptWeight" id="shptWeight" required>
<input type="number" placeholder="Enter Pieces" name="shptPieces" id="shptPieces" required>
<input type="number1" placeholder="Enter Dimensions" name="shptDimensions" id="shipmentDimensions" >
<select placeholder="Choose Type" name="shptStack" id="shptStack" required>
<option value="Stackable">Stackable</option>
<option value="Nonstackable">Nonstackable</option>
</select>
<select placeholder="Choose Desk" name="Desk" id="ChooseDesk" required>
<option value="KSA">KSA Desk</option>
<option value="DHA">DHA Desk</option>
<option value="RUH">RUH Desk</option>
<option value="JED">JED Desk</option>
</select>
<p>Comment</p>
<textarea name="comment" placeholder="Other Details...?" id="commentField"></textarea>
<div class="mainDiv" align="center" >
<input type="file" id="fileButton" />
<progress id="uploader" value="0" max="100" style="max-width: 128px;">0%</progress>
</div>
<!-- <button id="submitBtn" onclick="ActionData()">Next</button> -->
<button id="submitBtn" onclick="ActionData()">Next</button>
</form>
</div>
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
Full JavaScript
var DateText = document.getElementById("date");
var RRText = document.getElementById("RRField");
var CustAccText = document.getElementById("customerAccountField");
var CustNameText = document.getElementById("customerNameField");
var ShipperNameText = document.getElementById("shipperName");
var CollectionAddressText = document.getElementById("collectionAddress");
var ShipmentOrgText = document.getElementById("shipmentOrigin");
var ShipmentDestText = document.getElementById("shipmentDest");
var ShipmentweightText = document.getElementById("shptWeight");
var ShipmentPiecesText = document.getElementById("shptPieces");
var ShipmentDimensionsText = document.getElementById("shipmentDimensions");
var ShptStackText = document.getElementById("shptStack");
var ChooseDeskText = document.getElementById("ChooseDesk");
var CommentText = document.getElementById("commentField");
var ShipmentOriginValues = ShipmentOrgText.value;
ShipmentOriginValues = "All";
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
if (ShipmentOrgText.value != null)
{
var rootRefReAgents = firebase.database().ref().child("AgentsContact").child(ShipmentOriginValues);
rootRefReAgents.on("child_added", snap =>{
var AgentEmail = snap.child("Name").val();
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
});
}
function ActionData()
{
//setting up values from Text Fields
var DateValue = DateText.value;
var RRValue = RRText.value;
var CustAccountValue = CustAccText.value;
var CustNameValue = CustNameText.value;
var ShipperNameValue = ShipperNameText.value;
var CollectionAddressValues = CollectionAddressText.value;
ShipmentOriginValues = ShipmentOrgText.value;
var ShipmentDestValues = ShipmentDestText.value;
var ShipmentweightValues = ShipmentweightText.value;
var ShipmentPiecesValues = ShipmentPiecesText.value;
var ShipmentDimensionsValues = ShipmentDimensionsText.value;
var ShptStackValues = ShptStackText.value;
var ChooseDeskValues = ChooseDeskText.value;
var CommentValues = CommentText.value;
var FirebaseRef = firebase.database().ref("Requests").child(RRValue);
if(RRValue && ShipmentOriginValues && ShipmentDestValues && CustAccountValue == null)
{
window.alert("Need More details to upload")
}
else
{
FirebaseRef.child("Date").set(DateValue);
FirebaseRef.child("RR").set(RRValue);
FirebaseRef.child("Customer Account").set(CustAccountValue);
FirebaseRef.child("Customer Name").set(CustNameValue);
FirebaseRef.child("Shipper Name").set(ShipperNameValue);
FirebaseRef.child("Collection Address").set(CollectionAddressValues);
FirebaseRef.child("Origin").set(ShipmentOriginValues);
FirebaseRef.child("Destination").set(ShipmentDestValues);
FirebaseRef.child("Weight").set(ShipmentweightValues);
FirebaseRef.child("Pieces").set(ShipmentPiecesValues);
FirebaseRef.child("Dimensions").set(ShipmentDimensionsValues);
FirebaseRef.child("Stack").set(ShptStackValues);
FirebaseRef.child("Desk").set(ChooseDeskValues);
FirebaseRef.child("Comment").set(CommentValues);
FirebaseRef.child("Status").set("Pending");
//Uploading
fileButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = firebase.storage().ref('img/'+RRValue+'/'+file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
uploader.value = percentage;
}, function error(err) {
},function complete() {
});
});
}
}
I need to check boxes from the table and get their values back to Firebase when form is submitted.
You could specify an id or name for each input and then retrieve their value when you submit the form.
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><input type=\"checkbox\" id=\""+AgentEmail+"\" Value =\"Agent\"></Input></td></tr>")
var agents = ... //Get your agents list from firebase
$form.on('submit', function(){
agents.forEach(function(agent){
if($('#'+agent.email).prop('checked'){
//do something
}
})
})
If your code is working, you can ckeck if a checkbox is checked with:
/* jQuery */
if ($('#check_id').is(":checked"))
{
// checkbox is checked
}
you can also use:
/* jQuery */
$("#idOfCurrentRow").children()."input[type='checkbox']") is(":checked")
If you prefer pure JavaScript:
/* pure JavaScript*/
if(document.getElementById("idOfYourCheckbox").checked) {
...
}
or
if (document.getElementByName("nameOfYourCheckbox").checked) {
.....
}

Refactoring keyup function

I'm trying to make a form previewer.
The idea is to make a layer that shows user info printed on a div by default, but with the possibility of modifying their data in real time and show it in the box.
My code works, but I don't know how to simplify it.
Here's my code:
function preview() {
$('#previewName').html($('#Name').val());
$('#Name').keyup(function () {
$('#previewName').html($(this).val());
});
$('#previewDirection').html($('#Direction').val());
$('#Direction').keyup(function () {
$('#previewDirection').html($(this).val());
});
$('#previewPostal').html($('#Postal').val());
$('#Postal').keyup(function () {
$('#previewPostal').html($(this).val());
});
$('#previewCountry').html($('#Country option:selected').text());
$('#Country option:selected').change(function () {
$('#previewCountry').text($(this).text());
});
}
<form id="form">
<div>
<div>
<label>Name</label>
<input type="text" id="Name" name="Name" value="">
</div>
<div>
<label>Direction</label>
<input type="text" id="Direction" name="Direction">
</div>
<div>
<label>Postal</label>
<input type="text" id="Postal" name="Postal">
</div>
<div>
<label>Country</label>
<div>
<select name="Country" id="Country">
<option value="">x</option>
<option value="">y</option>
</select>
</div>
</div>
</div>
<div>
<div class="box">
<p class="strong" id="previewName"></p>
<p class="mb0" id="previewDirection"></p>
<p id="previewPostal"></p>
<p id="previewCountry"></p>
</div>
</div>
</form>
Any idea?
You can simplify this by querying the form input elements and using the id and value to update the preview.
// cache form selector
var form = $('#form');
// cache all form input elements
var inputs = form.find('input');
// cache all form select elements
var selects = form.find('select');
inputs.keyup(function(){
var id = this.id,
value = this.value;
$('#preview' + id).html(value);
});
selects.change(function(){
var id = this.id,
option = $(this).find('option:selected'),
value = option.val();
$('#preview' + id).html(value);
});
or a condensed version
$('#form input').keyup(function(){
var id = this.id,
value = this.value;
$('#preview' + id).html(value);
});
$('#form select').change(function(){
var id = this.id,
option = $(this).find('option:selected'),
value = option.val();
$('#preview' + id).html(value);
});
Demo

getting value from input and displaying in a div

I am trying to get the value of an input and display it in a div under it, while the user is typing. and i want to do it with vanilla js. no j query.
MY HTML:
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>
MY JS:
var input = document.getElementById('inputText').value;
var showQuestion = document.getElementsByClassName('displayQuestion');
function myDisplay(e){
showQuestion.innerHTML = input;
}
Try this:
function myDisplay(e) {
var input = document.getElementById('inputText').value;
var showQuestion = document.getElementById('displayQuestion');
showQuestion.innerHTML = input;
}
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay(this.value)"/>
</div>
<div id="displayQuestion"></div>
Here you go with VannilaJS way,
Recommendation: Change the name of the function myDisplay() to something meaningful like displayQuestion()
var targetElm = document.getElementsByClassName('displayQuestion');
var inputElm = document.getElementById('inputText');
function myDisplay() {
if(targetElm && targetElm.length > 0){
targetElm[0].innerHTML = inputElm.value;
}
}
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size ="50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>

Add a Drop Down Option in an HTML form

Can I add a drop down option on two of my forms like on the Gender (Male or Female Option) and on the VERID if (Yes or No) and then when I click on submit it will show the one that i inputted?
<form id="myForm">
Phone: <br><input type="text" name="Phone Number" placeholder="Phone Number"/><br/>
Gender: <br><input type="text" name="Gender" placeholder="Gender"/><br/>
INBOUND: <br><input type="text" name="INBOUND" placeholder="INBOUND"/><br/>
Name: <br><input type="text" name="Name" placeholder="Name"/><br/>
Status: <br><input type="text" name="Status" placeholder="Status" /><br/>
<button type="button" onclick="ShowText();">Submit</button>
</form>
<p>Result:</p>
<p><textarea cols=40 rows=8 id="show" onClick='selectText(this);'></textarea></p>
<script>
function ShowText(){
// find each input field inside the 'myForm' form:
var inputs = myForm.getElementsByTagName('input');
// declare 'box' variable (textarea element):
var box = document.getElementById('show');
// clear the 'box':
box.value = '';
// loop through the input elements:
for(var i=0; i<inputs.length; i++){
// append 'name' and 'value' to the 'box':
box.value += inputs[i].name + ': '+inputs[i].value+'\n';
}
}M
function selectText(textField)
{
textField.focus();
textField.select();
}
</script>
<textarea rows="8" cols="40">
Issue:
Steps:
</textarea>
In your form you should use select instead of input
<select name="Gender" placeholder="Gender"><option>Male<option>Female</select>
Next you can get the input tag and select tag using querySelectorAll
var inputs = myForm.querySelectorAll('input,select');
Putting all together :
<form id="myForm">
Gender:<select name="Gender" placeholder="Gender"><option>Male<option>Female</select><br/>
Name:<input type="text" name="Name" placeholder="Name"/><br/>
<button type="button" onclick="ShowText();">Submit</button>
</form>
<p>Result:</p>
<p><textarea cols=40 rows=8 id="show" onClick='selectText(this);'></textarea></p>
<script>
function ShowText(){
// find each input field inside the 'myForm' form:
var inputs = myForm.querySelectorAll('input,select');
// declare 'box' variable (textarea element):
var box = document.getElementById('show');
// clear the 'box':
box.value = '';
// loop through the input elements:
for(var i=0; i<inputs.length; i++){
// append 'name' and 'value' to the 'box':
box.value += inputs[i].name + ': '+inputs[i].value+'\n';
}
}
function selectText(textField) {
textField.focus();
textField.select();
}
</script>

Categories

Resources