js html select dropdown value depends on input value - javascript

I wanna create select drop down list where selected value will be depends on input value. Example:
If i write 0 in <input type='text' name='answer' id="ans" oninput="myFunction();"> than will be selected dynamically value NO.
<select id="abcd">
<option value="1">OK</option>
<option value="0">NO</option>
</select>
My attempts
function myFunction() {
var x = document.getElementById('ocena7');
if (x == 0)
{
document.getElementById("abcd").selectedIndex = 2;
}}
Greetings

The problem is that with var x = document.getElementById('ans'); you get the DOM element not the value of it.
You need to replace that with: var x = document.getElementById('ans').value;

Just look at this answer: https://stackoverflow.com/a/1085810/826211
And for your code:
You want to use
var x = document.getElementById('ocena7').value;
if you want the value of the element. Now you're just getting a reference to the element with
var x = document.getElementById('ocena7');

This may help
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById('ans').value;
if (x == 0)
{
document.getElementById("abcd").options[1].selected = 'selected'
}
}
</script>
</head>
<body>
<select id="abcd">
<option value="1" >OK</option>
<option value="0" >NO</option>
</select>
<input type='text' name='answer' id="ans" oninput="myFunction();">
</body>
</html>

Related

How to set cookie to value of checkbox

I am trying to make a function that sets a cookie to a true/false value depending on if a checkbox has been clicked or not. I can then use this value when the page loads to render the checkbox as toggled.
HTML:
<form name="example">
<div class="checklist-item">
<label for="example">Example</label>
<input type="checkbox" id="example" name="example">
</div>
</form>
JS:
document.getElementById("example").addEventListener("click", exampleCookie)
function exampleCookie() {
document.cookie = "exampleCookie";
}
How might I use the function exampleCookie to be equal to the value of the checkbox?
sorry, i give you a referrence from here https://www.javatpoint.com/javascript-cookies
maybe it helps
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="color" onchange="display()">
<option value="Select Color">Select Color</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<script type="text/javascript">
function display()
{
var value = document.getElementById("color").value;
if (value != "Select Color")
{
document.bgColor = value;
document.cookie = "color=" + value;
}
}
window.onload = function ()
{
if (document.cookie.length != 0)
{
var array = document.cookie.split("=");
document.getElementById("color").value = array[1];
document.bgColor = array[1];
}
}
</script>
</body>
</html>

Comparing answer key array with input answers

This is my first day using HTML/Javascript. I've done some Java a while ago. I'm trying to make a quiz that will get answers from a drop down list and compare them to the answer key. I've tried so many things I can't even remember them all. Any help would be appreciated. Specifically, I cant figure out how to compare each element in the two arrays. I'm sure there is a lot more wrong than just the arrays. I;ve googled answers for 4 hours and got nothinggggg. Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.<p>
<br>
<br>
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width = 300 height = 200>
<br>
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br>
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br>
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br>
<br>
<button onclick="myFunc()">Click me</button>
<script>
var q1 = document.getElementById("Q1");
var valueQ1=q1.options[q1.selectedIndex].value
var q2 = document.getElementById("Q2");
var valueQ2=q2.options[q2.selectedIndex].value
var q3 = document.getElementById("Q3");
var valueQ3=q3.options[q3.selectedIndex].value
var array ans = [1,2,3]
var array inpans = [valueQ1,valueQ2,valueQ3]
var counter = 0;
var count = 0;
function myFunc(){
while (count<ans.length){
if(ans[count]==inpans[count])
{
counter ++;
count ++;
}else {
counter = counter;
count ++,
}
}
document.getElementById("one").innerHTML = "You got " + counter + " right.";
}
</script>
<p id="one"></p>
</body>
</html>
You have a number of issues which need fixing:
Your HTML is invalid. Your're not closing your <p> tag on line 11:
<p>Please match the letter to the corresponding answer.</p> <!-- <-- close this -->
You have many syntax errors in your code. Whenever your code isn't working, the first thing you should look for is syntax errors. Syntax errors can be identified by your brower's console. The first syntax errors are on lines 58 and 59. There should only be one variable name (identifier) after the var keyword:
var ans = [1, 2, 3]; // <-- used to be: var array ans
var inpans = [valueQ1, valueQ2, valueQ3]; // used to be: array inpans
Another syntax error occurs on line 70. Here you're using a comma instead of a semi-colon. Again, the console could of helped you identify this error yourself:
count++; // used to be: count++,
Your next issue is a logical issue. The following code runs when the page loads:
var q1 = document.getElementById("Q1");
var valueQ1 = q1.options[q1.selectedIndex].value
var q2 = document.getElementById("Q2");
var valueQ2 = q2.options[q2.selectedIndex].value
var q3 = document.getElementById("Q3");
var valueQ3 = q3.options[q3.selectedIndex].value
...as it runs when the page initially loads, the values of valueQ1 etc. will all be the initial value of the dropdowns when the page initially loads. These values don't change when you change the selected value in the dropdowns. If you wanted that behaviour you'd need an event listener. However, an easy way to fix this is to set the values of valueQ1 through to valueQ3 inside your function. This way, your code will grab the values from the dropdowns when you click your button, which should be after the user has manually selected a value from the dropdowns themselves:
var q1 = document.getElementById("Q1");
var q2 = document.getElementById("Q2");
var q3 = document.getElementById("Q3");
...
function myFunc() {
// get value of dropdown elements
var valueQ1 = q1.value; // you can just grab the dropdown's value, no need for `q1.options[q1.selectedIndex].value`
var valueQ2 = q2.value;
var valueQ3 = q3.value;
var inpans = [valueQ1, valueQ2, valueQ3];
while (count < ans.length) {
...
Fixing all these will allow your code to check against answers. Currently, as your count variable is defined outside of the myFunc, your button will only run your while loop once (as the second time it runs count >= ans.length, making your while loop condition false - thus not running the code within it). If you want users to have multiple attempts at a given question you define count inside your function so that it gets reset when the button is clicked.
As a side note, if you're planning on using this code in production keep in mind that users will be able to see the answers to the questions by inspecting your website's source.
See altered code below:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.</p>
<br>
<br>
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width=300 height=200>
<br>
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br>
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br>
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br>
<br>
<button onclick="myFunc()">Click me</button>
<script>
// Get dropdown elements when page loads
var q1 = document.getElementById("Q1");
var q2 = document.getElementById("Q2");
var q3 = document.getElementById("Q3");
var ans = [1, 2, 3]
var counter = 0;
var count = 0;
function myFunc() {
// get value of dropdown elements
var valueQ1 = q1.value;
var valueQ2 = q2.value;
var valueQ3 = q3.value;
var inpans = [valueQ1, valueQ2, valueQ3];
while (count < ans.length) {
if (ans[count] == inpans[count]) {
counter++;
count++;
} else {
counter = counter;
count++;
}
}
document.getElementById("one").innerHTML = "You got " + counter + " right.";
}
</script>
<p id="one"></p>
</body>
</html>
For what it's worth, here's how I would write the equivalent code. It takes advantage of the class you have on each dropdown, and then iterating over all dropdowns to check whether they equal the correct answer. If you want the user to have multiple attempts at the question you can remove the {once: true} option:
// Get dropdown elements when page loads
const dropdowns = document.querySelectorAll('.Q');
const submitBtn = document.querySelector("#guess-btn");
const resultElem = document.getElementById("one");
const ans = [1, 2, 3];
submitBtn.addEventListener("click", () => {
const correctCount = [...dropdowns].reduce(
(total, dropdown, i) => total + (+dropdown.value === ans[i]), 0
);
resultElem.innerText = `You got ${correctCount} right.`;
}, {once: true});
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.</p>
<br />
<br />
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width="300" height="200" />
<br />
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br />
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br />
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br />
<br />
<button id="guess-btn">Click me</button>
<p id="one"></p>

Local Storage With JavaScript

I want to store a string locally so when the user reloads the page it saves what was last there.
I looked at this and tried to implement it.
I had this code which basicllay has a button and a dropdown list of colors to change the background.
When I close and reopen the doc I want it to be the color that I saved.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<form>
<script language="JavaScript">
<!--
function inputForm(){
var color = document.getElementById("color");
var outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
//-->
</script>
</body>
</html>
I made this code to do that but it didn't work
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="storeColor()">
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<input type="button" onClick="storeColor()" value="save color"/>
<script>
var outputContents;
function inputForm(){
var color = document.getElementById("color");
outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
function storeColor(){
// Store
localStorage.color = outputContents;
// Retrieve
document.body.style.backgroundColor = outputContents;
}
</script>
<form>
</body>
</html>
Local storage in JavaScript is uses (key, value) pairs of strings so if you wanted to save the value This is my test value. you would need to give it a key that you can get it from later, for example myTestValue.
So in code this would be
// set the value in window.localStorage
window.localStorage.setItem('myTestValue', 'This is my test value.')
// get the value from window.localStorage
window.localStorage.getItem('myTestValue')
Here is some more information: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
You code is almost complete. You only need to apply background color on window load. I added one more function applyColor:
function applyColor(color) {
color = color || localStorage.color;
document.body.style.backgroundColor = color;
// Select corresponding option in selectbox
var select = document.getElementById("color");
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value == color) {
select.options[i].selected = true;
return;
}
}
}
applyColor();
Also note that when page is loaded we should also select the option from selectbox corresponding to currently saved color.
Demo: http://jsfiddle.net/sd2Cx/

Store contents of drop down box into var, then load the new drop down box contents using the var

1.) How can I use javascript to save the contents of box1 and store it into a variable (x), separating them all by commas?
Since I will be doing some database work in the background, it is important that the values are stored using this method.
Example of whats in the drop down box:
[BOX1]
volvo
saab
mercedes
audi
Resulting var:
var x = volvo,saab,mercedes,audi
2.) Using the variable (x) how can I repopulate the drop down [BOX2] with the comma separated values.
[BOX2]
volvo
saab
mercedes
audi
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="box1" style="width: 100px;">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<input type="button" value="Save" name="Save">
<br><br>
<input type="button" value="Populate" name="Populate"><br>
<select id="box2" style="width: 100px;" name="D1"></select>
<br>
</body>
</html>
You could retrieve the options and simply put them into the other selectbox, by adding an event handler.
Working Example
//temp holds DOM elements
//temp2 holds only the values
var temp = [];
var temp2 = [];
function save() {
var cH = document.getElementById('box1').children;
for (var i in cH) {
if(cH.hasOwnProperty(i) && cH[i].nodeName == 'OPTION') {
temp.push(cH[i]);
temp2.push(cH[i].value);
}
}
alert(arr2csv());
}
function populate() {
var popul = csv2arr();
var box2 = document.getElementById('box2');
/*
for(var i=0;i<temp.length; i++) {
box2.options.add(new Option(temp[i].text,temp[i].value));
}
*/
for(var i=0;i<popul.length; i++) {
box2.options.add(new Option(popul[i],popul[i]));
}
}
function arr2csv() {
return temp2.join();
}
function csv2arr() {
return arr2csv().split(',');
}
document.getElementById('testsave').addEventListener("click", save);
document.getElementById('testpopulate').addEventListener("click", populate);

Javascript Get Values from Multiple Select Option Box

This one is driving me nuts. It’s got to be something simple and stupid that I am overlooking.
I have a multiple select box in a form. I am just trying to get the values that are selected. In my loop, if I use alert then I have no problem. As soon as try to concatenate the values I get the error ‘SelBranch[...].selected' is null or not an object
<form name="InventoryList" method="post" action="InventoryList.asp">
<select name="SelBranch" class="bnotes" size="5" multiple="multiple">
<option value="All">All</option>
<option value="001 Renton">001 Renton</option>
<option value="002 Spokane">002 Spokane</option>
<option value="003 Missoula">003 Missoula</option>
<option value="004 Chehalis">004 Chehalis</option>
<option value="005 Portland">005 Portland</option>
<option value="006 Anchorage">006 Anchorage</option>
<option value="018 PDC">018 PDC</option>
</select>
<input type="button" name="ViewReport" value="View" class="bnotes" onclick="GetInventory();">
</form>
<script language="JavaScript">
function GetInventory()
{
var InvForm = document.forms.InventoryList;
var SelBranchVal = "";
var x = 0;
for (x=0;x<=InvForm.SelBranch.length;x++)
{
if (InvForm.SelBranch[x].selected)
{
//alert(InvForm.SelBranch[x].value);
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
}
}
alert(SelBranchVal);
}
</script>
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
Take a look at HTMLSelectElement.selectedOptions.
HTML
<select name="north-america" multiple>
<option valud="ca" selected>Canada</a>
<option value="mx" selected>Mexico</a>
<option value="us">USA</a>
</select>
JavaScript
var elem = document.querySelector("select");
console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]
This would also work on non-multiple <select> elements
Warning: Support for this selectedOptions seems pretty unknown at this point
Also, change this:
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
to
SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
The reason is that for the first time the variable SelBranchVal will be empty

Categories

Resources