How to associate two inputs in JavaScript? - javascript

I have this code:
$(document).ready(function(){
$('.container select').each(function(){
$(this).on('change', function(){
var selectedVal = $(this).val();
//console.log(selectedVal);
});
});
$('input').on('change', function () {
var sum = 0;
$('input').each(function() {
sum += Number($(this).val());
});
$('.total span').html(sum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total'>
Total nr: <span>5(2 A1, 3 A2)</span>
</div>
</div>
Is it possible that on change of the select and the input of type number to modify the total number like in the code above using JavaScript/jQuery?
Can anyone help me with this please.
On every change on the inputs or select fields I need to calculate total number of A1 and total number of A2. Hope this make sense. And display them beside the total number.
JSFiddle

We can't give you the full code but I tried to provide some logic for what you want.I think you want some thing like this:
//create a json to collect the sum of numbers
var number = {
a1: 0,
a2: 0,
a1_count:0,
a2_count:0
};
//check in select change
$(".select").change(function() {
//flush previous calculation before using again
number.a1=0,number.a2=0,number.a1_count=0,number.a2_count=0;
//check all the select value and get the corresponding input value
$(".select").each(function() {
var valueType = $(this).val();
if (valueType == "a1") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
} else if (valueType == "a2") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
}
});
$("#total").html('Total:'+(number.a1+number.a2)+',A1:'+number.a1+'('+number.a1_count+'),A2:'+number.a1+'('+number.a2_count+')');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total' id="total">
</div>
</div>

This will work for any arbitrary list in the select.
function change() {
var res = {}, fulls = $('.container .full');
fulls.each(function(index){
var selected = $(this).find('select > option:selected').text();
if (! res[selected]) res[selected] = 0;
res[selected] += 1*$(this).find('input[type="number"]').val();
});
var detail = "", total = 0;
for(prop in res) {
if (res.hasOwnProperty(prop)) {
try {
var val = 1*res[prop];
detail += ", "+val+" "+prop;
total += val;
}catch(e){}
}
}
$('.total > span').text(""+total+" ("+detail.substr(2)+")");
}
$().add('.container .full input[type="number"]')
.add('.container .full select[name^="select"]')
.on('change', change);

Related

How to make this multidrop form to array

I have a multidrop form at this fiddle : Here's a link! . at this form only can add multidrop 3 times, i want to make always add this multidrop, and how to save the array data into sql
<div id="Yes1">
<label for="name" >Name</label>
<input type="text" id="name1" name="name1">
<br><br>
<label for="multiDrop" >Multi Drop</label>
<select name="multiDrop1" id="multiDrop1">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
Check here to add and remove your elements as per your requirement.
You can remove only that block which you selected No for.
$(document).ready(function() {
$(document).on("change", ".multidrop", function() {
if ($(this).val() == 'Y') {
$clone = $(this).closest(".Yes").clone();
var num = parseInt($(".Yes:last").attr("data-index")) + 1;
$clone.attr("data-index", num);
$clone.attr("id", $clone.attr("id").replace(/\d+/, num));
$clone.find("input,select").each(function() {
var name = ($(this).attr("name")).replace(/\d+/, num);
var id = ($(this).attr("id")).replace(/\d+/, num);
$(this).attr("name", name);
$(this).attr("id", id);
});
$clone.insertAfter(".Yes:last"); //Add field html
} else if ($(this).val() == "N" && $(".Yes").length > 1) {
$(this).closest(".Yes").remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Yes1" class="Yes" data-index="1">
<label for="name">Name</label>
<input type="text" id="name1" name="name1" class="name">
<label for="multiDrop">Multi Drop</label>
<select name="multiDrop1" id="multiDrop1" class="multidrop">
<option value="">Select Option</option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
I would recommend to use following approach:
get your repetitive block HTML into a variable;
listen for changes of drop down (using event delegation, selecting by class rather than id);
modify necessary attributes (names, id's, etc) based on global counter to distinguish those dynamic blocks;
const block = `
<div class="block">
<div class="yes">
<label>Name</label>
<input type="text" class="name"></input>
<label>Multi Drop</label>
<select class="multiDrop">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
</div>
</div>
`;
const addAnotherBlock = () => {
$('#wrapper').append(block);
$('.name:last').attr('name',i++);
};
var i = 0;
$(document).ready(() => addAnotherBlock());
$('#wrapper').on('change', '.multiDrop', function(){
if($(this).val() == 'Y') addAnotherBlock();
else if($(this).val() == 'N' && $('.block').length > 1 && !$(this).closest('.block').is('.block:last')){
$(this).closest('.block').remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper"></div>

How to keep once changed data value on select options?

$('.sela').change(function(){
var obj = $('.sela:visible');
var uname = obj.find(':selected').data('x');
$('#inptest').val(uname);
})
$('#btn').click(function(){
$('.sela:visible').find(':selected').attr('data-x', 999)
var a = $('.sela:visible').find(':selected').attr('data-x')
$('#inptest').val(a);
});
#btn{
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='sela'>
<option value='lorem1' data-x='left'>ADMIN</option>
<option value='lorem2' data-x='right'>AUTHS</option>
</select>
<br><br>
<select class='sela'>
<option value='lorem3' data-x='up'>SKY</option>
<option value='lorem4' data-x='down'>EARTH</option>
</select>
<br><br>
<input type='text' id='inptest'value='323'>
<br><br>
<div id='btn'>BUTTON</div>
Change first sela to AUTHS.
inptest becomes right
Click on btn - sela selected option data-x is 999 and inptest is 999
Now change sela back to ADMIN and again to AUTH.
I'm expecting it to keep 999 but it becomes right.
How to keep once changed data value on sela options?
Be consistent,
either use .attr('data-x')/.attr('data-x', newValue) or use .data('x')/.data('x',newValue)
So
$('.sela').change(function() {
var obj = $('.sela:visible');
var uname = obj.find(':selected').data('x');
$('#inptest').val(uname);
})
$('#btn').click(function() {
$('.sela:visible').find(':selected').data('x', 999)
var a = $('.sela:visible').find(':selected').data('x')
$('#inptest').val(a);
});
#btn {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='sela'>
<option value='lorem1' data-x='left'>ADMIN</option>
<option value='lorem2' data-x='right'>AUTHS</option>
</select>
<br><br>
<select class='sela'>
<option value='lorem3' data-x='up'>SKY</option>
<option value='lorem4' data-x='down'>EARTH</option>
</select>
<br><br>
<input type='text' id='inptest' value='323'>
<br><br>
<div id='btn'>BUTTON</div>
Or
$('.sela').change(function(){
var obj = $('.sela:visible');
var uname = obj.find(':selected').attr('data-x');
$('#inptest').val(uname);
})
$('#btn').click(function(){
$('.sela:visible').find(':selected').attr('data-x', 999)
var a = $('.sela:visible').find(':selected').attr('data-x')
$('#inptest').val(a);
});
#btn{
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='sela'>
<option value='lorem1' data-x='left'>ADMIN</option>
<option value='lorem2' data-x='right'>AUTHS</option>
</select>
<br><br>
<select class='sela'>
<option value='lorem3' data-x='up'>SKY</option>
<option value='lorem4' data-x='down'>EARTH</option>
</select>
<br><br>
<input type='text' id='inptest'value='323'>
<br><br>
<div id='btn'>BUTTON</div>

finding some based on checkbox and select

i am trying to find SUM of some number based on check box and select option .
here is my code
<div class="container">
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label>
<input type="checkbox" value="10">10
</label>
</div>
<input id="total" placeholder="total" />
And my script is
function updateTotal(){
var total = 0;
$(".container input[type='checkbox']").each(function(){
if($(this).is(":checked")){
var multiplier = Number($(this).parent().prev().val());
var checkboxAmount = Number($(this).val());
total += multiplier * checkboxAmount;
}
});
$("#total").val(total);
}
$("select, input[type='checkbox']").on("change", updateTotal);
The above script is just working fine give html code . But when keep my checkbox first and select option next , then this script will not give any output
i wanted my HTML code like this , then script should be work fine for this
<div class="container">
<label>
<input type="checkbox" value="10">10
</label>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<input id="total" placeholder="total" />
any help , code coppied from here
Try this one-
function updateTotal() {
var total = 0;
$(".container").each(function () {
var checkbox = $(this).find("input[type='checkbox']");
var select = $(this).find("select");
if (checkbox.is(":checked")) {
total += Number($(this).find("input[type='checkbox']").val()) * Number(select.val());
}
});
}

Draw 'N' inputs depending value from select

I'm trying to draw an specific number of inputs, this number depends of the value from select input, the problem here is that the selected option is determinated by the value from another number input, in other words if I type 3 on my numeric input, the selected option of my select input should be 3, as a result of this my function should draw 3 inputs. Maybe I'm not much clear but here is my code and what I tried:
$(document).ready(function() {
$('#Controls').on('blur', '#InputNumbers', function() {
selectValue();
});
});
function selectValue() {
var inputVal = $('#InputNumbers').val();
$('#MyInputs').val(inputVal);
$('#MyInputs').change(function() {
draw();
});
}
function draw() {
alert("Hi");
var total = $('#MyInputs').val();
var html = "";
for (var i = 0; i < total; i++) {
html += '<input />';
}
$('#draw').html(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Controls">
<input type="number" placeholder="Number of inputs" id="InputNumbers" />
<select id="MyInputs" disabled>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="draw">
</div>
</div>
As you can see first 2 steps works fine, the problem is when I tried to do this:
$('#MyInputs').change(function() {
draw();
});
The function is not executed, how can I solve this?
Please refer below code, how its working, You don't need change event
$(document).ready(function() {
$('#Controls').on('blur', '#InputNumbers', function() {
selectValue();
});
});
function selectValue() {
var inputVal = $('#InputNumbers').val();
$('#MyInputs').val(inputVal);
draw();
}
function draw() {
alert("Hi");
var total = $('#MyInputs').val();
alert(total)
var html = "";
for (var i = 0; i < total; i++) {
html += '<input />';
}
$('#draw').html(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Controls">
<input type="number" placeholder="Number of inputs" id="InputNumbers" />
<select id="MyInputs" disabled>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="draw">
</div>
</div>
You need to bind the change event to the input,your select is disabled:
$(document).ready(function() {
$('#Controls').on('blur', '#InputNumbers', function() {
selectValue();
});
});
function selectValue() {
var inputVal = $('#InputNumbers').val();
$('#MyInputs').val(inputVal);
}
$('#InputNumbers').change(function() {
draw();
});
function draw() {
$('#draw').empty();
var total = parseInt($('#InputNumbers').val());
for (var i = 0; i < total; i++) {
$('#draw').append('<input />');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Controls">
<input type="number" placeholder="Number of inputs" id="InputNumbers" />
<select id="MyInputs" disabled>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="draw">
</div>
</div>

calculations on multiple selects dropdown

I am trying calculate the amount on change of select dropdown. I need each row calculation front of that row i.e. subtotal and all subtotal will be at bottom at "Total Amount"
I am getting the calculations for first row, but there is issues somewhere, i cannot findout properly. Please help me.
My code is
jQuery(document).ready(function() {
var bookIndex = 1;
jQuery('#orderform')
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = jQuery('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.addClass('form-group')
.removeAttr('id')
.removeAttr('style')
.attr('id', "row"+bookIndex)
.attr('data-index', bookIndex)
.insertBefore($template);
jQuery("#row"+bookIndex+' .addprice span').addClass('item_price');
jQuery("#row"+bookIndex+' .addprice input').addClass('itemprice');
jQuery("#row"+bookIndex+' > div ').removeClass('addprice');
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = jQuery(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
// Remove element containing the fields
$row.remove();
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
});
jQuery(document).ready(function(){
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
jQuery(".dynamic-fields").each(function() {
var tpy = parseInt(jQuery(".service_type option:selected").val());
var clths = parseInt( jQuery(".cloths option:selected").val() );
var quantity = parseInt( jQuery(".quantity option:selected").val() );
var total;
total= tpy + clths * quantity;
jQuery("span.item_price").html(total);
jQuery("input.itemprice").attr('value', total);
});
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
var total = 0;
var id = jQuery(this).parent().parent().attr('id');
var index = jQuery(this).parent().parent().attr('data-index');
id = '#'+id+' '; //alert(id); //alert(index);
//jQuery('.form-group').each(function () {
var tpy = jQuery(id+'.service_type option:selected').val();
var clths = jQuery(id+'.cloths option:selected').val();
var quantity = jQuery(id+'.quantity option:selected').val();
total= ( parseInt(tpy) + parseInt(clths) ) * parseInt(quantity);
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
//});
var totalamount = 0;
var price =0;
jQuery('.accept-checkbox.dynamic-fields > div.form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form name="neworder" action="<?php the_permalink(); ?>" method="post" id="orderform">
<div class="accept-checkbox dynamic-fields">
<div class="form-group" id="row1" data-index="1">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2">
<span class="item_price">30</span>
<input type="hidden" class="itemprice" value="00"/>
</div>
<div class="col-sm-1">
<button class="btn btn-default addButton" type="button"><i class="fa fa-plus">+</i></button>
</div>
</div>
<!-- The template for adding new field -->
<div id="bookTemplate" class=" hide" style="display: none;">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2 addprice">
<span >30</span>
<input type="hidden" value="00"/>
</div>
<div class="col-xs-1">
<button class="btn btn-default removeButton" type="button"><i class="fa fa-minus"> - </i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-5 pull-right">
<span><strong>Total Amount : </strong></span><span id="totalamount"> <span>00.00</span>/- </span>
</div>
</div>
</form>
The added elements do not have an event handler.
To write one event handler for current and future elements, replace this:
jQuery('.dynamic-fields > div.form-group select').on("change", function () {
With:
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
Note that you still have many issues with your code. You should better keep your quantities, prices, etc.. (also) in variables, and not re-read them every time from html attributes.
For instance these lines are now wrong:
jQuery(".item_price").html(total);
jQuery("input.itemprice").attr('value', total);
You intended this:
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
... and there are more issues like that, but if I were you, I would refactor this code to rely less on the html attributes for calculating the total.
change the line
jQuery('.dynamic-fields > div.form-group select').on("change", function() { ...
to
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() { ...
because the EventListener change is bind once to the elements that are at the time in DOM the code is executed with selector .dynamic-fields > div.form-group select.
Now the EventListener is set to the document und the function is executed when event.target is .dynamic-fields > div.form-group select.

Categories