How do I make a dynamic drop down menu using JavaScript - javascript

I have it so you type in on a form a maximum number then it creates a table after clicking a button.
I want it so after you click the button to add the row it writes a drop down menu in the table that goes from 0 to the number you put in the form
This is my HTML code:
<html>
<head>
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<script language="JavaScript" src="../js/exercise2.js" type="text/javascript">
</script>
</head>
<body>
<p>
<button class="button" data-modal="M2KM">Form Generator</button>
</p>
<div id="M2KM" class="modal">
<div class="modal-content">
<div class="form">
<a class="close">Ă—</a>
<form action="">
<textarea rows="1" name="Section" id="Section" cols="10">Section</textarea>
<textarea rows="1" name="Max" id="Max" cols="10">Max</textarea>
<textarea rows="1" name="Comment" id="Comment" cols="10">Comment</textarea>
<textarea rows="1" name="Mark" id="Mark" cols="10">Mark</textarea>
<input type="button" value="Add Row" name="Add Row" onclick="conversionTable('table')" />
<input type="reset" value="Clear" name="Clear">
</form>
<div id="conversion">
<table id="table">
<thead>
<tr>
<th>Section</th>
<th>Max</th>
<th>Comment</th>
<th>Mark</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
This is my JavaScript Code:
function conversionTable(tagId, from, to)
{
var section = document.getElementById("Section").value;
var max = document.getElementById("Max").value;
var comment = document.getElementById("Comment").value;
var mark = document.getElementById("Mark").value;
from = 0;
to = 1;
var total = 0;
var arr = [];
var conv = document.getElementById(tagId) ;
var pre = document.createElement("pre");
conv.appendChild(pre);
var body= conv.appendChild(document.createElement("tbody"));
for (var i=from; i<to; i++)
{ row = body.appendChild(document.createElement("tr"));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(section));
data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(max));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(comment));
data=row.appendChild(document.createElement("select"));
data.setAttribute("id", "mySelect");
row.appendChild(data);
var z = document.createElement("option");
z.setAttribute("value", "volvocar");
var t = document.createTextNode("1");
z.appendChild(t);
document.getElementById("mySelect").appendChild(z);
total = total + mark;
var obj = {section: section, max: max, comment: comment, mark: mark};
arr.push(obj);
}
}
This is a screenshot showing test data:

Here's a simplified example that adds a select element with a number of options equal to the number entered by the user.
See comments in the code for an explanation of how it works.
// Identifies existing HTML elements
const maxInput = document.getElementById("max");
const button = document.getElementById("button");
const table = document.getElementById("table");
// Calls `addDropdown` when `button` is clicked
button.addEventListener("click", addDropdown);
// Defines the event listener
function addDropdown(event) { //(`event` object is available if we want it)
// Gets value from input
let max = parseInt(maxInput.value);
// Exits function early if maxInput doesn't have a number
if(!max){ return; }
// Defines the new elements
const row = document.createElement("tr");
const cell = document.createElement("td");
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let optNumber = -1;
while(++optNumber <= max){
let optionElement = document.createElement("option");
optionElement.value = "opt" + optNumber;
optionElement.innerHTML = "Option " + optNumber;
dropdown.appendChild(optionElement);
}
// Adds the elements to the page
cell.appendChild(dropdown);
row.appendChild(cell);
table.appendChild(row);
}
<label>
<span>Enter maximum value for dropdown:</span>
<input id="max" value="5" />
</label>
<br />
<button id="button">Add Dropdown in New Row</button>
<div id="container">
<table id="table"></table>
</div>

Related

I want to save the data in a textbox created repeatedly in JavaScript using webstorage

this is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>CV Information</title>
<link rel="stylesheet" href="StyleSheet1.css" />
</head>
<body>
<header><b>CV Information</b></header>
<!--<script src="Script1.js"></script>-->
<div class="mydiv">
<form action="CV_Viewer.html">
<fieldset id="field">
<div class="scrollable" id="scroll">
<header>Languages</header><br />
<label for="mLan">Your Mothertoungue:</label>
<input type="text" id="mLan" placeholder="Primary Language.." name="name" pattern="[A-Za-z ]{3,}" required><br><br>
<input type="button" id="plus" onclick="addTextBox()" class="plus" value="+ other languages..." name="plus" />
</div>
<div style="position: static">
<input type="submit" onclick="webstorage()" class="hov" style="margin-top:30px" value="Next">
</div>
</fieldset>
</form>
</div>
<footer>
Copyright©2022 Rami Joulani
</footer>
<script>
let b = 1;
let q=0;
const array = [];
function addTextBox() {
b++;
const textBox = document.createElement("INPUT");
textBox.setAttribute("type", "text");
textBox.setAttribute("placeholder", "Any Other Language...");
textBox.setAttribute("pattern", "[A-Za-z ]{3,}");
textBox.setAttribute("style", "margin-top:35px;");
textBox.setAttribute("id",q);
const div = document.getElementById("scroll");
div.appendChild(textBox);
var plus = document.getElementById("plus");
div.insertBefore(textBox, plus);
array[q] = textBox.value;
console.log(array[q]);
q++;
return fieldSet();
}
function fieldSet() {
const radio1 = document.createElement("input");
radio1.setAttribute("type", "radio");
radio1.setAttribute("id", "rad1");
radio1.setAttribute("name", "connected");
const div = document.getElementById("scroll");
var plus = document.getElementById("plus");
div.appendChild(radio1);
div.insertBefore(radio1, plus);
const begg = document.createElement("label");
begg.setAttribute("for", "rad1");
const begginer = document.createTextNode("Begginer");
begg.appendChild(begginer);
div.appendChild(begg);
div.insertBefore(begg, plus);
const radio2 = document.createElement("input");
radio2.setAttribute("type", "radio");
radio2.setAttribute("id", "rad2");
radio2.setAttribute("name", "connected")
div.appendChild(radio2);
div.insertBefore(radio2, plus);
const inter = document.createElement("label");
inter.setAttribute("for", "rad2");
const intermadiate = document.createTextNode("Intermadiate");
inter.appendChild(intermadiate);
div.appendChild(inter);
div.insertBefore(inter, plus);
const radio3 = document.createElement("input");
radio3.setAttribute("type", "radio");
radio3.setAttribute("id", "rad3");
radio3.setAttribute("name", "connected")
div.appendChild(radio3);
div.insertBefore(radio3, plus);
const flu = document.createElement("label");
flu.setAttribute("for", "rad3");
const fluent = document.createTextNode("Fluent");
flu.appendChild(fluent);
div.appendChild(flu);
div.insertBefore(flu, plus);
plus.setAttribute("style", "margin-top:20px;")
if(b==4) {
plus.hidden=true;
}
}
function webstorage() {
localStorage.setItem("mothTong", document.getElementById("mLan").value);
}
</script>
</body>
</html>
I changed it multiple times when I tried to solve it
how can I save textBox value and the radio button values separately though they are created with the same attribute
it might be simple but I just couldn't figure it out.
Don't point out to some missing stuff but if you please tell me how is it possible to do it depending on the general form of the code.

for loop with array of strings rendering the same thing twice?

I am building in javascript a simple feedback that has a text area and is grabbing the text and displaying a successful message when the add button is clicked. When the view feedback button is clicked it should render the feedback and it does but if I click the button once and then type in the text area again and again it keeps rendering multiple times the same feedback message. Attached is my javascript code.
var array = Array();
var x = 0;
function addFeedback() {
array[x] = document.getElementById('feedback').value;
x++;
document.getElementById('feedback').value = '';
document.getElementById('result').innerHTML =
'<h2><h3> Your have successfully Added Feedback!</h3></h2>';
}
var feedback = '';
function displayFeedback() {
for (var i = 1; i < array.length + 1; i++) {
feedback = array[i - 1] + '<br/>';
console.log(feedback);
}
document.getElementById('result').innerHTML =
'<h2>feedback Details: </h2>' + feedback.split('<br>');
}
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<!-- Fill code here -->
<div>
<h2>Feedback for the ART OF LIVING</h2>
<div>
<label for="feedback"></label>Enter the Feedback:
<textarea id="feedback" name="feedback" value="feedback" type="text"></textarea>
<div>
<input type="button" id="create" name="create" onclick="javascript:addFeedback()">Add Feedback</input><br/>
<input type="button" id="view" name="view" onclick="javascript:displayFeedback()">View feedback</input>
</div>
<div id="result"></div>
</div>
</div>
</body>
</html>

Converting JavaScript Object to Float

I am currently trying to make an application where I can add up the columns of an HTML table. I am able to add inputs to the table but when I try to add up the columns I get, "NaN" error.
/* Function to calculate income */
function Add() {
// Variables from input field
var table = document.getElementById("Expenses");
var name = document.getElementById("Name").value;
var price = parseFloat(document.getElementById("Price").value);
if (price == "" && name == "") {
alert("Please enter in values.");
} else {
// Insert a default row from here:
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
col0.innerHTML = name;
col1.innerHTML = "$" + parseFloat(price);
document.getElementById("Name").value = "";
document.getElementById("Price").value = "";
console.log(typeof col1);
}
}
/* Function to add up last column */
function Calculate() {
var table = document.getElementById("Expenses");
var sumVal = 0;
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
for (var i = 1; i < table.rows.length; i++) {
sumVal += parseFloat(table.rows[i].cells[1]);
}
col0.innerHTML = "All Expenses";
col1.innerHTML = sumVal;
}
<div class="body">
<div class="container">
<div class="center">
<h3>Enter Expenses Below</h3>
<ul class="info">
<li>
<input type="text" placeholder="Name of Expense" id="Name">
</li>
<li>
<input type="number" min="0" placeholder="Price of Expense" id="Price">
</li>
</ul>
</div>
</div>
<table class="topmargin results-field" id="Expenses">
<tr>
<th>Name of Expense</th>
<th>Price of Expense</th>
</tr>
</table>
<div class="container1">
<div class="center1">
<button type="button" id="Add" onclick="Add()">Add</button>
<button type="button" id="Remove" onclick="Remove()">Remove</button>
<button type="button" id="Calculate" onclick="Calculate()">Calculate</button>
<button type="button" id="Print" onclick="window.print()">Print</button>
</div>
</div>
</div>
Any help is appreciated. Thank you.
Cell is a td element so we should get its innerHTML or innerText and remove '$' symbol from it. And for loop should be table.rows.length-1 because of last sum row. And it's clean now!
/* Function to calculate income */
function Add() {
// Variables from input field
var table = document.getElementById("Expenses");
var name = document.getElementById("Name").value;
var price = parseFloat(document.getElementById("Price").value);
if (price == "" && name == "") {
alert("Please enter in values.");
} else {
// Insert a default row from here:
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
col0.innerHTML = name;
col1.innerHTML = "$" + parseFloat(price);
document.getElementById("Name").value = "";
document.getElementById("Price").value = "";
console.log(typeof col1);
}
}
/* Function to add up last column */
function Calculate() {
var table = document.getElementById("Expenses");
var sumVal = 0;
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
for (var i = 1; i < table.rows.length-1; i++) {
sumVal += parseFloat(table.rows[i].cells[1].innerHTML.replace('$',''));
}
col0.innerHTML = "All Expenses";
col1.innerHTML = "$" + sumVal;
}
<div class="body">
<div class="container">
<div class="center">
<h3>Enter Expenses Below</h3>
<ul class="info">
<li>
<input type="text" placeholder="Name of Expense" id="Name">
</li>
<li>
<input type="number" min="0" placeholder="Price of Expense" id="Price">
</li>
</ul>
</div>
</div>
<table class="topmargin results-field" id="Expenses">
<tr>
<th>Name of Expense</th>
<th>Price of Expense</th>
</tr>
</table>
<div class="container1">
<div class="center1">
<button type="button" id="Add" onclick="Add()">Add</button>
<button type="button" id="Remove" onclick="Remove()">Remove</button>
<button type="button" id="Calculate" onclick="Calculate()">Calculate</button>
<button type="button" id="Print" onclick="window.print()">Print</button>
</div>
</div>
</div>

Javascript Comparing dropdown lists

I'm new to Javascript and I'm having trouble comparing elements from HTML. This is what I have for a function I cannot get the if statement to compare to the word Other which is one of my list items any ideas?
function createList(form) {
var row;
var table;
var form;
table = document.getElementById("shoppingList");
row = table.insertRow(table.rows.length);
form = form;
if (form.elements["storeItems"].value === "Other"){
row.insertCell(0).innerHTML = form.elements["otherItems"].value;}
else{
row.insertCell(0).innerHTML = form.elements["storeItems"].value;
}
row.insertCell(1).innerHTML = form.elements["funStores"].value;
row.insertCell(2).innerHTML = form.elements["selectColor"].value;
row.insertCell(3).innerHTML = form.elements["notes"].value;
}
My goal is if the list option Other is selected it pulls data from a text Other box instead of the word Other.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta Tags -->
<meta charset="utf-8">
<meta name="description" content="Benoit's living space">
<meta name="keywords" content="home, funiture, living, space, Benoit">
<meta name="author" content="Jesse Benoit">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jesse Benoit Homework Chapter 9</title>
<link rel="stylesheet" href="../css/Homework11.css"> <!-- Import of CSS -->
</head>
<body>
<h2 class="center">Furniture Shopping List</h2> <!-- Header 2 Centered -->
<div class="row">
<p class="center"> <!-- p cenetered with instructions -->
Time to go shopping! Pick an Item or Items from the list. Pick a Store from the list. Pick a color from the list. Added any extra notes you would like.
</p>
<div class="left">
<p>
<!-- Form to gather inputs from the user -->
<form>
<label>List of Items</label>
<select id="storeItems" size="4"></select> <br>
<label>Other: </label>
<input type="text" id="otherItems"> <br>
<label>Stores</label>
<select id="funStores" size="4"></select> <br>
<label>Other: </label>
<input type="text" id="otherStores"> <br>
<label>Chose a Color</label> <br>
<input type="radio" name="selectColor" value="White">White<br>
<input type="radio" name="selectColor" value="Black">Black<br>
<input type="radio" name="selectColor" value="Blue">Blue<br>
<input type="radio" name="selectColor" value="Red">Red<br>
<input type="radio" name="selectColor" value="OtherColor">Other<br>
<div id="selectColor"></div>
<label>Notes: </label><br>
<textarea rows="5" cols="20" id="notes"></textarea><br>
<input type="button" id="submit" value="Create Shopping List" onClick="createList(this.form);"> <!-- Button to create an invitation -->
<br><br>
</form>
</p>
</div>
<div class="right">
<table id="shoppingList">
<tr>
<th>Item </th><th>Store </th><th>Color of Item </th><th>Notes </th>
</tr>
</table>
</div>
</div>
<br>
<script src="../js/homework11.js"></script>
</body>
</html>
selectItem();
selectStore();
function selectItem() {
var myItems = "Couch; Table; Dresser; Chair; Bed; Other" ;
var itemArray = myItems.split(";");
var name = 0;
var myOption = "";
for (var i = 0; i < itemArray.length; i++) {
name = itemArray[i];
myOption = document.createElement("option");
myOption.name = name;
myOption.value = name;
myOption.text = name;
document.getElementById("storeItems").appendChild(myOption);
}
}
function selectStore(){
var myStore = "Walmart; Target; Wayfair; Other" ;
var storeArray = myStore.split(";");
var name = 0;
var myOption = "";
for (var i = 0; i < storeArray.length; i++) {
name = storeArray[i];
myOption = document.createElement("option");
myOption.name = name;
myOption.value = name;
myOption.text = name;
document.getElementById("funStores").appendChild(myOption);
}
}
function createList(form) {
var row;
var table;
var form;
table = document.getElementById("shoppingList");
row = table.insertRow(table.rows.length);
form = form;
if (form.elements["storeItems"].value === "Other"){
row.insertCell(0).innerHTML = form.elements["otherItems"].value;}
else{
row.insertCell(0).innerHTML = form.elements["storeItems"].value;
}
row.insertCell(1).innerHTML = form.elements["funStores"].value;
row.insertCell(2).innerHTML = form.elements["selectColor"].value;
row.insertCell(3).innerHTML = form.elements["notes"].value;
}
If you have a dropdown, you can get the selected value via:
let dropdownEl = document.getElementById('storeItems');
console.log(dropdownEl.value);
I'm slightly confused with what form is - but I'm assuming your dropdown has id="storeItems".
Also, I'm assuming you created the dropdown using the <select>...</select> tag.
Turns out having the dropdown list as a function was the issue and I needed list my options in the HTML

DOM event clearing text values

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Categories

Resources