HTML how to save input depending on selected dropdown value - html

HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="" method="post">
<label>Select Fridge or Freezer</label>
<select name="FridgeFreezer">
<option value="Fridge 1">Fridge 1</option>
<option value="Fridge 2">Fridge 2</option>
<option value="Fridge 3">Fridge 3</option>
</select>
<label>Temperature °C</label>
<input type="number">
<label>Comments</label>
<textarea name="comments"></textarea>
<button type="button" name="button">Save</button>
</form>
</body>
</html>
Goal:
How can I select a value from the dropdown menu, for example, I have selected Fridge 1 from the menu, I then type some value in the Temperature °C and Comments box. Next select another value from drop down box as an example Fridge 2 and start a fresh input, but if I go back to Fridge 1 the data previously inputted to be visible.
What do I need to look into in terms of research? I am not sure where to look or what keywords to search.

I've put together a quick example of what I mentioned in the comments, using a simple array of objects the maintain each options previous state.
When the select is changed, we:
Check to see if we have an object for the previous id
If we do, update that object, otherwise, create a new one with the new values
Update the current id (We store this externally as it's lost by the time the change is executed)
Check for any saved data for the newly loaded id and load that if it exists
var savedValues = []
var currentId = document.getElementById("fridgeFreezer").value
function handleChange() {
// The new values for the fridge with id currentId:
var temp = document.getElementById("temperature").value
var comments = document.getElementById("comments").value
// Save these values for the previous id
// - First, check to see if we already have a record we can update
var save = savedValues.find(save => {
return save.id === currentId
})
// - If we do, update it, otherwise create a new record
if (save) {
save.temp = temp
save.comments = comments
} else {
savedValues.push({
id: currentId,
temp: temp,
comments: comments,
})
}
// Update the current id to the newly selected option
currentId = document.getElementById("fridgeFreezer").value
// Load any previously saved data for this new id
save = savedValues.find(save => {
return save.id === currentId
})
// If we find a previous value, load it, otherwise empty the inputs
if (save) {
document.getElementById("temperature").value = save.temp
document.getElementById("comments").value = save.comments
} else {
document.getElementById("temperature").value = ''
document.getElementById("comments").value = ''
}
}
// Attach the event listener to the document
document.getElementById("fridgeFreezer").addEventListener('change', handleChange, false)
label {
display: block
}
<form action="" method="post">
<label>Select Fridge or Freezer</label>
<select name="FridgeFreezer" id="fridgeFreezer">
<option value="Fridge 1">Fridge 1</option>
<option value="Fridge 2">Fridge 2</option>
<option value="Fridge 3">Fridge 3</option>
</select>
<label>Temperature °C</label>
<input type="number" id="temperature">
<label>Comments</label>
<textarea name="comments" id="comments"></textarea>
<button type="button" name="button">Save</button>
</form>

I highly recommend using Vue.js for this. State management is very easy in it. The way I would do this is:
var app = new Vue({
el: '#app',
data: function(){
return {
devices: [{id: 0, name: 'fridge1', tempCelcius: 39, price: 20},
{id: 1, name: 'fridge1', tempCelcius: 39, price: 30},
{id: 2, name: 'fridge1', tempCelcius: 39, price: 40}],
selected = ''
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app">
<select v-model="selected">
<option disabled value="">Please select one</option>
<option v-for="device in devices" v-bind:key="device.id">{{ device.name }}</option>
</select>
<span>{{ selected }}</span>
</div>
</body>
</html>
This is a start, it doesn't quite work yet but here is where you'll find how to implement

Related

Jquery returned 'undefined'(s) when try to get the ID of the 'select' tag through class

I'm trying to check if my select box is empty or not by using class. However, based on the code below, the alert returned not only the id but also another 2 'undefined'. Anyone who can tell me why is this happening?
<script>
$('.test-input').each(function () {
var el = [];
if ($(this).val() === "") {
var target = $(this).attr('id');
alert(target); *// return media_type | underfined | underfined*
el.push(target);
}
})
</script>
<div class="form-group col-sm-4">
<label class="">Type:</label>
<select class="form-control required-input test-input" id="media_type" placeholder="Choose a media">
<option value="">Select a state</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="lizard">Lizard</option>
<option value="snake">snake</option>
</select>
</div>
$('.test-input').each(function () will iterate through each element in your HTML that has the "test-input" class name, so when there you are cycling through those and getting an undefined from pulling its id via var target = $(this).attr('id');, what this means is that somewhere else in the file you must have two other classes named "test-input" without an ID.
I would console.log("Iteration"); in the loop and check your console to see how many times the loop is being run and go from there.

How to write HTML code that read the input and produce a combination of string as an output?

Let's say I have two Dropdown Input Field. The first dropdown consists of 1 to 4 numbers. The second dropdown consists of A,B,C and D. When user select his/her choice from both dropdown and click 'SUBMIT', an output text will be shown. For example:
Dropdown 1:
1 -- Bad
2 -- Good
3 -- Great
4 -- Perfect
Dropdown 2:
A -- Boy
B -- Girl
C -- Man
D -- Woman
If User choose 2 and C respectively and click SUBMIT, an output text will be showing 'Good Man'.
How can I achieve this by using HTML code?
You'll have to use Javascript. Here's an example where clicking the submit button will fire an event that changes the text inside #answer.
I'm also splitting on -- to only include the last word in the selected choice.
document.getElementById('submit').addEventListener('click', (e) => {
const choiceOne = document.getElementById('selectOne').value.split('--')[1].trim();
const choiceTwo = document.getElementById('selectTwo').value.split('--')[1].trim();
document.getElementById('answer').textContent = choiceOne + ' ' + choiceTwo;
});
<select id="selectOne">
<option>1 -- Bad</option>
<option>2 -- Good</option>
<option>3 -- Great</option>
<option>4 -- Perfect</option>
</select>
<select id="selectTwo">
<option>A -- Boy</option>
<option>B -- Girl</option>
<option>C -- Man</option>
<option>D -- Woman</option>
</select>
<button id="submit">Submit</button>
<p id="answer"></p>
It is customary to include your code when you ask a question. It makes answering a little easier.
Assuming I have the HTML right, then something like this (taking from an answer here: Capture a form submit in JavaScript)
document.addEventListener("click",function() {
/* alert('ready'); */
document.getElementById('form1').addEventListener("submit",function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
var adj = document.getElementById('adj').value;
var noun= document.getElementById('noun').value;
// Should be triggered on form submit
document.getElementById("output").innerHTML = adj + " " + noun;
});
});
<form id="form1" method="get">
<select id="adj" name="adjective">
<option value="Good">Good</option>
<option value="Awesome">Awesome</option>
</select>
<select id="noun" name="noun">
<option value="Boy">Boy</option>
<option value="Girl">Girl</option>
</select>
<input type="submit">
</form>
<div id="output">
</div>
Here's my sample code, you can work on from this.
Codepen: https://codepen.io/DieByMacro/pen/WBdzbp?editors=1111
(function() {
const firstSelect = document.querySelector('#first-select');
const secondSelect = document.querySelector('#second-select');
const btnSubmit = document.querySelector('#submit');
function selectChangeHandler(event) {
console.log(event.target.value);
}
function clickHandler() {
const value1 = document.querySelector('#first-select').value;
const value2 = document.querySelector('#second-select').value;
const result = document.querySelector('#result')
result.innerText = `Selected ${value1} ${value2}`
}
firstSelect.addEventListener('change', selectChangeHandler )
secondSelect.addEventListener('change', selectChangeHandler )
btnSubmit.addEventListener('click', clickHandler )
})()
<select id="first-select">
<option value="Good">Good</option>
<option value="Bad">Bad</option>
</select>
<select id="second-select">
<option value="Boy">Boy</option>
<option value="Girl">Girl</option>
</select>
<button id="submit">Submit</button>
<div id="result"></div>

How to link option tags by name to a javascript if statement

I've been having some trouble coding one part of a webpage I am writing. The code looks something like this:
form name = dropDown
select
option name = "normalOne" /option
option name = "normalTwo" /option
/select
/form
Then:
if (document.dropDown.normalOne.selected == true) {
window.alert("drop down menu works");
}
Unfortunately, this does not work. What do I do?
Option elements don't have names (and the name attribute is not valid for them).
Deal with values instead.
document.querySelector("button").addEventListener("click", show);
function show(event) {
const select = document.querySelector("select");
const value = select.value;
console.log(value);
}
<select>
<option value="a"> One
<option value="b"> Two
<option value="c"> Three
</select>
<button>Log</button>
<!DOCTYPE html>
<html>
<body>
<select onChange="check(this.value)">
<option value="normalOne">normalOne</option>
<option value="normalTwo">normalTwo</option>
</select>
</body>
<script>
function check(value){
if (value === "normalOne") {
window.alert("drop down menu works");
}
}
</script>
</html>

Local Storage multiple fields with one field overwriting the second

I am creating a Chrome extension that restricts off-limits TV content. I have two roll-down menu forms that store values to Local Storage.
Javascript (external files):
ratings.js
window.onload=function (){
document.getElementById('saveRatings').onsubmit=saveRatings;
}
function saveRatings() {
var selectedRatings = document.forms["ratings_form"]["ratings"].value;
// store selectedRatings to local storage
localStorage.storedRatings = selectedRatings;
}
age.js
window.onload=function (){
document.getElementById('saveAge').onsubmit=saveAge;
}
function saveAge() {
var selectedAge = document.forms["age_form"]["age"].value;
// store selectedAge to local storage
localStorage.storedAge = selectedAge;
}
HTML
<summary>Select Content to Allow</summary><br>
<form name = "ratings_form" id="saveRatings">
<select name="ratings" multiple="multiple">
<option value="G">G only</option>
<option value="G/PG">G/PG only</option>
<option value="G/PG/PG13">G/PG/PG-13 only</option>
<option value="G/PG/PG13/R">G/PG/PG-13/R</option>
</select>
<div></div>
<input type="submit" value="Save"> </form>
<summary>Select Age Group to Deter</summary><br>
<form name = "age_form" id="saveAge">
<select name="age" multiple="multiple">
<option value="e">Everyone</option>
<option value="ct">Children & Teens;</option>
<option value="c">Children</option>
<option value="0">Turn off</option>
</select>
<div></div>
<input type="submit" value="Save">
</form>
The key-value pair for age_form stores correctly. However, ratings_form always gives me undefined. If I switch up the order (age first and ratings next), then the key-value pair for ratings_form would give me the correct value whereas age_value would give me undefined. It seems like the second form values are overwriting the first form values. How can I prevent this overwriting from occurring.
Thanks for your help.
Of course, your problem is that you're overwriting the window.onload function with whichever code runs last! All you need is a simple console.log(); in each function to see that the first one is not being called. You can remedy this with addEventListener() or by using jQuery's $(document).ready().
window.addEventListener('load', function() {
console.log('1');
});
window.addEventListener('load', function() {
console.log('2');
});
Just remember onload is a property of window and acts just like any variable/property would. Consider this:
var foo = 'bar';
foo = 'baz';
console.log(foo); // displays 'baz', of course! You changed the value!
That is just what you did with the onload function. You changed it to something else.

drop down list each option to take me to a different link

I am having a drop down list and I want when I select an option and then click go, to take me to an other link (each option takes me to different link)
This is my code but it doesnt seem to play.
<html>
<head>
<title>
Database Project Winter 2012
</title>
<script>
function goToNewPage(dropdownlist)
{
var url = dropdownlist.options(dropdownlist.selectedIndex).value;
if (url != "")
{
window.open(url);
}
}
</script>
</head>
<body>
<form name="dropdown">
<select name="list" accesskey="E">
<option selected>Select...</option>
<option value="http://www.google.com/">Google</option>
<option value="http://www.search.com/">Search.com</option>
<option value="http://www.dogpile.com/">Dogpile</option>
<select>
<input type=button value="Go" onclick="goToNewPage(document.dropdown.list)">
</form>
</body>
</html>
What to change?
Have you considered using a simpler javascript function?
function goToNewPage() {
if(document.getElementById('target').value){
window.location.href = document.getElementById('target').value;
}
}
And adding an ID to the Select element?
<select name="list" id="target">
You don't need to reference inside the select tag. The value of select tag itself contains the selected option
function goToNewPage(dropdownlist)
{
var url = dropdownlist.value;
if (url != "")
{
window.open(url);
}
}