Javascript, grading multiply options - javascript

I have read a lot of topics already but I still do not have a clue what I have to write to make my check() work.
When you choose an option, it will generate multiply questions ( 1 x 1 1 x 2 etc. ) then the user needs to fill in the right answer and when pressed on the submit button it needs to make the good answers green and the bad answers red.
I tried a lot of ways but this time I just can not see it haha. can anyone tell me or bring me in the right direction of what I need to write in my calc()
Thanks for helping :)
<div id="section">
<h2>De toets</h2>
<p>Welke toets wil je maken?</p>
<label for="toetsmenu"></label>
<select id="toetsmenu" onchange="toets()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="toetsding"></div>
<script>
function toets() {
var x = document.getElementById("toetsmenu").value;
document.getElementById("toetsding").innerHTML = "";
for (i = 1; i < 11; i++) {
document.getElementById("toetsding").innerHTML += x + " x " + i +
" = <input type='text' id='test'>" + "<br>";
}
document.getElementById("toetsding").innerHTML += "<input type='submit' value='check' id='sub' onclick='calc()'>"
}
function calc() {
}
</script>
</div>

When creating the <input> elements you need to give them each a unique ID: id='test" + i + "
In the calc() function you can then simply access them by their ID in the loop and check the result
function toets() {
var x = document.getElementById("toetsmenu").value;
document.getElementById("toetsding").innerHTML = "";
for (i = 1; i < 11; i++) {
document.getElementById("toetsding").innerHTML += x + " x " + i +
" = <input type='text' id='test" + i + "'>" + "<br>";
}
document.getElementById("toetsding").innerHTML += "<input type='submit' value='check' id='sub' onclick='calc()'>"
}
function calc() {
var x = document.getElementById("toetsmenu").value
for (i = 1; i < 11; i++) {
var input = document.getElementById("test" + i)
var result = input.value
console.log(input.value)
if (result == x * i) {
input.className = "correct"
} else {
input.className = "wrong"
}
}
}
toets()
.wrong {
background-color: red;
}
.correct {
background-color: green;
}
<div id="section">
<h2>De toets</h2>
<p>Welke toets wil je maken?</p>
<label for="toetsmenu"></label>
<select id="toetsmenu" onchange="toets()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="toetsding"></div>
</div>

Related

Concatenating multiple menu selections into string with all possible variations

I have found here an answer to a question about concatenating menu selection to string using javascript.
I wonder if is it possible to change the select elements to multiple to create all possible combinations from selected values?
<form>
<input form="form" type="hidden" name="product_data[product]" id="product_description_product" value="{$product_data.product}" />
<script type='text/javascript'>
$("#product_description_product_1, #product_description_product_2, #product_description_product_3").change(function(){
concatenated_string = $("#product_description_product_1").val() +
$("#product_description_product_2").val() +
$("#product_description_product_3").val();
$("#product_description_product").val(concatenated_string);
})
</script>
<select size="5" multiple="multiple" id="product_description_product_1">
<optgroup label="Box size">
<option value="Extra small">Extra small</option>
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
<option value="Extra Large">Extra Large</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="product_description_product_2">
<optgroup label="Speciality">
<option value="organic">organic</option>
<option value="seasonal">seasonal</option>
<option value="locally grown">locally grown</option>
<option value="exotic">exotic</option>
<option value="gourmet">gourmet</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="product_description_product_3">
<optgroup label="Type of box">
<option value="veg box">veg box</option>
<option value="fruit box">fruit box</option>
<option value="fruit & veg box">fruit & veg box</option>
</optgroup>
</select>
</form>
If I select for example:
from first select element: Small, Medium
from second select element: organic, gourmet
from third select element: fruit box
return me different strings with all possible combinations
Small organic fruit box
Medium organic fruit box
Small gourmet fruit box
Medium gourmet fruit box
Why don't you use array to save the values?
A simple way would create 3 arrays:
var itemsBoxSize;
var itemsSpeciality;
var itemsTypeBox;
So, when user select an item, adds it to the array. For example:
itemsBoxSize.push("Small");
Finally, you access all arrays:
for (i = 0; i <= itemsBoxSize.length; i++) {
var resultString = itemsBoxSize[i] + " " + itemsSpeciality[i] + itemsTypeBox[i];
}
Something like that!
I'm not sure if it's correct, but it's on the right way:
Note: it is still a little bit manual, but you can try to automate it.
HTML:
<div id="result"></div>
<form id="optionsForm">
<select size="5" multiple="multiple" id="boxSize">
<optgroup label="Box size">
<option value="Extra small">Extra small</option>
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
<option value="Extra Large">Extra Large</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="speciality">
<optgroup label="Speciality">
<option value="organic">organic</option>
<option value="seasonal">seasonal</option>
<option value="locally grown">locally grown</option>
<option value="exotic">exotic</option>
<option value="gourmet">gourmet</option>
</optgroup>
</select>
<select size="5" multiple="multiple" id="typeBox">
<optgroup label="Type of box">
<option value="veg box">veg box</option>
<option value="fruit box">fruit box</option>
<option value="fruit & veg box">fruit & veg box</option>
</optgroup>
</select>
</form>
JQUERY:
$(document).ready(function() {
// It also is used to clear the array
function initItems() {
items["boxSize"] = [];
items["speciality"] = [];
items["typeBox"] = [];
}
var items = [];
initItems();
// When user selects items
$("#optionsForm").change(function() {
initItems(); // Clear items
$("select :selected").each(function(i, selected) {
var selectId = $(this).closest("select").attr("id");
items[selectId].push($(selected).text());
});
showResult();
});
function showResult() {
var s = "";
var highestLenght = getHighestLenght();
var partialLength;
for (i = 0; i < highestLenght; i++) {
// BOX SIZE
partialLength = items["boxSize"].length;
if (partialLength >= highestLenght) {
s += items["boxSize"][i] + " ";
} else {
s += items["boxSize"][partialLength - 1] + " ";
}
// SPECIALITY
partialLength = items["speciality"].length;
if (partialLength >= highestLenght) {
s += items["speciality"][i] + " ";
} else {
s += items["speciality"][partialLength - 1] + " ";
}
// TYPE BOX
partialLength = items["typeBox"].length;
if (partialLength >= highestLenght) {
s += items["typeBox"][i] + " ";
} else {
s += items["typeBox"][partialLength - 1] + " ";
}
s += "<br>";
}
$('#result').html(s);
}
// What is the highest amount of elements?
function getHighestLenght() {
var highestValues = [];
highestValues.push(items["boxSize"].length);
highestValues.push(items["speciality"].length);
highestValues.push(items["typeBox"].length);
var highest = Math.max.apply(null, highestValues);
return highest;
}
})

Adding input type dynamically

Trying to dynamically add input type text boxes by selecting how many need to be created within the .answer-box using a select tag with options. What am I missing here?
And please refrain from telling me to use .on instead of bind. Thank you!
Here is jsfiddle: https://jsfiddle.net/otjuhp59/
Code:
$(document).ready(function(){
$("#create-skill").unbind("click");
$("#create-language").unbind("click");
$("#create-skill").bind("click", addSkill);
$("#create-language").bind("click",addLanguage);
var language=$("#lang").val();
var skill=$("#skill").val();
addSkill(skill);
addLanguage(language);
});
function addSkill(s){
$(".answer-box").html("");
for(var i=1; i<=s; i++)
{
var skillContent="Skill "+i+"<br /><input type='text' id='txt1"+i+"' name='txt1"+i+"' value='' placeholder='Please enter Skill' /><br />";
$(".answer-box").append(skillContent);
}
}
function addLanguage(l){
$(".answer-box").html("");
for (var j=1; j<=l; j++)
{
var langContent="Language "+j+"<br /><input type='text' id='txt2"+j+"' name='txt2"+j+"' value='' placeholder='Please enter laanguage' /><br />";
$(".answer-box").append(langContent);
}
}
HTML:
<div class="select-container">
<div class="user-input-box">
<p>Select number of Skills:</p>
<select class="skill" id="skill">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
</select>
<input type="button" id="create-skill" name="create-skill" value="Create Skill" />
<p>Select number of Languages:</p>
<select class="lang" id="lang">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
</select>
<input type="button" id="create-language" name="create-language" value="Create Language" />
</div>
</div>
<div class="answer-box">
</div>
</div>
CSS:
.select-container{border:1px solid black; min-width:200px; min-height:100px; float:left;}
.user-input-box{width:180px; min-height:100px; float:left; margin-left:5px;}
.answer-box{border:1px solid black; min-width:400px; min-height:100px; float:left; margin-left:100px;}
There are few modifications needed
Hope this snippet and comments will be useful
JS
$(document).ready(function(){
// remove all the bind & unbind
// create input on click of button create-skill
$("#create-skill").on('click',function(){
// get the value of selected option
var s = $("#skill").val();
$(".answer-box").html("");
for(var i=1; i<=s; i++)
{
var skillContent="Skill "+i+"<br /><input type='text' id='txt1"+i+"' name='txt1"+i+"' value='' placeholder='Please enter Skill' /><br />";
$(".answer-box").append(skillContent);
}
})
//rest of the code
})
HTML
put separate value in each option
<select class="skill" id="skill">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
DEMO
The value of your skills and language dropdown does not get passed through when you change the dropdown and click the button.
Two problems you have is that:
you don't actually tell the function to get the new value
The dropdown options all have the same value set to "1", you've only
just updated the text label.
https://jsfiddle.net/43cxmx3k/16/
JS:
function addSkill(s) {
var s = $("#skill").val();
$(".answer-box").html("");
for (var i = 1; i <= s; i++) {
var skillContent = "Skill " + i + "<br /><input type='text' id='txt1" + i + "' name='txt1" + i + "' value='' placeholder='Please enter Skill' /><br />";
$(".answer-box").append(skillContent);
}
}
function addLanguage() {
var l = $("#lang").val();
$(".answer-box").html("");
for (var j = 1; j <= l; j++) {
var langContent = "Language " + j + "<br /><input type='text' id='txt2" + j + "' name='txt2" + j + "' value='' placeholder='Please enter laanguage' /><br />";
$(".answer-box").append(langContent);
}
}
HTML:
<select class="skill" id="skill">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select class="lang" id="lang">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

Can I pass multiple values in the <option> tag?

I have a program that simulates a folding effect on a flyer that has a front image and a back image. I select the flyers through a dropDownList. How can I pass the back image in the tag so that, when I rotate the image, the picture on the back is shown?
This is the HTML for my dropDownList:
<form name="Pictures">
<select name="dropPic" onchange="selectFront(this.value)">
<option value="Flyer1pag1.png" value="Flyer1pag2.png">Flyer 1</option>
<option value="Flyer2pag1.png" value="Flyer1pag2.png">Flyer 2</option>
<option value="Flyer3pag1.png" value="Flyer1pag2.png">Flyer 3</option>
</select>
</form>
Here is the function in JavaScript that changes the front image regarding the selection of the dropDownList and the function that should take the back image of the flyer:
function selectFront(imgSrc) {
loadImage(imgSrc);
var Dim_Slice = document.querySelectorAll(".slice");
for (var i = 0; i < Dim_Slice.length; i++) {
Dim_Slice[i].style.backgroundImage = "url(" + imgSrc + ")";
}
}
function selectBack(imgSrc) {
var Dim_Sliceb = document.querySelectorAll(".sliceb");
for (var i = 0; i < Dim_Sliceb.length; i++) {
Dim_Sliceb[i].style.backgroundImage = "url(" + imgSrc + ")";
}
}
it can be done in this way
<select id="dropPic">
<option data-picone="Flyer1pag1.png" data-pictwo="Flyer1pag2.png">Flyer 1</option>
<option data-picone="Flyer2pag1.png" data-pictwo="Flyer1pag2.png">Flyer 2</option>
<option data-picone="Flyer3pag1.png" data-pictwo="Flyer1pag2.png">Flyer 3</option>
</select>
And on change event you can get the value as below
$("#dropPic").change(function () {
alert($(this).find(':selected').data('picone'));
});
Check this link for similar question
Can an Option in a Select tag carry multiple values?
Your question and / or what you're trying to do isn't entirely clear, but I think this is what you want:
<form name="Pictures">
<select name="dropPic"
onchange="selectFront(this.value.split(',')[0]);selectBack(this.value.split(',')[1]);">
<option value="Flyer1pag1.png,Flyer1pag2.png">Flyer 1</option>
<option value="Flyer2pag1.png,Flyer1pag2.png">Flyer 2</option>
<option value="Flyer3pag1.png,Flyer1pag2.png">Flyer 3</option>
</select>
</form>
You cannot have Multiple values in an Option Tag.
If the Name of the Front and Back-Image only differ by the Page-number, you can use this code:
function selectFlyer(name){
selectFront(name+"pag1.png");
selectBack(name+"pag2.png");
}
function selectFront(imgSrc) {
loadImage(imgSrc);
var Dim_Slice = document.querySelectorAll(".slice");
for (var i = 0; i < Dim_Slice.length; i++) {
Dim_Slice[i].style.backgroundImage = "url(" + imgSrc + ")";
}
}
function selectBack(imgSrc) {
loadImage(imgSrc);
var Dim_Sliceb = document.querySelectorAll(".sliceb");
for (var i = 0; i < Dim_Sliceb.length; i++) {
Dim_Sliceb[i].style.backgroundImage = "url(" + imgSrc + ")";
}
}
<form name="Pictures">
<select name="dropPic" onchange="selectFlyer(this.value)">
<option value="Flyer1">Flyer 1</option>
<option value="Flyer2">Flyer 2</option>
<option value="Flyer3">Flyer 3</option>
</select>
</form>
You can feed it a series of values, separated by commas:
<select id="BLAH" onchange="readBlah()">
<option value="1,car,red">1</option>
<option value="2,car,red">2</option>
<option value="3,truck,blue">3</option>
</select>
function readBlah() {
var e = document.getElementById("BLAH");
feedArray=e.value.split(",");
console.log(feedArray[0]);
console.log(feedArray[1]);
console.log(feedArray[2]);
}
<form method="post">
<select class='form-control' name= 'dropPic'>
<option value="Flyer1pag1.png,Flyer1pag2.png">Flyer 1</option>
<option value="Flyer2pag1.png,Flyer1pag2.png">Flyer 2</option>
<option value="Flyer3pag1.png,Flyer1pag2.png">Flyer 3</option>
</select>
</form>
<?php
$dropPic=$_POST['dropPic'];
$result=explode(',', $dropPic);
$dropPic1=$result[0];
$dropPic2=$result[1];
?>

Display all selected value of multiple drop down list

Below is what I have...
<html>
<body>
<form name="myForm">
<select name="myOption" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type=submit value="Print First" onClick="printMe()">
<input type=submit value="Print All" onClick="printAll()">
</body>
<script>
function printMe() {
alert ("Selected option is " + myForm.myOption.value);
}
function printAll() {
var str = "";
// what should I write here??
alert("Options selected are " + str);
}
</script>
</html>
Please let me know what should I write in printAll() so that I can print all the values that I selected... I know how can I print the first selected value...
how about this??
function printAll() {
var str="",i;
for (i=0;i<myForm.myOption.options.length;i++) {
if (myForm.myOption.options[i].selected) {
str = str + i + " ";
}
}
alert("Options selected are " + str);
}
Good Luck!!!
You can do something like this:
function printAll() {
var obj = myForm.myOption,
options = obj.options,
selected = [], i, str;
for (i = 0; i < options.length; i++) {
options[i].selected && selected.push(obj[i].value);
}
str = selected.join();
// what should I write here??
alert("Options selected are " + str);
}
Demo: http://jsfiddle.net/n3cXj/1/
I would use jquery as it's easier
JQuery:
$("myOption:selected").each(function () {
alert($(this).text());
});
http://jsfiddle.net/XBDmU/2/
var selected = [];
$("#Mymutiple option").each(function(){
$(this).click(function(evt){
myvar = $(this).val();
if (evt.ctrlKey){
if(jQuery.inArray(myvar, selected) >-1){
selected = jQuery.grep(selected , function(value) {
return value != myvar;
});
}
else{
selected.push(myvar);
}
}
else{
selected = [];
selected.push(myvar);
}
});
})
$("#printMe").click(function(){
alert("First selected is:" + selected[0]);
return false;
});
$("#printAll").click(function(){
alert("Options selected are :" + selected);
return false;
});
html:
<form name="myForm">
<select name="myOption" id="Mymutiple" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type="submit" value="Print First" id="printMe">
<input type="submit" value="Print All" id="printAll">
This will help you. It's in pure js. no jquery, mootools...
<!DOCTYPE html>
<html>
<body>
<script>
function get(){
var str="",i;
for (i=0;i<asa.cars.options.length;i++) {
if (asa.cars.options[i].selected) {
str += asa.cars.options[i].value + ",";
}
}
if (str.charAt(str.length - 1) == ',') {
str = str.substr(0, str.length - 1);
}
alert("Options selected are " + str);
}
</script>
<form name="asa">
<select name="cars" id="combo" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" onclick="get()">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
</body>
</html>
In angular 4, instead of using angular multi-select dropdown I used the normal one.
Following is the code.
HTML file:
<select [ngModel]="DataValue" (change)="selectChangeHandler($event)"
id="multiple-select" name="multiple-select" class ="form-control" multiple>
<option *ngFor="let ref of Data" [value]="ref['title']">
{{ref['title']}}
</option>
</select>
Ts file:
selectChangeHandler (event: any) {
let oldvalue;
let mergedValue = "";
for ( let index = 0 ; index < event.currentTarget.selectedOptions.length; index++)
{
oldvalue = event.currentTarget.selectedOptions[index].value.replace(/["']/g, "");
oldvalue = oldvalue.split(': ')[1];
if (index ==`enter code here`= 0)
{ mergedValue += oldvalue; }
else
{ mergedValue += ", " + oldvalue; }
}
console.log(mergedValue);
}
Comments:
Using event.currentTarget.selectedOptions[index].value you can get multiple selected values of multi-select dropdown. In my case, mergedValue gives me proper multiple selected values.
I have used split and replace to format the string obtained as I wanted it common separated.
I hope this can help someone.

Add form values without exceeding a total value in javascript

Excually Im not a programmer, but Im trying to learn how to make a questionnaire with html and javascript:
I have four selection boxes in a form. Each one of the selection boxes has the values through 0 to 10. The main rule of this questionnaire is to change the value of all four selection boxes so that it adds up to 10.
I figured out the following solution:
instant updated text box where it calculates the total value selected (with onChange);
validate at submit button if a total value of 10 (and not more or less) is selected.
Alternatively I would even assign a (error) message instantly when the user selects a value that exceeds the total value of 10.
I have some half baked javascripts, but I don't have enough understanding of the subject to excually connect the dots. Hope you can help me.
Tim
My framework:
<html>
<head>
<script type="text/javascript">
function editTotalValue(){
}
function validateTotalValue(){
}
</script>
</head>
<body>
<form name="form1">
<select name="question1" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select name="question2" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select name="question3" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select name="question4" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!-- Show total value selected in text box -->
<input name="totalValue" type="text" maxlength="2" readonly="true">
<!-- Validate that totalValue(); is indeed 10 and not more or less and pass on the data -->
<input name="submit" type="button" onClick="validateTotalValue();">
</form>
</body>
</html>
Here's something more in-depth that you can play with:
document.getElementById("form1").onsubmit = checkTarget;
function checkTarget(evt)
{
var el;
if(window.event)
{
//checking for IE equivalent
el = window.event.srcElement;
}else if(evt.target)
{
el = evt.target;
}
if(window.event)
{
//checking for IE equivalent
window.event.returnValue = false;
}else if(evt.preventDefault)
{
evt.preventDefault();
}
calculateValues(el);
}
function calculateValues(form)
{
var values = [];
var value = 0;
for(var i=0;i<form.elements.length;i++)
{
var el = form.elements[i];
if(el.tagName === "SELECT")
{
values.push(el.value);
}
}
for(var j=0;j<values.length;j++)
{
value = value + parseInt(values[j], 10);
}
updateValue(value);
checkValue(values, value);
}
function updateValue(value)
{
document.getElementById("result_box").value = value;
}
function checkValue(values, value)
{
var temp = [];
for(var i=0;i<values.length;i++)
{
if(values[i] > 0 && values[i] < 10)
{
temp.push(values[i]);
}
}
if(value === 10 && temp.length === 4)
{
document.getElementById("message_box").value = "You win!";
}else if(value > 10 && temp.length === 4)
{
document.getElementById("message_box").value = "Value is more than 10";
}
}
http://jsfiddle.net/YS6mm/9/
Tested as working in: Firefox 4, IE8, IE8 Compatibility View (Quirks), IE7 Quirks Mode, Chrome 4, Safari 4, and Opera 11.
function editTotalValue() {
var val = 0;
for (var i = 1; i < 5; i++) {
val = val + document.getElementById("question" + i).value;
}
var display = document.getElementbyId("totalValue");
if (val > 10) {
alert("error");
} else {
display.value = val;
}
}

Categories

Resources