function to increment / decrement more than stepper in javascript - javascript

Hello I am trying to rewrite a function that will increment / decrement more than 1 stepper in javascript. Here is what I tried so far
here is a codepen link http://codepen.io/Ongomobile/pen/XdyBgv/
Here is 1 of the steppers
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal("one",-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal("one",1)">+1</button>
</div>
// This is current one
function modify_qty(val) {
var qty = document.querySelector("#qty1").value;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.querySelector("#qty1").value = new_qty;
return new_qty;
}
This is what I tried
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
[name].value = new_qty;
return new_qty;
}

A few issues:
What's the purpose of this line parseInt(qty,10) + val;? parseInt is intended to convert a string into its equivalent digit. Not much point in calling it on a base10 number.
Not sure what the point of the name argument to stepperVal is. Isn't the amount to be stepped already implied by the value argument?
You can pass a reference to the object triggering the onclick event by passing this to your function declared within the onclick.
new_qty always evaluates to val
stepperVal(arg,-1) is actually the same as stepperVal(arg,0). Why not just call it that way?
Updated code
replace "one" with this in :
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal(this,-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal(this,1)">+1</button>
</div>
Simplified JS:
function stepperVal(event, val){
clicked_link = event.target
return clicked_link.value = Math.max(0, val); # Return the greater of 0 and `val`
}

Use following it must work:
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(document.getElementsByName(name),10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.getElementsByName(name).value = new_qty;
return new_qty;
}

Related

Slidebar which can be adjusted manually

I did a Slidebar (0-99) which is working well.
I want to add 2 buttons to manually change it (first button -1 ; second button +1).
It was working well with my "-1" code for the first button, but the second one isnt working and I dont understand why. (It add 1 but for example if my slidebar is at 50, when i click its not going to 51 but 501).
Here is my code :
<div>
<button id="moins1" onclick="moins1()">MOINS 1</button>
<span class="unselectable rangeValue1" id="rangeValue1">RR</span>
<Input class="range" type="range" name="BarreRR" value="0" min="0" max="99" onChange="rangeSlide1(this.value)" onmousemove="rangeSlide1(this.value)"></Input>
<button id="plus1" onclick="plus1()">PLUS 1</button>
</div>
<script type="text/javascript">
function rangeSlide1(value) {
document.getElementById('rangeValue1').innerHTML = value;
}
function moins1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop -=1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
function plus1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop +=1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
</script>
Thanks for help, Zartex.
The issue is that textContent returns string and using + operator will try to concatenate the values. So you can parse it. But I would recommend directly connecting your range with displayed value and only alter the range using the buttons or change them together for example:
function rangeSlide1(value) {
document.getElementById('rangeValue1').innerHTML = value;
}
function moins1() {
let range = document.querySelector('.range')
if (range.value != 0) {
let newValue = range.value - 1
document.getElementById('rangeValue1').innerHTML = newValue
range.value = newValue
}
}
function plus1() {
let range = document.querySelector('.range')
if (range.value < 99) {
let newValue = Number(range.value) + 1
document.getElementById('rangeValue1').innerHTML = newValue
range.value = newValue
}
}
<div>
<button id="moins1" onclick="moins1()">MOINS 1</button>
<span class="unselectable rangeValue1" id="rangeValue1">RR</span>
<Input class="range" type="range" name="BarreRR" value="0" min="0" max="99" onChange="rangeSlide1(this.value)" onmousemove="rangeSlide1(this.value)"></Input>
<button id="plus1" onclick="plus1()">PLUS 1</button>
</div>
Considering your range is limited from 0 to 100 I added condition not to go under 0
it will help you,
Yop value always in "50" + 1 it will return by concat 501
so parseInt your string and add/minus by 1
function moins1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop = parseInt(Yop)-1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
function plus1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop = parseInt(Yop)+1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}

How do I make these functions shorter

I was making a simple calculator with two input boxes for each number, and four buttons for each operation underneath. After pressing one of the buttons (Ex:Add) They would perform the operation. However, inside each function I had to keep writing these two lines:
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
Is there a way I could write these before I make each individual function? Could someone with more skill possibly show me what I could do?
function add() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 + Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function sub() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 - Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function mul() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 * Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function div() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 / Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Is there a way I could write these before I make each individual function?
You can get the elements just once:
const input1 = document.getElementById("Value1");
Then when you need its value:
const value1 = input1.valueAsNumber;
In general, you can usually write a function to avoid duplicated logic. Probably not appropriate in this case, but for example:
function getValueAsNumber(id) {
return document.getElementById(id).valueAsNumber;
}
then
const value1 = getValueAsNumber("Value1");
A couple of side notes:
In JavaScript and related languages, the overwhelming convention is to use an initial lower case letter for variables that don't refer to constructor functions. So value1 rather than Value1, value1Element rather than Value1Element, etc.
var is no longer best practice in JavaScript. In new code, prefer let or const because of their more useful scoping.
When putting just plain text in an element, you're better off using textContent rather than innerHTML, because the browser doesn't try to parse the text you give it as HTML.
onxyz-attribute-style event handlers are not best practice, not least because the functions they call have to be globals, and the global namespace is crowded. Consider using modern event handling (addEventListener and the like).
Just for an example, here's your code with some of the above applied, but without going overboard:
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
gid("add").addEventListener("click", () => {
const total = input1.valueAsNumber + input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("sub").addEventListener("click", () => {
const total = input1.valueAsNumber - input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("mul").addEventListener("click", () => {
const total = input1.valueAsNumber * input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("div").addEventListener("click", () => {
const total = input1.valueAsNumber / input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Or we could abstract away everything but the operation itself (just for fun):
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
const clickHandler = (id, operation) => {
// ^^^^^^^^^
gid(id).addEventListener("click", () => {
const total = operation(input1.valueAsNumber, input2.valueAsNumber);
// ^^^^^^^^^
demo.textContent = "Total: " + total;
});
};
clickHandler("add", (a, b) => a + b);
// ^^^^^^^^^^^^^^^
clickHandler("sub", (a, b) => a - b);
clickHandler("mul", (a, b) => a * b);
clickHandler("div", (a, b) => a / b);
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You could even go further than that, but it starts getting hard to follow. :-)
You can make a function to get the value of an element by ID, and re-use it, also you can create 1 function that will show the total as well.
function showTotal(total) {
document.getElementById('demo').innerHTML = "Total: " + total;
}
function getValue(id) {
return document.getElementById(id).valueAsNumber;
}
function add() {
showTotal(getValue("Value1") + getValue("Value2"));
}
function sub() {
showTotal(getValue("Value1") - getValue("Value2"));
}
function mul() {
showTotal(getValue("Value1") * getValue("Value2"));
}
function div() {
showTotal(getValue("Value1") / getValue("Value2"));
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>
Some suggestions:
Let's separate the calculating from the formatted displaying. We'll have one function to calculate (+, -, /, *) and a different function to handle innerHTML-setting.
Since the calculations are all in one function, that removes the redundancy of multiple document.getElementById calls throughout your code.
We can use a switch() statement to determine the operation to apply, although a standard if()/else() also would work.
Working demo...
function operate(e) {
var Total = getOperationTotal(e);
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function getOperationTotal(e) {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var total;
switch(e.target.id) {
case 'add-button':
total = Value1 + Value2;
break;
case 'subtract-button':
total = Value1 - Value2;
break;
case 'multiply-button':
total = Value1 * Value2;
break;
case 'divide-button':
total = Value1 / Value2;
break;
}
return total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button id="add-button" type="button" onclick="operate(event)">Add</button>
<button id="subtract-button" type="button" onclick="operate(event)">Subtract</button>
<button id="multiply-button" type="button" onclick="operate(event)">Multiply</button>
<button id="divide-button" type="button" onclick="operate(event)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You can define global variables and additionally add onchange functions for the input, so as soon as you change the number the value changes in JS too.
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
function updateNr(id){
(id === 1) ? Value1 = document.getElementById('Value1').valueAsNumber : Value2 = document.getElementById('Value2').valueAsNumber;
}
function add() {
var Total = Value1 + Value2;
postAnswer(Total);
}
function sub() {
var Total = Value1 - Value2;
postAnswer(Total);
}
function mul() {
var Total = Value1 * Value2;
postAnswer(Total);
}
function div() {
var Total = Value1 / Value2;
postAnswer(Total);
}
function postAnswer(total){
document.getElementById('demo').innerHTML = "Total: " + total;
}
First Number: <input onchange="updateNr(1)" type="number" id="Value1"><br><br>
Second Number: <input onchange="updateNr(2)" type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="action(this)">Add</button>
<button type="button" onclick="action(this)">Subtract</button>
<button type="button" onclick="action(this)">Multiply</button>
<button type="button" onclick="action(this)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<script>
action = (e) => {
const Value1 = document.getElementById('Value1').valueAsNumber;
const Value2 = document.getElementById('Value2').valueAsNumber;
let Total = null;
switch(e.textContent) {
case 'Add':
Total = Value1 + Value2;
break;
case 'Subtract':
Total = Value1 - Value2;
break;
case 'Multiply':
Total = Value1 * Value2;
break;
case 'Divide':
Total = Value1 / Value2;
break;
}
document.getElementById('demo').innerHTML = `Total: ${Total}`;
}
</script>
</body>
We dont need to write each function for each calculation, Try to reuse the code insted of re-writing it, Since you are trying to execute the same logic but only the arithmetic operators are changed in each function you defined, we can write a single function and change the operators depending on the calculations we intend to perform. Below code uses function calculate(operation) which takes operation as a parameter and gives us the result depending on the argument passed.
Always try to use let insted of var as let has block scope but var doesn't
Also for better code readability and consistency follow naming conventions to name your variables
function calculate(operation){
let total;
let value1 = document.getElementById('Value1').valueAsNumber;
let value2 = document.getElementById('Value2').valueAsNumber;
if(operation == 'add') total = value1 + value2;
else if(operation == 'sub') total = value1 - value2;
else if(operation == 'multiply') total = value1 * value2;
else if(operation == 'devide') total = value1 / value2;
document.getElementById('demo').innerHTML = "Total: " + total;
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="calculate('add')">Add</button>
<button type="button" onclick="calculate('sub')">Subtract</button>
<button type="button" onclick="calculate('multiply')">Multiply</button>
<button type="button" onclick="calculate('devide')">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>

if condition not running even when the condition satisfies

only the else statement in main.js statement where it reads scores-=1 runs and the if condition doesnt even when the condition satisfies. even after clicking on the right option my scores value doesnt increase by 1 instead it always decreasesby 1 which means it only satisfies the else statement
index.html
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
main.js
var questions =[{
question:'abcbcb',
options:['a','b','c','d'],
answer:'b'
}, {
question:"capital of india",
options:['delhi','mum','pune','kol'],
answer:'delhi'
}]
var x = Math.floor(Math.random() * (questions.length));
var scores = 0;
function gameplay(){
var quesn = document.getElementById('question');
quesn.innerHTML =questions[x].question;
for(i=0;i<4;i++){
var opt = document.getElementById('option'+i);
opt.innerHTML = questions[x].options[i];
var score = document.getElementById('scores');
score.innerHTML = scores;
}
}
gameplay();
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
For pure Javascript, use the innerHTML property.
For your example, use the following:
var spanVal = document.getElementById("option0").innerHTML;
var x = document.getElementById("option0").innerHTML;
console.log(x)
That is how you can attain the value, ".innerText" would also work.
(btw you labeled this as a question in java, this is javascript. Very different.
Hope this helps.
WORKING SAMPLE
Replace this
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
With this
function answer(ans)
{
var myAnswer = document.getElementById('option'+ans);
if(myAnswer.innerHTML == (questions[x].answer))
{
scores += 1;
}
else{
scores -= 1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
console.log(ans);
}
Then this
<p id="question"></p>
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>
With this
<p id="question"></p>
<div class="buttons">
<button id="button0" onclick ="answer('0')"><span id="option0"></span></button>
<button id="button1" onclick ="answer('1')"><span id="option1"></span></button>
<button id="button2" onclick ="answer('2')"><span id="option2"></span></button>
<button id="button3" onclick ="answer('3')"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>

How to reuse code block in javascript

I am new to learning javascript and apologize if this question is too basic. I have tried to search for a solution but nothing has been clear to me. I have created this code in this link.
https://jsfiddle.net/5p7wzy9x/3/
var btn = document.getElementById("calc");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
var totalTb = document.getElementById("total");
totalTb.value = count ? output : "NaN";
});
var btn = document.getElementById("calcTwo");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = (total / count);
var totalTb = document.getElementById("total");
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
My question is, how would I go about being able to use the same code for the second "grade" button without having to copy and pasting the same code?
I saw that you can use functions to invoke the same code block but am confused how I would go about it. I apologize if this question has already been answered, but I have diligently searched and tried to figure this out on my own. Thank you in advanced.
Instead of passing anonymous functions (functions with no names) to your event handlers as data:
btn.addEventListener("click", function() { ...
set up those functions as "function declarations" so that you can call them by name. Then, instead of passing them into the .addEventListner() method call, you reference them by name (without parenthesis next to the name).
Here's an example:
// Both buttons are configured to call the same event handling function:
document.getElementById("btn1").addEventListener("click", doSomething);
document.getElementById("btn2").addEventListener("click", doSomething);
function doSomething(){
console.log("Hello!");
}
<input type=button id="btn1" value="Click Me">
<input type=button id="btn2" value="Click Me">
Here is how you can combine common code in one function:
var btn = document.getElementById("calc");
var btn2 = document.getElementById("calcTwo");
var totalTb = document.getElementById("total");
btn.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output < Infinity ? output : "NaN";
});
btn2.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
function getTotal() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
return output;
}
<form id="form1">
<input class="value" type="text" value="80" /><br />
<input class="value" type="text" value="50" /><br />
<input class="value" type="text" value="15" /><br />
<input class="value" type="text" value="30" /><br />
<input class="value" type="text" value="90" /><br />
<br />
<input type="text" id="total" />
<button type="button" id="calc">Calculate</button>
<button type="button" id="calcTwo">Grade</button>
</form>

Auto calculation occurs on previous value

i have a function that increments a number, takes the total and multiplies it by a price. However, when I click the button that increments for the first time it doesn't do anything. I click the button a second time and it works. However if I then click the button that decreases, then it does the previous function (e.g. adding) then pressing it a second time will decrease the value.
I understand that the onClick="myFunction()" may be in the wrong place, however I don't know where to put it. I want the total to be calculated automatically. A demo can be found at http://alpha.kentishtours.co.uk/destinations/bruges.php
The function that takes the value and multiplies it and calculates the total.
function myFunction()
{
var a = document.getElementById('adult').value;
z=39;
x=a*z;
var c = document.getElementById('child').value;
if(a >= 1) {
a=+30; }
else {
a=+39; }
b=c;
c=a*b
d=x+c
document.getElementById("total").innerHTML=d;
document.getElementById("value").value = d;
}`
These are the buttons that increment the number and call the function to calculate.
<div class="calculator">
<div class="calculator-submodule input-group">
<h4>Adult (12+)</h4>
<button class="btn theme-btn" id="decrease" value="Decrease Value" onClick="myFunction()" >-</button>
<input type="text" id="adult" value="1" class="form-control input-usmall" min="0" disabled>
<button class="btn theme-btn" id="increase" value="Increase Value" onClick="myFunction()" >+</button>
</div>
<div class="calculator-submodule input-group">
<h4>Child (2-11)</h4>
<button class="btn theme-btn" id="decreasec" value="Decrease Value" onClick="myFunction()" >-</button>
<input type="text" id="child" value="0" class="form-control input-usmall" min="0" disabled>
<button class="btn theme-btn" id="increasec" value="Increase Value" onClick="myFunction()" >+</button>
</div>
<div class="calculator-submodule">
<span class="pound">£</span>
<span id="total">39</span><span class="pound">.00</span>
</div>
You have functions in your increment.js script that change the value of the input after you get them in "myfuntion". You need to calculate the prices after the values are changed.
So first you should remove the lines below from this file:
http://alpha.kentishtours.co.uk/assets/scripts/increment.js
$("#increase").click(function(){
var $n = $("#adult");
$n.val(Number($n.val())+1);
});
$("#decrease").click(function(){
var $n = $("#adult");
$n.val(Number($n.val())-1);
});
$("#increasec").click(function(){
var $n = $("#child");
$n.val(Number($n.val())+1);
});
$("#decreasec").click(function(){
var $n = $("#child");
$n.val(Number($n.val())-1);
});
Also remove the onClick="myFunction()" attribute in your HTML form.
Then change all your myFunction script to this:
var adult = $('#adult'),
child = $('#child'),
total = $('#total'),
value = $('#value'),
increase = $('#increase'),
decrease = $('#decrease'),
increasec = $('#increasec'),
decreasec = $('#decreasec');
var calulate_price = function(a, c){
var p1 = 39,
p2 = 30,
PA = a * p1,
PC, d;
if(a >= 1) PC = c * p2;
else PC = c * p1;
d = PA + PC;
total.text(d);
value.val(d);
};
increase.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
adult.val(++a);
calulate_price(a, c);
});
decrease.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
adult.val(--a);
calulate_price(a, c);
});
increasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
child.val(++c);
calulate_price(a, c);
});
decreasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
child.val(--c);
calulate_price(a, c);
});
Everything working: http://jsbin.com/ohUniCa/2/edit?js,output

Categories

Resources