Duplicate input's value when clicked to button - javascript

I have a two similar forms with input "Quantity" and buttons "-", "+".
I need to duplicate input's value to second form and back.
For example: When I'm click to "+" in first form it will be incremented.
I need to in the second form was the same value.
<div class="quantity">
<input class="subtraction" name="sub" type="button" value="-">
<input type="number" step="1" name="qty" value="1" class="input-text qty text panel-quantity" size="4" />
<input class="addition" name="add" type="button" value="+">
</div>
<div class="quantity">
<input class="subtraction" name="sub" type="button" value="-">
<input type="number" step="1" name="qty" value="1" class="input-text qty text panel-quantity" size="4"/>
<input class="addition" name="add" type="button" value="+">
</div>
JS:
$(function(){
$('.quantity').on('click', '.addition, .subtraction', function() {
var quantityPanel = $('.panel-quantity');
var quantity = $(this).closest('.quantity').find('input.qty');
var currentValue = parseInt(quantity.val());
var maxValue = parseInt(quantity.attr('max'));
var minValue = parseInt(quantity.attr('min'));
if($(this).is('.addition')) {
if(maxValue && (currentValue >= maxValue)){
quantity.val(maxValue);
} else {
quantity.val((currentValue + 1));
}
} else {
if (minValue && (currentValue <= minValue)) {
quantity.val(minValue);
} else if(currentValue > 0) {
quantity.val((currentValue - 1));
}
}
quantity.trigger('change');
});
});
I think that I can just set the same name for the INPUT, so that they work the same way.
Thanks
It's my example in jsfiddle

add $('input.qty').not(quantity).val(quantity.val()); before triggering change in the input box. and also you have add $('input.qty').not(this).val($(this).val()); in onchange listener of input.qty
$(function(){
$('.quantity').on('click', '.addition, .subtraction', function() {
var quantityPanel = $('.panel-quantity');
var quantity = $(this).closest('.quantity').find('input.qty');
var currentValue = parseInt(quantity.val());
var maxValue = parseInt(quantity.attr('max'));
var minValue = parseInt(quantity.attr('min'));
if($(this).is('.addition')) {
if(maxValue && (currentValue >= maxValue)){
quantity.val(maxValue);
} else {
quantity.val((currentValue + 1));
}
} else {
if (minValue && (currentValue <= minValue)) {
quantity.val(minValue);
} else if(currentValue > 0) {
quantity.val((currentValue - 1));
}
}
$('input.qty').not(quantity).val(quantity.val());
quantity.trigger('change');
});
$('input.qty').on('change', function() {
$('input.qty').not(this).val($(this).val());
});
$('input.qty').on('keyup', function() {
$('input.qty').not(this).val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quantity">
<input class="subtraction" name="sub" type="button" value="-">
<input type="number" step="1" name="qty" value="1" class="input-text qty text panel-quantity" size="4" />
<input class="addition" name="add" type="button" value="+">
</div>
<div class="quantity">
<input class="subtraction" name="sub" type="button" value="-">
<input type="number" step="1" name="qty" value="1" class="input-text qty text panel-quantity" size="4"/>
<input class="addition" name="add" type="button" value="+">
</div>

Related

Trying to make D100 rolling application, cannot get the statuses in my array to print once I start dividing the value

const roll = $(".roll-btn");
const rollVal = $("#roll-number");
const rollStat = $("#roll-status");
const luckRoll = $("#roll-luck-btn");
const charSheet = $("#char-sheet-container")
const stat = $('.stat')
let result = Math.ceil(Math.random() * 99);
//converts the hidden value of the roll to being seen
rollVal.attr("data-state", "reveal");
if (rollVal.data("data-state", "reveal")) {
rollVal.css("display", "block");
}
//converts the hidden status to being seen
rollStat.attr("data-state", "reveal");
if (rollStat.data("data-state", "reveal")) {
rollStat.css("display", "block");
}
const rollOneHundred = () => {
result = Math.ceil(Math.random() * 99);
if (result) {
rollVal.data("data-state", "reveal");
rollVal.text(result);
}
};
roll.on("click", function () {
let two = stat.val() / 2;
let five = stat.val() / 5;
rollOneHundred();
let status = ['Critical Success', 'Extreme Success', 'Hard Success', 'Success', 'Failure', 'Critical Failure']
if (result >= 99) {
rollStat.text(status[5]);
rollStat.data("data-state", "reveal");
} else if (result > stat.val()) {
rollStat.text(status[4]);
rollStat.data("data-state", "reveal");
} else if (result <= stat.val()) {
rollStat.text(status[3]);
rollStat.data("data-state", "reveal");
} else if (result <= two) {
rollStat.text(status[2]);//won't print
rollStat.data("data-state", "reveal");
} else if (result <= five) {
rollStat.text(status[1]);//won't print
rollStat.data("data-state", "reveal");
return;
} else if (result <= 1) {
rollStat.text(status[0]);//won't print
rollStat.data("data-state", "reveal");
return;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main id="root">
<section id="char-sheet-container">
<h2>Character Sheet</h2>
<h3>Base Characteristics</h3>
<label for="str">Strength</label>
<input type="number" id="str" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="dex">Dexterity</label>
<input type="number" id="dex" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="int">Intelligence</label>
<input type="number" id="int" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="wis">Wisdom</label>
<input type="number" id="wis" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="pow">Power</label>
<input type="number" id="pow" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<h3>Vital Characteristics</h3>
<label for="luck">Luck</label>
<input type="number" id="luck" class="stat"><button type="button" class="roll-btn">Roll</button>
<button type="button" id="roll-luck-btn" data-state="hidden">Roll Luck</button><br>
<label for="con">Constitution</label>
<input type="number" id="con" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="vit">Vitality</label>
<input type="number" id="vit" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="me">Mind's Eye</label>
<input type="number" id="me" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<h3>Skills</h3>
<label for="atmo">Atmosphere</label>
<input type="number" id="atmo" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<label for="not">Notice</label>
<input type="number" id="not" class="stat"><button type="button" class="roll-btn">Roll</button><br>
<br>
<button type="button" id="add-skill">Add A Skill</button><br>
</section>
<section id="results-container">
<h4 data-state="hidden" id="roll-number"></h4>
<h4 data-state="hidden" id="roll-status"></h4>
</section>
</main>
I can't get them to print. Also the only value its doing the calculation for is the one in the first skill out of 11 total as you can see in the html, I want people to be able to roll for each skill individually and be able to change that number dynamically as the game progresses. Any thoughts?

How to clear form when radio button is changed

I want to clear form when the radio button is changed. Example gender is male and I fill number in weight input only If I change gender, the form will be clear or when I fill number in all input and click calculate and then BMR show me If I change gender, the form will be clear too.
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
let weight = +document.getElementById('weight').value;
let height = +document.getElementById('height').value;
let age = +document.getElementById('age').value;
if (weight && age && height) {
let result = (10 * weight) + (6.25 * height) - (5 * age)
result += gender === 'male' ? 5 : -161;
document.getElementById('result').innerHTML = result.toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
const clearForm = () => {
document.getElementById('do-form').reset();
document.getElementById('showResult').style.display = "none";
}
const changeGender = () => {
let form = toBmr();
let r = document.getElementById('showResult').style.display;
if (r == "block") {
form = document.querySelector('[name=gender]:checked').addEventListener('change', clearForm());
}
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<div id="selectGender" onchange="changeGender()">
<p>Gender:
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</p>
</div>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
use form.reset() and then check the button
clearForm = (el) => {
document.querySelector("#f1").reset(); // reset the form
el.checked = true; // since we passed the element into the function we can simply check it
}
<form id="f1">
<input type="text" name="t" /><br />
<input type="radio" id="b1" name="b" value="b1" onclick="clearForm(this)" />
<label for="b1">b1</label><br>
<input type="radio" id="b2" name="b" value="b2" onclick="clearForm(this)" />
<label for="b2">b2</label><br>
</form>

add additional value to the total

I am looking for a way to add the value from (discount) and (quantity) to my total. As for discount part, the customer will need to enter the right code to receiver discount. And for quantity, when clicked at the checkbox, then change the quantity, the total will also follow. Can you guys help me out on this problem?
thanks
(sorry, my English is not good)
function addItemPrice() {
var total = 0;
var count = 0;
for (var i = 0; i < document.myform.item.length; i++) {
if (document.myform.item[i].checked) {
total = (total + document.myform.item[i].value * 1); // another way to convert string to number
count++;
}
}
return total;
}
var sh_prices = new Array();
sh_prices["standard"] = 10;
sh_prices["express"] = 20;
function getAddShipping() {
var shippingPrice = 0;
var theForm = document.forms["myform"];
var shipping = theForm.elements["shipping"]
for (var i = 0; i < shipping.length; i++) {
if (shipping[i].checked) {
shippingPrice = sh_prices[shipping[i].value];
break;
}
}
return shippingPrice;
}
function getCode() {
var theForm = document.forms["myform"];
var discode = theForm.elements["discount"]
if (discode == "UAC123") {
alert("yes");
} else {
alert("no")
}
}
function getTotal() {
var totalPrice = getAddShipping() + addItemPrice();
document.getElementById('Price').innerHTML = "the total price" + totalPrice;
}
<form name="myform">
Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity"><br> Sickle $1 <input type="checkbox" name="item" value="1" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $50 <input type="checkbox" name="item" value="50" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $7 <input type="checkbox" name="item" value="7" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Standard
<input type="radio" name="shipping" value="standard" onClick="getTotal(shipping)" /> Express
<input type="radio" name="shipping" value="express" onClick="getTotal(shipping)" /> <br> Discount code
<input type="text" name="discount" size=15>
<input type="button" id="code" value="check" onClick="getCode(code)">
<div id="Price">
</div>
</form>

jQuery iterate through input fields and disable

I have a question I'm trying to figure out...
I have a lot of inputs in a form, but I only need to iterate through the ones in the div with player class.
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
What I need is to iterate through them all once an input field has been modified and calculate how many of the input fields have 0 in them and if its 1 or more than 4 disable submit button.
I've been trying like this but it doesn't seem to work
$(document).ready(function()
{
$(function()
{
var $sum = parseInt($("#sum").text(), 10);
var $num = 0;
if(($sum == 0))
{
$("button[name=submit2]").attr("disabled", "disabled");
}
$(".player input[type=text]").bind("DOMSubtreeModified", function()
{
$.each($("input[type=text]"),function(){
if (!isNaN(+this.value))
{
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
});
})
});
I've also tried
$(document).ready(function(){
$(".unit").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".unit").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Try changing
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
with
if($(this).val() != "" && $(this).val() !=0) {
++$num;
}
to be more jQuery style
I guess this is what you want :
// control function
function checkInputs() {
var num = 0;
// foreach inputs
$(".player input").each(function(i,item) {
var value = $(this).val();
if (value.trim() === "0") {
num++;
}
});
if (num === 1 || num > 4) {
$("#myForm input[type='submit']").attr("disabled", "true");
} else {
$("#myForm input[type='submit']").removeAttr("disabled");
}
}
// if you want a first check after loading the page :
checkInputs();
$(".player input").change(
// This function will be called each time an input change in the player div
checkInputs
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myForm">
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
<input type="submit"/>
</form>
I am not sure why are you checking the length? this.value.length!=0
I tweaked your code, here is the fiddle link : http://jsfiddle.net/bLa6evpg/
Hope this help!
I couldn't follow your function, but I believe your problem is that you are running it on page load, and not on the onchange of your input boxes. I achieved the desired functionality by doing that in this codepen
html:
<div class="player">
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number"/>
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
</div>
<button name="submit2">Click</button>
JS:
function validateChanges() {
var playerDiv = document.getElementsByClassName("player")[0];
var inputs = playerDiv.getElementsByTagName("input");
var total = 0;
for(var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if(total == 1 || total > 4) { // IF total is 1 or more then 4
document.getElementsByTagName("button")[0].disabled = true;
} else {
document.getElementsByTagName("button")[0].disabled = false;
}
}
looks like i was almost right just messed up a bit Silent_coder fixed this +i added some tricks i saw here
$(document).ready(function(){
CheckNull();
$(".player input").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".player input").each(function() {
if(this.value != 0 ) {
$num++;
}
});
if (($num > 4) || ($num <= 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Works like i charm for me ^^
Here is a JsFiddle example
$(function () {
$('.unit').on('change', function () {
var units = 0;
$('.unit').each(function (index, value) {
var unit = parseInt($(value).val(),10);
units += unit;
if(units >= 4 || units === 1) {
$('form > button').prop('disabled', true);
} else {
$('form > button').prop('disabled', false);
}
});
});
});

How to show the results when checkbox is selected

Here is my code:
<form id="F2" onsubmit="return false;">
Which do you want?<br />
<input name="a" onclick="TotalCheckedValues()" type="checkbox" value="10" />New (10.00)<br />
<input name="b" onclick="TotalCheckedValues()" type="checkbox" value="0" />Broken (Free)<br />
<input name="c" onclick="TotalCheckedValues()" type="checkbox" value="55" />Antique (55.00)<br />
<input name="d" onclick="TotalCheckedValues()" type="checkbox" value="4.95" />Refurbished (4.95)<br />
Total: <input name="T" readonly="readonly" size="5" type="text" /><br />
<input onclick="TotalCheckedValues()" type="button" value="Click" /> </form>
function TotalCheckedValues() {
var total = 0;
if(document.getElementById("F2").a.checked == true) { total += parseFloat(document.getElementById("F2").a.value); }
if(document.getElementById("F2").b.checked == true) { total += parseFloat(document.getElementById("F2").b.value); }
if(document.getElementById("F2").c.checked == true) { total += parseFloat(document.getElementById("F2").c.value); }
if(document.getElementById("F2").d.checked == true) { total += parseFloat(document.getElementById("F2").d.value); }
var ts = new String(total);
if(ts.indexOf('.') < 0) { ts += '.00'; }
if(ts.indexOf('.') == (ts.length - 2)) { ts += '0'; }
document.getElementById("F2").T.value = ts;
document.getElementById("F3").innerHTML = ts;
}
I want to show the updated result whenever I click and untick the checkbox.
Just add "script" tag in your html before function start which indicate javascripts code.

Categories