I'm writing an <input type="number"> with - and + button for an ecommerce cart.
The structure of each group is:
1x <button class="minus" data-prod="prod_id_int">
1x <input type="number" id="prod_id_int">
1x <button class="plus" data-prod="prod_id_int">
What I'm trying to do now is disabling the button - if the value of the input type number is < 1.
To achieve it, based on my script, I have to disable not the general <button class="minus"> but the specific <button class="minus" data-prod="prod_id_int">.
I tried this
$(buttonClass).data('prod', dataProd).prop('disabled', true);
and it actually prevents the quantity from being < 1 BUT it doesn't really add the property disabled to the button. I'm not sure, then, that it's the right way. Can someone explain me how to achieve it?
Here the working snippet
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = parseInt(inputToChangeValue) - parseInt(1);
if (newValue < 1) {
$(buttonClass).data('prod', dataProd).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 1.5%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="62">
<button class="plus" data-prod="90">+</button>
Here is solution.
$('.'+buttonClass).data('prod', dataProd).prop('disabled', true);
All you need is to concatenate . symbol to your class.
buttonClass returns only the className, such as minus and you need jquery selector, like this: $('.minus')
Also, I recommend you to use this: var newValue = --inputToChangeValue; for a simply way to decrement value, instead var newValue = parseInt(inputToChangeValue) - parseInt(1);
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = --inputToChangeValue;
if (newValue < 1) {
$('.'+buttonClass).filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
$('.minus').filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', false);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 10%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="12">
<button class="plus" data-prod="90">+</button>
Related
****UPDATE****
I was able to have below issue work with the help of #JasonB.
In addition, I also have another 3 textareas on the same form that will only show when its checkbox is clicked. How will I add that on my current script? I tried grouping it the same way as TextBoxesGroup but just giving another id but when I hit submit, even if I didn't clicked the checkbox, values inside are being submitted. Thank you so much in advance. I'm really new to programming and I'm trying to learn the basics.
HERE'S MY CODE for the checkbox
<textarea id="text" >NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text1">NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text2">NAME-
ADDRESS-
ETC-</textarea>
<input type="checkbox" id="myCheck" onclick="myFunction()">DETAILS
<input type="checkbox" id="myCheck1" onclick="myFunction1()">DETAILS
<input type="checkbox" id="myCheck2" onclick="myFunction2()">OTHERS
<script>
function myFunction() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myFunction1() {
var checkBox1 = document.getElementById("myCheck1");
var text1 = document.getElementById("text1");
if (checkBox1.checked == true){
text1.style.display = "block";
} else {
text1.style.display = "none";
}
}
function myFunction2() {
var checkBox2 = document.getElementById("myCheck2");
var text2 = document.getElementById("text2");
if (checkBox2.checked == true){
text2.style.display = "block";
} else {
text2.style.display = "none";
}
}
</script>
PREVIOUS QUESTION
I have a form with multiple textareas. I'm not familiar with any databases so instead of using one, I prefer using or saving the values/inputs of my textarea to another textarea on submit. I was able to make it work but with those textareas being added dynamically, I only get the first textarea.
here's my script
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 15) {
alert("Only 15 textboxes allowed");
return false;
}
$('<div/>',{'id':'TextBoxDiv' + counter}).html(
$('<textarea/>',{'id':'myTextArea' + counter ,'class':'myTextArea'}).html( 'STEP ' + counter + ' : ' )
)
.appendTo( '#TextBoxesGroup' )
$("#myTextArea" + counter).each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
$(document).ready(function() {
$("#btn-primary").click(function() {
e=1;
var text55 = $('#textarea55').val();
var text56 = $('#textarea56').val();
var text57 = $('#textarea57').val();
var text58 = $('#textarea58').val();
var text59 = $('#textarea59').val();
var text60 = $('#textarea60').val();
var text61 = $('#textarea61').val();
var text62 = $('#textarea62').val();
var myTextArea = $('#myTextArea'+e).val();
$('#inputTextToSave').val( $('#inputTextToSave').val()+text55+'\n'+text56+'\n'+text57+'\n'+'TROUBLESHOOTING NOTES'+'\n'+myTextArea+'\n'+text58+'\n'+text59+'\n'+text60+'\n'+text61+'\n'+text62+'\n');
e++;
});
here's my html
<textarea id="textarea55" name="caller"></textarea><br>
<textarea id="textarea56" name="auth"></textarea><br>
<textarea id="textarea57" name="issue"></textarea><br>
<label>TROUBLESHOOTING NOTES:</label><br>
<body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv"></div></div>
<input type='button' value='ADD TS STEPS' id='addButton' class="bubbly-button">
<input type='button' value='REMOVE TS' id='removeButton' class="bubbly-button"><br><\body>
<textarea id="textarea58" name="acct"></textarea><br>
<textarea id="textarea59" name="tid"></textarea><br
<textarea id="textarea60" name="resolution"></textarea><br>
<textarea id="textarea61" name="case"></textarea><br>
<textarea id="textarea62" rows="1" disabled>YANA</textarea>
<input type='button' value='SUBMIT' id='btn-primary' class="bubbly-button"><br>
my css
div {
padding: 1px;
}
textarea {
outline: none;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
}
.myTextArea {
width: 535px;
min-height: 14px;
overflow-y: hidden;
font-size: 14px;
border: 3px solid orange;
background-color:white;color:mediumvioletred;
display: block;
}
body{
font-size: 14px;
font-family: 'tempus sans ITC', 'Arial';
color: mediumvioletred;
text-align: center;
background-color: pink;
}
Your dynamically created textareas are all in #TextBoxesGroup.
To select them all at the time of submission, you can call $('#TextBoxesGroup textarea'). To append their contents into a string with '\n' characters separating them you can use jQuery's .map function to get the text of each element in an array wrapped in a jQuery object, .get to get the underlying array, and .join to concatenate the strings with '\n' as the glue.
var contents = $('#TextBoxesGroup textarea')
.map(function() {
return $(this).text();
})
.get()
.join('\n');
console.log( contents );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="TextBoxesGroup">
<div><textarea>One</textarea></div>
<div><textarea>Two</textarea></div>
<div><textarea>Three</textarea></div>
</div>
This question already has answers here:
How to get the selected radio button value using js
(19 answers)
Closed 5 years ago.
I have a set of dynamically generated radio buttons against each data of the list but I am not able to get the checked radio button value. Please help!!
function displayList()
{
var arr=["Apple", "Banana", "Grapes"];
var list
var output="";
var output2="";
var output3="";
var output4="";
for(var i=0; i<arr.length; i++)
{
list=arr[i];
output+= '<input type="checkbox" value='+list+' name="box2">' + ' ' + list+' '+'<br><br>';
output2+= 'yes:<input type="radio" value="yes" name="box2'+i+'">'+'no:<input type="radio" value="yes" name="box2'+i+'">'+'<br><br>';
output3+= '<button type="button" id="myBtn" onclick="displayCardList()" >Add Prompt</button>'+'<br><br>';
//onclick="myfunction()"
output4+= '<button type="button" id="mySaveBtn" onclick="addEntity()" >Save </button>'+'<br><br>';
document.getElementById("List").innerHTML=output;
document.getElementById("radioBtn").innerHTML=output2;
document.getElementById("myBtn").innerHTML=output3;
}
}
<html>
<body onload="displayList()">
<div class="row">
<div class="col-sm-4"><div style="font-size:16px" id="List"> </div></div>
<div class="col-sm-4"><div style="font-size:16px" id="radioBtn"></div></div>
<div class="col-sm-4"><div id="myBtn"></div></div>
</div>
</body>
</html>
But first, let me separate content
I recommend using template tag to separate JavaScript from HTML, as you should always do.
You can then insert as many items using that template, as you wish. As you can see below it's quite tedious using pure JavaScript. I'd recommend using Handlebars.
var getRadioValue = function(name) {
var radios = document.getElementsByName(name);
for (var i = 0, length = radios.length; i < length; ++i) {
if (radios[i].checked) {
return radios[i].value
}
}
return null;
};
var Actions = {
addPrompt: function(i) {
var value = getRadioValue('fruit-fresh-' + i);
if (value == "no") {
prompt('Why is ' + fruits[i] + ' not fresh? Explain:');
}
else if (value == "yes") {
alert('We are glad that ' + fruits[i] + ' is fresh! Good job!');
}
else {
alert('Please, check the corresponding value for ' + fruits[i] + ' freshness!');
}
},
save: function(i) {
alert('Saving: ' + fruits[i]);
},
generateMarkupForFruit: function(i, fruitName) {
var template = document.querySelector('#fruits-template');
var row = document.importNode(template.content, true);
var fruitId = 'fruit-' + i,
fruitField = row.querySelector('.fruit'),
fruitLabel = row.querySelector('.fruit-label');
fruitField.value = fruitName;
fruitField.setAttribute('id', fruitId);
fruitLabel.textContent = fruitName;
fruitLabel.setAttribute('for', fruitId);
var yesId = 'fruit-yes-' + i,
noId = 'fruit-no-' + i,
groupId = 'fruit-fresh-' + i,
yesField = row.querySelector('.yes'),
yesLabel = row.querySelector('.yes-label'),
noField = row.querySelector('.no'),
noLabel = row.querySelector('.no-label');
yesField.setAttribute('name', groupId);
yesField.setAttribute('id', yesId);
yesLabel.setAttribute('for', yesId);
noField.setAttribute('name', groupId);
noField.setAttribute('id', noId);
noLabel.setAttribute('for', noId);
var addPromptBtn = row.querySelector('.add-prompt-btn'),
saveBtn = row.querySelector('.save-btn');
addPromptBtn.addEventListener('click', Actions.addPrompt.bind(null, i));
saveBtn.addEventListener('click', Actions.save.bind(null, i));
return row;
}
};
var fruits = ["Apple", "Banana", "Grapes"];
var table = document.querySelector('#fruits');
for (var i = 0; i < fruits.length; ++i)
{
var row = Actions.generateMarkupForFruit(i, fruits[i]);
table.appendChild(row);
}
#fruits {
width: 100%;
border-collapse: collapse;
}
#fruits td,
#fruits th {
border: solid 1px;
padding: 0.25em;
}
#fruits th {
color: #fff;
background: #000;
}
#fruits .actions {
text-align: center;
}
#fruits .actions .save-btn {
font-weight: bold;
}
<table id="fruits">
<tr>
<th>Fruit</th>
<th>Is fruit fresh?</th>
<th>Actions</th>
</tr>
</table>
<template id="fruits-template">
<tr>
<td>
<input type="checkbox" class="fruit">
<label class="fruit-label"></label>
</td>
<td>
<input type="radio" class="yes" value="yes">
<label class="yes-label">Yes</label>
<input type="radio" class="no" value="no">
<label class="no-label">No</label>
</td>
<td class="actions">
<button type="button" class="add-prompt-btn">Add Prompt</button>
<button type="button" class="save-btn">Save</button>
</td>
</tr>
</template>
I have input with an id and i need to add a class to the id when it is checked(true) and remove when it is false.
<input id="<?= $ec['id']?>" type="checkbox" value="<?= $ec['id']?>" class="category" onclick="handleClick(this)" >
<script>
function handleClick(cb) {
var id= cb.id;var checked = cb.checked ;
console.log("id is " + id + cb.checked);
if ($('#id').is(':checked')) {
console.log("inside if");
}
}
</script>
You can try this
function handleClick(cb) {
var id= cb.id;
var checked = cb.checked ;
console.log("id is " + id + cb.checked);
if(cb.checked) {
$(cb).addClass('check');
}
else {
$(cb).removeClass('check');
}
}
function handleClick(cb)
{
$(cb).prop('checked') ? $(cb).addClass('checkboxSelected') : $(cb).removeClass('checkboxSelected');
}
Use .toggleClass() with state
function handleClick(cb) {
$(cb).toggleClass('checked', cb.checked);
}
.checked {
border: solid #ff0000 5px;
width: 30px;
height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" value="100" class="category" onclick="handleClick(this)">
I am working on a app dashboard, where I am trying to add a jquery calculator inside webui-popover. the calculator is working fine outside the popover but when it is inside the popover div it is not working. The plugin author said "This problem is caused by that the plugin stop the event bubbling",
I do not have much knowledge about Jquery or Javascript, If anyone can help me with this it will be nice. So, is there any way to make the calculator work inside popover element?.
Calculator Script taken from HERE
Here is the codes
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>
Use dismissible:false
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true,
dismissible:false
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>
I made a way to add and remove fields using the input[type"number"]. I use jquery to do this but the way I did is not perfect. If there's a value in the field, the value will get erase if the number value is change because of using .remove(). Is there a better way to doing this?
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
<script>
$('#num').bind('keyup mouseup', function () {
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
</script>
My Fiddle
Try something like this. Instead of removing all of the inputs every time, this just removes the ones on the end, or adds more to the end.
The main difference between this one and yours is that I added var totNum = 0; to keep track of the current number of input there are. I then used that to determine how many to add/remove.
var totNum = 0;
$(document).on('keyup mouseup', '#num', function(){
var num = $(this).val();
if (num != "")
{
if (totNum == 0)
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
for (var i = num; i < totNum; i++)
{
$('.dynamicInput .row:last-child').remove();
}
for (var i = totNum; i < num; i++)
{
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
totNum = num;
if (totNum == 0)
{
$('.dynamicInput h4').remove();
$('.dynamicInput .row').remove();
}
}
});
input[type="number"] {
width: 200px;
height: 30px;
font-family: Arial, sans-serif;
font-size: 20px;
}
.row {
display: block;
margin-bottom: 15px;
}
body {
width: 100%;
padding: 40px;
}
input[type="text"] {
width: 100%;
}
.col1,
.col2 {
width: 45%;
display: inline-block;
margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
It's easier and less likely to fail using a data structure as a skeleton upon which you can build the view. Note that this technique requires an extra computation in order to save user inputs, this is the reason why I've added the "change" event.
In the following code snippet, I've made two panels side by side. The left one is a list of inputs, very close to yours, easy to adapt to your needs, while the right one allows to see the evolution of the "data" array according to user actions.
Both panels rely on the "data" array, in other words, as soon as new items are added to or removed from "data", or a single item is updated, both panels are fully rebuilt. Note that the "change" event takes advantage of event delegation in order to deal with newly added inputs.
Finally, the "update" functions update the entire data source or a single item of the data source when the corresponding input changes, while the "render" functions draw on the data source to keep the panels in sync with the data. By the way, the right panel is rendered once at starting.
$(function () {
var data = []; // data source
var $num = $('#num'); // input for number of rows
var $left = $('#left'); // left panel
var $right = $('#right'); // right panel
// render the right panel at starting
renderRightPanel();
// when the number of rows changes:
// - rebuild the left panel entirely
// - keep the data list up to date
// - print the array to the right panel
$num.on('keyup mouseup', function () {
renderLeftPanel($(this).val());
updateList();
renderRightPanel();
});
// when a value changes:
// - keep the data item up to date
// - print the array to the right panel
$left.on('change', 'input', function () {
var i = $left.find('input').index(this);
updateItem(i, $(this).val());
renderRightPanel();
});
// updates the data list
function updateList () {
data = $left.find('input').map(function () {
return $(this).val();
}).get();
}
// updates a single data item
function updateItem (index, value) {
data[index] = value;
}
// refreshes the DOM of the right panel
function renderRightPanel () {
$right.html('<pre>data = ' + (
JSON.stringify(data, 0, 4)
) + '</pre>');
}
// refreshes the DOM of the left panel
function renderLeftPanel (nLines) {
var i;
var html = '';
if (nLines > 0) {
html = '<h4>Heading</h4>';
for (i = 0; i < nLines; i++) {
html += '<div><input value="' + (data[i] || '') + '" /></div>';
}
}
$left.html(html);
}
});
body * {
padding: 0;
margin: 0;
}
h4, input {
margin-bottom: .5em;
}
#panels {
border: 1px solid black;
}
#panels > div {
display: table-cell;
padding: 1em;
}
#right {
border-left: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panels">
<div id="left"></div
><div id="right"></div>
</div>
Disable and hide extra elements instead of removing them. That will prevent them from getting posted, and also retain the previous value of all values that have been entered. See fiddle
One last point, if you don't want to retain values of hidden elements, change .hide() to .hide().val("")
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput">
<h4>Please fill in the name and email of each extra attendees</h4>
</div>
</body>
<style>
.col1, .col2 { display: inline; width: 48%; margin-right: 2%; }
.row { padding: 5px; }
</style>
<script>
for (var i = 0; i < 20; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
$('#num').bind('keyup mouseup', function () {
var num = parseInt($(this).val());
$('.dynamicInput .row')
.slice(num)
.hide()
.attr('disabled','disabled');
if ( num > 0) {
$('.dynamicInput .row')
.slice(0,num).show()
.removeAttr('disabled');
$('.dynamicInput h4').show();
} else {
$('.dynamicInput h4').hide();
}
}).trigger('keyup');
</script>
Off-hand, you could cache the values within javascript to resist losing them between #num changes. e.g.
(function($){
var $num = $('#num'),
$dynamic = $('.dynamicInput');
cache = {};
$dynamic.on('change', 'input', function(e){
cache[$(this).prop('name')] = $(this).val();
});
$num.on('change keyup mouseup', function(e){
$dynamic.empty();
var val = parseInt($(this).val(), 10);
if (!isNaN(val) && val > 0){
$('<h4>')
.text('Please fill in the name and email of each extra attendees')
.appendTo($dynamic);
for (var i = 0; i < val; i++){
var nameName = 'attendeesName' + i,
emailName = 'attendeesEmail' + i;
var $row = $('<div>',{'class':'row'}),
$col1 = $('<div>',{'class':'col1'}).appendTo($row),
$col2 = $('<div>',{'class':'col2'}).appendTo($row);
$('<input>',{
'type': 'text',
'name': nameName,
'placeholder': 'Name',
'required': 'true'
}).val(cache[nameName] || '').appendTo($col1);
$('<input>',{
'type': 'email',
'name': emailName,
'placeholder': 'Email',
'required': 'true'
}).val(cache[emailName] || '').appendTo($col2);
$row.appendTo($dynamic);
}
}
});
})(jQuery);
input[type="number"] {
width:200px;
height:30px;
font-family:Arial, sans-serif;
font-size:20px;
}
.row {
display:block;
margin-bottom:15px;
}
body{
width:100%;
padding:40px;
}
input[type="text"]{
width:100%;
}
.col1, .col2{
width:45%;
display:inline-block;
margin-right:10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
Here is an attempt to improve the accepted answer:
$(function () {
var $num = $('#num');
var $panel = $('#panel');
var h4 = '<h4>Heading</h4>';
var row = '<div><input /></div>';
$num.on('mouseup keyup', function () {
var n, $inputs;
var value = $(this).val();
if (value <= 0) {
$panel.empty();
}
else {
$inputs = $panel.find('input');
// get the number of inputs already added
n = $inputs.size();
// add your heading if there is no input
if (n === 0) {
$panel.append(h4);
}
// the user wants less inputs
if (value < n) {
$inputs.slice(value).remove();
}
// the user wants more inputs
else if (value > n) {
$panel.append(
// a little trick, see below
new Array(value - n + 1).join(row)
);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panel"></div>
A word on the "array join trick":
var a = [1, 2, 3, 4];
console.log(a.join('+'));
// prints "1+2+3+4"
var b = new Array(4); // an array of 4 undefined items
console.log(b.join('+'));
// prints "+++"
var c = new Array(3);
console.log('<ul>' + c.join('<li>item</li>') + '</ul>');
// prints "<ul><li>item</li><li>item</li></ul>"
This is what exactly you are looking for,
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#num").keyup(function(){
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
});
</script>
</head>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
</html>