I have multiple input fields and I want to apply key up JavaScript event on some of input field. Basically, I want to do some expense calculation and I want to get total expenses and set final expense amount in input field to display. So, I tried to apply keyup on multiple input field but did not work.
$('#tripfuel','#cardfee','#loadrepair','#shoprepair','#truckrent','#comcheck','#advance','#othercharge').on('keyup', function () {
var fuel = document.getElementById('tripfuel').value;
var cardfee = document.getElementById('cardfee').value;
var onloadrepair = document.getElementById('loadrepair').value;
var shoprepair = document.getElementById('shoprepair').value;
var trailerrent = document.getElementById('truckrent').value;
var comcheck = document.getElementById('comcheck').value;
var advance = document.getElementById('advance').value;
var miscellenous = document.getElementById('othercharge').value;
var expense = parseFloat(amount)-parseFloat(fuel)-parseFloat(cardfee)-parseFloat(onloadrepair)-parseFloat(shoprepair)-parseFloat(trailerrent)-parseFloat(comcheck)-parseFloat(advance)-parseFloat(miscellenous);
console.log("Total Expense : || "+expense);
document.getElementById('totalamount').value = parseFloat(expense).toFixed(2);
});
apply the class of all of your expenses input like
<input type="text" class="expenses" />
then get the total value like this.
$('.expenses').on('keyup', function () {
let totalExpense = 0;
$(document).find("input.expenses").each(function(){
totalExpense += parseFloat($(this).val())
})
});
Related
I would like that a JavaScript function could take a random sentence from a datalist in the same file, and then show it when I click on a button with an "onclick" event. I am looking for the easiest way to do that. Does anyone have an example?
(Just looking around, trying JavaScript for the first time)
let dataList =["sentence 1","sentence 2","sentence 3","sentence 4"]
let div = document.getElementById('asd')
document.getElementsByTagName("button")[0].addEventListener("click",myFunc)
function myFunc(){
let x = parseInt(Math.random()* dataList.length )
div.innerHTML = dataList[x]
}
<button>click me</button>
<div id='asd'></div>
This is easy using the function parseInt() and Math.random()*n:
var yourDataList = ["Option 1", "Option 2", "Option 3"]; // Define datalist
var myBtn = document.getElementById("yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Decclre random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist
return yourDataList[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
alert(getRandom()); //Do whatever you want to with the random value
});
<button id = "yourIdHere">Click me!!</button>
EDIT:
Using the DOM HTML element <datalist> as your input, this is some working code:
var yourDataList = document.getElementById("datalist"); // Define datalist
var myInput = document.getElementById("myInput");
var dataListOptionsElems = yourDataList.querySelectorAll("option");//Get all options elements
var dataListOptions = [];//Declare options
for(var i = 0;i<dataListOptionsElems.length;i++){
dataListOptions.push(dataListOptionsElems[i].value);
}
var myBtn = document.getElementById("yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Declare random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * dataListOptions.length); //Get random number between 0 and the length of your datalist
return dataListOptions[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
alert(getRandom());
console.log(getRandom());
myInput.value = getRandom();
//Do whatever you want to with the random value
});
<button id = "yourIdHere">Click me!!</button>
<input list="datalist" id="myInput">
<datalist id="datalist">
<option value="Option1">
<option value="Option2">
<option value="Option3">
<option value="Option4">
<option value="Option5">
</datalist>
<p>Note: the alert box, console message, and input value will not be the same, due to it being random each time the function is called.</p>
Working JSFiddle
I am trying to do one task using javascript, i have two text boxes one is for total amount and second is for discount and i have value in total amount for example 100 and when i insert discount in discount text box that inserted discount must be subtract from total amount but when i remove that discount that value must be as previous i tried below but it substract value but when it removes discount it does not work please help. Thanks in advance.
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount.length>0) {
var total=gross-totalDiscount;
} else{
var total=gross;
}
$('input[name="total_gross_amount"]').val(total);
});
Try this one.
As #Chris G proposed in comments and I edited his fiddle(just an example how this could be done, but since the questioner did not provide all info, this is what we have done):
$(".form-basic input").on('input', function() {
var gross = $('input[name="total_gross_amount"]').val();
var totalDiscount = $('.grand-discount').val();
var total = gross - totalDiscount;
$('#total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-basic">
<input type="number" class="total_gross_amount" name="total_gross_amount">
<input type="number" class="grand-discount" name="grand-discount">
</form>
<p>Total: <span id="total"></span></p>
I think this solve your problem, the key is to take gross out of input event:
$(document).ready(function(){
var gross= $('input[name="total_gross_amount"]').val();
$(".form-basic .grand-discount").on('keyup', function () {
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
});
ful example here https://jsfiddle.net/wkj0jjvp/
if you want to update gross amount, you should set an event for gross and put inside the discount event.
I need to calculate the tax of total amount during onchange of quantity or price values.
Here is what I did:
function sum() {
var result1 = document.getElementById('result1').value;
var result2 = document.getElementById('result2').value;
var result3 = document.getElementById('result3').value;
var result4 = document.getElementById('result4').value;
var result5 = document.getElementById('result5').value;
var result6 = document.getElementById('result6').value;
var myResult = Number(result1) + Number(result2) + Number(result3) + Number(result4) + Number(result5) + Number(result6);
tax(myResult);
document.getElementById('sumvalue').value = myResult;
}
Here result1,2,3.. are sub total of items. Total amount is passed to the tax calculation.
function tax(tot) {
var taxval = document.getElementById('tax_val').value;
amt = (tot * taxval)/100 ;
document.getElementById('tax_amt').value = amt;
}
tax_amt is the Tax Amount final value. My requirement is: when I change the tax value, I need to run this same method.
Below element is the tax percentage holder. Whenever I change the value it must be frequently change the tax_total.
<input id="tax_val" type="number" value="15" oninput="tax(this_element_value)" >
In your case, I understand that you want realtime update of tax, when input is changed.
I would do something like this:
<input id="tax_val" type="number" value="15" oninput="onInputChanged(this)" >
function onInputChanged(elem) {
tax(elem.value);
}
First you can assign a class to all the elements variables (result1, result2, result3...) then add a event to this class like this:
$(".result").change(function () {
sum();
});
<div>
<input class="input-class" />
<input class="input-class" />
</div>
<script>
$('.input-class').on('change', function () {
/// here you need find input and there value then you can sum of these value.
});
</script>
check this. I think it helps you.
I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery
when user select any option in radio buttons in group one and then enter any number in respective input field and then select the next any radio option and enter any value in input field then this time it should add the new result with old one and display it in result input field and now if he empty any input field then that should also minus from the total result and display it in result field.
i have so many groups like that but here i just put two of them to get the result.
here id the FIDDLE
here is the jquery code. i can work in jquery but not very good i used separate code for every group and i know there must be a way to get this whole functionality through generic code but again i am not good at jquery
jQuery("#txt_im").keyup(setValue);
jQuery('[name="rdbtn-im"]').change(setValue);
function setValue() {
var txt_value = jQuery("#txt_im").val();
var rad_val = jQuery('[name="rdbtn-im"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res = txt_value * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
var final2 = 0;
jQuery("#txt_fb").keyup(setValue2);
jQuery('[name="rdbtn-fb"]').change(setValue2);
function setValue2() {
var txt_value = jQuery("#txt_fb").val();
var rad_val = jQuery('[name="rdbtn-fb"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res2 = txt_value * rad_val;
final2 = parseInt(res2, 10) + final;
var MBresult = final2 / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
infact user is free to select any number of groups or also free to remove any number of group after selection.
i know there is error in fiddle when user select 2nd group after the select of first it removes the result which is wron and i tried to solve it but failed but i define the whole seen what i need to do. i will be very thankfull to you for this kind favour.
HTML:
<table>
<tr>
<td>
<input type="radio" name="rdbtn-im" id="rdbtn-im-day" value="25" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-im" id="rdbtn-im-week" value="175" class="rdbtn-style-social" />Weekly
<input type="text" name="txb3" id="txt_im" class="txt-email" style="width:100px;margin: 2px;" />
</td>
</tr>
<tr>
<td class="sec-td-rdbtns-social">
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-day" value="3500" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-week" value="500" class="rdbtn-style-social" />Weekly
<input type="text" name="txb1" id="txt_fb" class="txt-email" style="width:100px;margin: 2px;" /> </td>
</tr>
</table>
<br>result
<input type="text" name="final_res" id="final_res" class="" style="width:100px;margin: 2px;" />
Jquery:
jQuery(".txt-email").keyup(setValue);
jQuery('.rdbtn-style-social').change(setValue);
function setValue() {
var total = 0;
$(".rdbtn-style-social:checked").each(function () {
var myInput = $(this).siblings(".txt-email").val();
if (myInput.length) {
total += myInput * $(this).val();
}
});
if (total) {
jQuery('#final_res').val((total / 1024).toFixed(2));
} else {
jQuery('#final_res').val('');
}
}
FIDDLE
If you are using chrome, then console is your best friend ( https://developers.google.com/chrome-developer-tools/docs/console )
For firefox you have firebug, opera has dragonfly (or something like that ?). Even IE has console now. There you can see all errors popping up.
Ok, so first of all let's clean up this a little bit by wrapping it all in closure (we can now safely use the $ instead of jQuery even if there is namespace conflict outside). Also, we will use single function for both cases, because they are so similar.
!function ($) {
$(".txt-email").keyup(setValue);
$('.rdbtn-style-social').change(function(e) { setValue(e, true) });
function setValue(e, radio) {
if('undefined' === typeof radio) radio = false;
var attr = radio ? 'name' : 'id';
var tmp = e.target[attr].split('-');
var media = tmp[tmp.length - 1];
var txt_value = $("#txt-"+media).val();
var rad_val = $('.rdbtn-style-social[name="rdbtn-'+media+'"]:checked').val();
if (!txt_value.length || !rad_val.length) {
$('#final_res').val('');
return false;
}
var res = (txt_value | 0) * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
$('#final_res').val(MBresult.toFixed(2));
}
}(jQuery);
(variable | 0 is same as parseInt(variable, 10)).
So, long story short: when radio or text gets changed, the function is fired (if it's radio, additional argument is passed). We retrieve whether we want to work on im or fb, then do whatever you want. I changed id of inputs to replace _ with -'s (for split consistency)
Final jsfiddle: http://jsfiddle.net/Misiur/f6cxA/1/