Javascript passing variable and elementId to an function - javascript

var ingaveA = {
stuks: ""
};
var ingaveB = {
prijs: ""
};
var uitgave = {
totaal: ""
};
update(ingaveA, "testa", ingaveB, "testb", uitgave, "testc");
function update(refA, argsA, refB, argsB, refC, argsC) {
refA.stuks = document.getElementById(argsA).value;
refB.prijs = document.getElementById(argsB).value;
refC.totaal = refA.stuks * refB.prijs;
document.getElementById(argsC).value = refC.totaal;
}
ingaveA = ingaveA.stuks;
ingaveB = ingaveB.prijs;
uitgave = uitgave.totaal;
alert("Stuks=" + ingaveA + " Prijs=" + ingaveB + " Totaal=" + uitgave);
<input id="testa" value="10">
<input id="testb" value="6">
<input id="testc" value="">
Is there an better way to do this? always 3 variable names and 3 elements.
Maybe using an array ?
thanks in advance

Instead of using document.getElementById() for every input, you can use document.querySelectorAll() and [id^=test] to select all 3 and put them in a NodeList (think of it as an array).
[id^=test] means every id that starts with test
You can also make one general object, and update it as needed like below.
var ingave = {
ingaveA: {
stuks: ""
},
ingaveB: {
prijs: ""
},
uitgave: {
totaal: ""
}
};
var inputs = document.querySelectorAll("[id^=test]");
update(ingave, inputs);
function update(ref, inputs) {
ref.ingaveA.stuks = inputs[0].value;
ref.ingaveB.prijs = inputs[1].value;
ref.uitgave.totaal = ref.ingaveA.stuks * ref.ingaveB.prijs;
inputs[2].value = ref.uitgave.totaal;
}
var ingaveA = ingave.ingaveA.stuks;
var ingaveB = ingave.ingaveB.prijs;
var uitgave = ingave.uitgave.totaal;
alert("Stuks=" + ingaveA + " Prijs=" + ingaveB + " Totaal=" + uitgave);
<input id="testa" value="10">
<input id="testb" value="6">
<input id="testc" value="">

I'm not really sure what the question is here, but you don't need to create 3 separate objects.
let ingaveA = ""
let ingaveB = ""
let uitgave = ""
then just pass these 3 to your function:
function update(refA, refB, refC) {
refA = document.getElementById("testa").value;
refB = document.getElementById("testb").value;
refC = refA * refB;
document.getElementById("testc").value = refC.totaal;
}
Again, it's hard to optimize it as we don't know your specifics of the code.

Related

Why do I get same result from two difference?

<h2>Volume</h2>
<b>Choose Convert : </b><br><br>
<input type=radio name=volConvert id="LitToGal" value="LitToGal" checked>Litre To Gallon<br>
<input type=radio name=volConvert id="GalToLit" value="GalToLit">Gallon To Litre
<br><br>
<label>
<b>Input a data: </b><br>
<input name="volData" id="inVolData" type="text" size="10">
</label><br><br>
<p>
<input type=button value="Convert" onClick="VolConvert()" />
</P>
<h4 id="result"></h4>
</div>
var value = parseFloat(0);
var conValue = parseFloat(0);
function VolConvert() {
if (document.getElementById("LitToGal")) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 16.52);
} else if (document.getElementById("GalToLit")) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 113.50);
}
var conValue = value.toFixed(2);;
resultmessage = ("The converted value: " + conValue);
document.getElementById("result").innerHTML = resultmessage;
}
You need to compare the "checked" value
function VolConvert() {
if (document.getElementById("LitToGal").checked) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 16.52);
} else if (document.getElementById("GalToLit").checked) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 113.50);
}
var conValue = value.toFixed(2);;
resultmessage = ("The converted value: " + conValue);
document.getElementById("result").innerHTML = resultmessage;
}
In your code you have the following If-Statement:
if (document.getElementById("LitToGal")) {
...
else if (document.getElementById("GalToLit")) {
...
}
This document.getElementById("LitToGal") will always be true since the element exists in your HTML .
Meaning value = (inputData * 16.52); will always be the result.
To fix the statement, try the following:
if (document.getElementById("LitToGal").checked) {
...
else if (document.getElementById("GalToLit").checked) {
...
}
if(document.getElementById("LitToGal").checked)
if (document.getElementById("GalToLit").checked)

mergeMap() RXJS 3 observables

I watched a tutorial on how to use mergeMap() on 2 observables but I'm still very unclear on how to use it with more than 2 observables.
Here is the link to the tutorial:
https://www.youtube.com/watch?v=b59tcUwfpWU&t=1s
Here is the code for 3 observables to concatenate three inputs and display dynamically on html.
var input1 = document.querySelector('#input1');
var input2 = document.querySelector('#input2');
var input3 = document.querySelector('#input3');
var span = document.querySelector('span');
var obs1 = Rx.Observable.fromEvent(input1, 'input');
var obs2 = Rx.Observable.fromEvent(input2, 'input');
var obs3 = Rx.Observable.fromEvent(input3, 'input');
obs1.mergeMap((event1) => {
return obs2.map((event2) => {
return event1.target.value + ' ' + event2.target.value;
});
}).mergeMap((result) => {
return obs3.map((event3) => {
return result + ' ' + event3.target.value;
});
}).subscribe((combinedValue) => {
console.log(combinedValue);
return span.textContent = combinedValue;
})
<script src="https://unpkg.com/#reactivex/rxjs#5.3.0/dist/global/Rx.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
<input type="text" id="input3">
<p>Combined value: <span></span></p>
My problem here is that when i type in the first and second inputs, the display does not dynamically show the changes until I enter something into the third input.
My current understanding of mergeMap() is that it flattens a sequence of sequence of observables into a sequence of observables.
I think you want the operator combineLatest().
To make things simpler, I would map the event.target.value after each fromEvent, and perhaps throw in the startWith('') since nothing is happening until the user types.
console.clear()
var input1 = document.querySelector('#input1')
var input2 = document.querySelector('#input2');
var input3 = document.querySelector('#input3');
var span = document.querySelector('span');
var obs1 = Rx.Observable.fromEvent(input1, 'input')
.map(e=>e.target.value)
.startWith('')
var obs2 = Rx.Observable.fromEvent(input2, 'input')
.map(e=>e.target.value)
.startWith('')
var obs3 = Rx.Observable.fromEvent(input3, 'input')
.map(e=>e.target.value)
.startWith('')
Rx.Observable.combineLatest(obs1,obs2,obs3)
.map(([val1,val2,val3]) => val1 + ' ' + val2 + ' ' + val3)
.subscribe((combinedValue) => {
console.log(combinedValue);
return span.textContent = combinedValue;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.7/Rx.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
<input type="text" id="input3">
<p>Combined value: <span></span></p>

Using HTML5 local storage

I am developing a small site and having trouble to maintain the persistence of a cost value across the web pages.
I have tried using the Html5 storage but I can't get it to work.
Here is my Javascript:
function modifyPrice(cost) {
// body...
var total = document.getElementById('totalCost');
var accumulte = total.value;
var temp = cost + Number.isInteger(accumulte) + 15;
total.value = temp;
localStorage.setItem("priceTag",temp);
document.getElementById('pricetag').innerHTML = localStorage.getItem("priceTag");
}
And here's my sample html:
<span>
<span name="price" id="pricetag"></span> $
</span>
Could it be the way I am executing localStorage or is there a better way?
Number.isInteger(accumulte) returns a boolean result. So you have to change your code to something like
var calculate = document.getElementById('calculate');
calculate.addEventListener("click", function() {
var total = document.getElementById('totalCost'),
accumulte = +total.value, // casting int to string.
cost = 10,
temp = cost + (Number.isInteger(accumulte) ? parseInt(accumulte, 10) : 0) + 15;
alert("Value when accumulte is " + total.value + " = " + temp);
}, false);
<input type="text" value="07" id="totalCost" />
<input type="button" value="Calculate" id="calculate" />

java script functions for different textbox my code here

This is my code in html and java script. I coded same things thrice, I want to do it once... what to do...............
<input type="text" name="option1" id="option1" onblur="calc_amt(1);">
<input type="text" name="price1" id="price1" onblur="calc_amt(1);">
<input type="text" name="amount1" id="amount1" readonly>
<input type="text" name="option2" id="option2" onblur="calc_amt(2);">
<input type="text" name="price2" id="price2" onblur="calc_amt(2);">
<input type="text" name="amount2" id="amount2" readonly>
<input type="text" name="option3" id="option3" onblur="calc_amt(3);">
<input type="text" name="price3" id="price3" onblur="calc_amt(3);">
<input type="text" name="amount3" id="amount3" readonly>
<script>
function calc_amt(val){
if(val==1){
var option1 = document.getElementById("option1").value;
var pri1 = document.getElementById("price1").value;
....
document.getElementById("amount1").value=amoun1 ;
}
if(val==2){
var option2 = document.getElementById("option2").value;
var pri2 = document.getElementById("price2").value;
...
document.getElementById("amount2").value=amoun2;
}
if(val==3){
var option3 = document.getElementById("option3").value;
var pri3 = document.getElementById("price3").value;
....
document.getElementById("amount3").value=amoun3;
}
var amoun1=document.getElementById("amount1").value;
var amoun2=document.getElementById("amount2").value;
var amoun3=document.getElementById("amount3").value;
var tot = Number(amt1)+Number(amt2)+Number(amt3);
document.getElementById("amount").value=tot;
}
</script>
how do solve it by coding only once... I am beginner please help me.... any other ideas to solve this.. i need a solution like inheritance.
You can further reduce above script like this. Your amoun is unclear for though. However you can reduce the code like this. This is just an idea and make sure you match the variables with correct statement.
<script>
function calc_amt(val){
var option1 = document.getElementById("option"+val).value;
var pri1 = document.getElementById("price"+val).value;
....
document.getElementById("amount"+val).value=""+amount+val ;
var amoun1=document.getElementById("amount1").value;
var amoun2=document.getElementById("amount2").value;
var amoun3=document.getElementById("amount3").value;
var tot = Number(amt1)+Number(amt2)+Number(amt3);
document.getElementById("amount").value=tot;
}
</script>
Replace:
if(val==1){
var option1 = document.getElementById("option1").value;
var pri1 = document.getElementById("price1").value;
document.getElementById("amount1").value=amoun1 ;
}
with:
var amoun = document.getElementById("amount" + val).value;
var option = document.getElementById("option" + val).value;
var pri = document.getElementById("price" + val).value;
document.getElementById("amount" + val).value=amoun;
TRY...
Remove all inline handler and use blur handler like in demo
$("input[type=text]").on("blur", function () {
var id = this.id;
var last = id.charAt(id.length - 1); // get last id string value
var optionValue = $("#option" + last).val();
var priceValue = $("#price" + last).val();
var option = isNaN(optionValue) ? 0 : +optionValue; // check is nan
var price = isNaN(priceValue) ? 0 : +priceValue;
$("#amount" + last).val(option * price); // display multiply value
$("#amount").text($("input[type=text][id^=amount]").map(function () { // collect all amount1,2,3 values
var value = $(this).val();
return isNaN(value) ? 0 : +value;
}).get().reduce(function (a, b) { // add total value
return a + b;
}));
});
DEMO
OPTIMIZED CODE
$("input[type=text]:not([readonly])").on("blur", function () {
var obj = $();
obj = obj.add($(this)).add($(this).prevUntil('[readonly]')).add($(this).nextUntil('[readonly]'));
$(this).nextAll('[readonly]').first().val($.map(obj, function (val, i) {
return parseInt(val.value, 10) || 0;
}).reduce(function (a, b) {
return a * b
}, 1));
$("#amount").text($("input[type=text][id^=amount]").map(function () {
var value = $(this).val();
return isNaN(value) ? 0 : +value;
}).get().reduce(function (a, b) {
return a + b;
}));
});
DEMO

Matching radio button selection with nested Array content in Javascript

UPDATE 6-25-2014
Any insight would be appreciated!
UPDATE 6-21-2014
I tried to make the radio variables, global so the 'if block' in the 'answerFwd' function could be compared to the correctAnswer Array, but that didn't work!
UPDATE 6-16-2014
ADDED JS FIDDLE
I am building a quiz and creating an array of radio buttons dynamically, and would like to match the selected button with the correct answer I have established in the question array.
html
<div id="responses">
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
<div id="c0" class="choiceText">The Observers</div>
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
<div id="c1" class="choiceText">The Watchers </div>
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
<div id="c2" class="choiceText">The Sentinels</div>
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
<div id="c3" class="choiceText">The Oa</div>
</div>
questions:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0 }, {
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3 },{},{} //other questions];
var item = allQuestions[0];
var currentQuestion = 0;
var playersScore = 0;
//function which creates the buttons
function createRadioButtonFromArray(array) {
var len = array.length;
var responses = document.getElementById("responses");
responses.innerHTML = '';
for (var i = 0; i < len; i++) {
radio = document.createElement("input"); //Updated 6-21-2014 removed 'var'
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
ar radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
responses.appendChild(radio);
responses.appendChild(radioText);
}
}
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
var playerTally = 0; //Updated 6-9-2014
var playerFeedback = " "; //Updated 6-9-2014
var playerMessage = document.getElementById("playerMessage"); //Updated 6-9-2014
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices);
* Updated 6-9-2014 I am stumped; This doesn't work but I was encouraged I got a score tally on the page! Am I comparing the elements correctly? Updated 6-21-2014 This reversed the gain, where I had the tally render on the screen*
if (itemAnswers.correctAnswer === responses.id) { //Updated 6-21-2014
playerTally += 1;
playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
playerMessage.innerHTML = playerFeedback;
}
}
At first I tried to debug this but had trouble finding where the error was coming from.
One thing I noticed was currentAnswer variable was only being set once. (when it was declared)
Another thing that would make this cleaner is storing each response to each question as a property of the questions object.
For example: {"question": "What is the registry of the Starship Reliant?","choices": ["NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],"correctAnswer": 1,"selectedAnswer": 0}
This is a good example of why you may want to use object oriented programming. You can keep the global namespace clean, while also having tighter control over your variables.
I put together this Quiz Code using some object oriented principles:
JavaScript
var Quiz = function(questions) {
this.questions = questions;
this.$template = {
"header": document.querySelector(".question"),
"options": document.querySelector(".question-choices")
};
this.init();
}
Quiz.prototype = {
"init": function() {
this.question = 0;
this.generateQuestion();
this.bindEvents();
},
//gets called when this.question == this.questions.length, calculates a score percentage and alerts it
"score": function() {
var correctCount = 0;
this.questions.forEach(function(question){
if ( (question.selectedAnswer || -1) === question.correctAnswer ) correctCount += 1
})
alert("Score: " + ((correctCount / this.questions.length) * 100) + "%")
},
//Gets called during initialization, and also after a nav button is pressed, loads the question and shows the choices
"generateQuestion": function() {
var question = this.questions[this.question];
this.$template.header.innerHTML = question.question;
this.$template.options.innerHTML = "";
question.choices.forEach(this.createRadio.bind(this));
},
//Binds the previous, and next event handlers, to navigate through the questions
"bindEvents": function() {
var _this = this,
$nextBtn = document.querySelector(".question-navigation--next"),
$prevBtn = document.querySelector(".question-navigation--prev");
$nextBtn.addEventListener("click", function(e) {
//Go to the next question
_this.question++;
if ( _this.question == _this.questions.length ) {
_this.score();
} else {
_this.generateQuestion();
}
});
$prevBtn.addEventListener("click", function(e) {
_this.question--;
if ( _this.question <= 0 ) _this.question = 0
_this.generateQuestion();
});
},
//Create each individual radio button, is callback in a forEach loop
"createRadio": function(choice, index) {
var question = this.questions[this.question];
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "options";
radio.id = "option-"+index;
if ( question.selectedAnswer === index ) {
radio.checked = true;
}
radio.addEventListener("click", function(e) {
question.selectedAnswer = index;
})
var radioText = document.createElement("label");
radioText.setAttribute("for", "option-"+index)
radioText.innerHTML = choice;
radioText.insertBefore(radio, radioText.firstChild);
this.$template.options.appendChild(radioText);
}
}
var q = new Quiz(allQuestions)

Categories

Resources