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
Related
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.
I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>
So I have a project to create a webpage that accepts user input on one page and displays it in a table on another page. I know at least some of the local storage is working because I called the 'textvalue' and it always has the user input correct. I can't seem to figure out why I can't get the data to display on the table though.
This is the code that I have to the page that takes the user input and throws it into local storage.
#page
#model RSVPModel
#{
ViewData["Title"] = "RSVP";
}
<h1>#ViewData["Title"]</h1>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content=" width=device-width, initial-scale=1.0" />
<title>RSVP</title>
<link rel="stylesheet" type=" text/css" href="style.css" />
<script>
function getDetails() {
var name = document.getElementById("name").value;
localStorage.setItem("textvalue", name);
var age = document.getElementById("age").value;
localStorage.setItem("agevalue", age);
var arrtime = document.getElementById("arrtime").value;
localStorage.setItem("timevalue", arrtime);
var parking = document.getElementById("parking").value;
localStorage.setItem("parkingvalue", parking);
return false;
if (!name || !age || !arrtime || !parking) {
alert("Please fill all fields before proceeding");
return;
}
}
</script>
</head>
<body>
<div id=" container">
<div class=" input">Name: <input id="name" type="text" /></div>
<div class=" input">Age: <input id="age" type="number" /></div>
<div class=" input">Arrival Time: <input id="arrtime" type="time" /></div>
<label for="parking">Request Parking?</label>
<select name="parking" id="parking">
<option value=""></option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
<form action="Submitted">
<input type="submit" id="submit" value="Submit RSVP" onclick="getDetails();"/>
</form>
</div>
</body>
</html>
After the input page hitting the submit button will take them to a thank you page where they can navigate to the table page via a link on the page or the nav bar at the top of the page. Here is the code for that page.
#page
#model SubmittedModel
#{
ViewData["Title"] = "RSVP Submitted";
}
<body>
<div class="text-center">
<h1 class="display-4">Thank you <span id="result"></span>!</h1>
<p>It's great that you're coming. The drinks are already in the fridge!</p>
<p>Click here to see who is coming.</p>
</div>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
</body>
And this is the code I have for the page that tries to take that out of local storage, assign it to a variable, and then display it in the table.
#page
#model PrivacyModel
#{
ViewData["Title"] = "Here is a list of people attending the party";
}
<h1>#ViewData["Title"]</h1>
<body>
<script>
var row = 1;
var submit = document.getElementById('submit');
submit.addEventListener("click", displayDetails);
function displayDetails() {
document.getElementById("guestName").innerHTML = localStorage.getItem("textvalue");
document.getElementById("guestAge").innerHTML = localStorage.getItem("agevalue");
document.getElementById("arrivalTime").innerHTML = localStorage.getItem("timevalue");
document.getElementById("parkingRequest").innerHTML = localStorage.getItem("parkingvalue");
var display = document.getElementById("display");
var newRow = display.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = guestName;
cell2.innerHTML = guestAge;
cell3.innerHTML = arrivalTime;
cell4.innerHTML = parkingRequest;
row++;
}
</script>
<table id="display">
<tr>
<th>Name</th>
<th>Age</th>
<th>Arrival Time</th>
<th>Request Parking</th>
</tr>
</table>
</body>
I couldn't really find any information on a process like this, so I'm trying to piece together like 3 different tutorials. I might just need some fresh eyes to spot a simple mistake or I could be doing it completely wrong. Any help would be greatly appreciated.
I am not sure what happened on you code. If the following code is working, maybe you can modify it.
<body>
<div>
<span>Test</span><input type="text" id="input_test" size="14" value="new">
</div>
<div>
<button type="button" id="save">Save</button>
</div>
<div>
<button type="button" id="load">Load</button>
</div>
<table id="table_test">
<tr>
<th>test</th>
</tr>
</table>
</body>
<script>
let save = document.getElementById('save');
save.addEventListener("click", saveDetails);
function saveDetails() {
localStorage.setItem("Test", document.getElementById('input_test').value);
}
let load = document.getElementById('load');
load.addEventListener("click", loadDetails);
function loadDetails() {
let t = document.getElementById('table_test');
let r = t.insertRow(1);
let c = r.insertCell(0);
c.innerHTML = localStorage.getItem("Test");
}
</script>
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>
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);
}