Please take a look at this http://jsfiddle.net/F2wEK/4/:
HTML
cost 1 :<input type="text" class="cost" name="cost1" /><br />
cost 2 :<input type="text" class="cost" name="cost2" /><br />
cost 3 :<input type="text" class="cost" name="cost3" /><br />
cost 4 :<input type="text" class="cost" name="cost4" /><br /><br />
sum : <input type="text" id="sum" readonly />
Javascript
$(document).ready(function(){
$(".cost").each(
function(){
$(this).keyup(
function(){
calculateSum()
});
});
});
function calculateSum(){
var sum=0;
$(".cost").each(
function(){
var vl = this.value.replace(',','');
if(!isNaN(vl) && vl.length!=0){
sum+=parseFloat(vl);
}
});
$("#sum").val(sum.toFixed(2));
}
$(document).ready(function(){
$('input.cost').keyup(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
Why it can not be auto sum if i enter 100000, 1000000, 10000000, more bigger...? How to make it work with thousand, million or billion number? Please help me guys..
The Problem is your replace function, it only replaces the first ',' not all. In your calculateSum() function you do this:
var vl = this.value.replace(',', '');
I would propose to
var vl = this.value.split(',').join('');
instead. Or use a RegExp for the ',' like here:
var myExp = /,/g;
var vl = this.value.replace(myExp, '');
Try the fiddle it works fine for me.
Change your replace function. It replaces only first occurrence of comma:
var vl = this.value.replace(/,/g, '');
Related
I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.
You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.
This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.
I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL
Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}
<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation
I have this textbox:
<td width="10%"><input name="date" type="text" size=11 maxlength=10 /></td>
when typing date in the field it must add a forward slash in it like 09/02/2016
You can do the same functionality in PHP using JS OR jQuery.
Replace
<input name="date" type="text" size=11 maxlength=10 />
To
<!-- SET type="date" -->
<input type="date" name="date">
jQuery Code:-
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="date"]');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5){
var thisVal = $jqDate.val();
thisVal += '/';
$jqDate.val(thisVal);
}
}
});
Hope it will help you :)
This one was very ticky! This is how I got it working, though it's not complete as you will need to check for when a number is deleted
<input type="hidden" id='counter' value='0'>
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="doDate()"/>
<script>
function doDate(){
var dateSoFar = document.getElementById("date");
var counter = parseInt(document.getElementById("counter").value);
counter = counter+1;
document.getElementById("counter").value = counter;
if(counter == 3 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>
Try this,
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="updateDate()"/>
<script>
function updateDate(){
var dateSoFar = document.getElementById("date");
var counter = dateSoFar.value.length;
if(counter == 2 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>
I am trying to make a function using jquery where i want to get the total number of input in a page with attibute value defined by me . For eg there are four input tags
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="200" total_quantity="3" name="product1" value="book" class="product-200">
In the above tags i want to pre define barcode number in a variable and the count the number of inputs accordingly and also get the value of total_quantity in a variable for that barcode number i provide. I made the following code to get the total inputs but its for all input and is not according to barcode i will specify .
var barcode_pd = $('input[barcode]').size();
var total_pd = $('input.code').attr("total_quantity");
var sumOfVals = 0;
$(".mn-no-cnt").each(function(){sumOfVals = sumOfVals + parseInt($(this).val(), 10);});
Using above code the ouput for count of input is 4 and i want to specify the barcode number too such as 567 so that the count could be 3 or if i use barcode number 200 then the count is 1.
I have used array to store values.
var code = [];
var count = [];
$("input.code").each(function(){
var c = $(this).attr("barcode");
if(code.indexOf(c) >= 0){
count[code.indexOf(c)] += 1;
}
else{
code.push(c);
count.push(1);
}
});
for(var i=0;i<code.length;i++){
$("body").append("<p>Barcode:"+code[i]+" Count:"+count[i]+"</p>");
}
DEMO here.
Without using jQuery:
function getCount(barcode){
var code = document.getElementsByClassName('code') ;
var length = code.length ;
var count = 0 ;
for(var i = 0 ; i < length ; i++){
if(code[i].attributes['barcode'].value == barcode) count++ ;
}
return count ;
}
// Test
alert(getCount(567)) ; // 3
alert(getCount(200)) ; // 1
Demo : http://jsfiddle.net/wz98E/
http://jsfiddle.net/A95Js/
function countBarcode(numberToFind){
var countInputs = 0;
$('input[barcode]').each(function(){
if($(this).attr("barcode") == numberToFind){
countInputs ++;
}
return countInputs;
});
}
$('#answer').html(countBarcode(567));
This is purely to count them - but combined with Hirals answer you should be able to work out how to turn his into a function. JSfiddle is above - obviously to make this useful you need to return the value not add it to a div - was just showing how to count it.
Try this. Set the barcode variable to the barcode you want to search for. I have also converted to data- attributes and have provided code to count and sum the data-total_quantity:
HTML:
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10105">
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10106">
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10107">
<input type="hidden" class="code" data-barcode="200" data-total_quantity="3" name="product1" value="book" class="product-200">
Javascript:
$(function () {
var barcode = 567; // set to whatever you want to search for...
var sumOfVals = 0;
$("input.code[data-barcode='" + barcode + "']").each(function () {
sumOfVals += parseInt($(this).data('total_quantity'), 10);
});
alert("Length: " + $("input.code[data-barcode='" + barcode + "']").length);
alert("Sum: " + sumOfVals);
});
Fiddle:
http://jsfiddle.net/d89BR/4/
Try this :
var barcode = 123;
var $123 = $('input[data-barcode="' + barcode + '"]');
var howMany = $123.length;
var sumOfQuantities = Function('return ' + $123.map(function () {
return $(this).data('quantity');
}).get().join('+') + ';')();
var sumOfValues = Function('return ' + $123.map(function () {
return $(this).val() || '0';
}).get().join('+') + ';')();
HTML (example) :
<input data-barcode="123" data-quantity="123" value="123" />
I need some help with javascript or jQuery.
I have three (3) input fields that I want to filter (sum of three fields).
the total value of 3 input fields is must 100. If the user fills more than 100, it will be automatically change the value that the total is 100.
you can see this example
<input type="text" name="text1" size="3"> text1<br />
<input type="text" name="text2" size="3"> text2<br />
<input type="text" name="text3" size="3"> text3<br />
<p>The maximum value of total 3 fields above is 100.</p>
<pre>example 1 :
text1 : 20;
text2 : 30;
text3 : 50; (will automatically filled with 50 because the total value must 100)</pre>
<pre>example 2 :
text1 : 37;
text2 : 60;
text3 : 3; (will automatically filled with 3 because the total value must 100)</pre>
Thanks for helping me,
I need it :)
$("input:lt(2)").on("change", function() {
var other = $("input:lt(2)").not(this).val();
if (other.length)
$("input:eq(2)").val(100 - this.value - other);
});
DEMO: http://jsfiddle.net/D5F3p/3/
This is the simplest thing I can think of!
$(document).ready(function(){
$('input[name="text2"]').blur(function(){
$('input[name="text3"]').val(100 - $('input[name="text1"]').val() - $('input[name="text2"]').val());
});
});
IMO, you can do these:
Give only two characters for both the inputs. Don't allow more than that!
You also need to check if the sum of the two inputs should not exceed 101!
Keep the input 2 readonly, until something has been entered in input 1.
Keep the input 3 always readonly.
Fiddle: http://jsfiddle.net/praveenscience/D5F3p/5/
<head>
<script type="text/javascript">
function check() {
var sum = 0;
var inputs = $(".test");
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == parseInt(inputs[i].value)) {
sum += parseInt(inputs[i].value);
if (sum > 100) {
sum -= parseInt(inputs[i].value);
inputs[i].value = 100-sum;
}
}
}
}
</script>
</head>
<body>
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
$(function(){
$('input[name="text1"]').keyup(function(){
var text1Value = $('input[name="text1"]').val();
if(text1Value >=100)
{
$('input[name="text1"]').val(100);
$('input[name="text2"]').val('');
$('input[name="text3"]').val('');
$('input[name="text2"]').attr('disabled','disabled');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text2"]').removeAttr('disabled');
$('input[name="text3"]').removeAttr('disabled');
}
});
$('input[name="text2"]').keyup(function(){
var text1Value = parseInt($('input[name="text1"]').val());
var text2Value = parseInt($('input[name="text2"]').val());
if(isNaN(text1Value))
{
text1Value =0;
}
if(isNaN(text2Value))
{
text2Value =0;
}
var total = text1Value + text2Value;
if(total >=100)
{
$('input[name="text2"]').val(100-text1Value);
$('input[name="text3"]').val('');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text3"]').removeAttr('disabled');
$('input[name="text3"]').val(100-total);
}
});
});
I am checking if sum of all text boxes if exceeding 100, then making correction in the last entered textbox with disabling the next textbox.
I'm using the following code to take the value of one field, subtract it from the value of another field and display the result.
$(document).ready(function() {
var numIn;
var numOut;
var total;
$('#submit').click(function() {
numIn = $('input.in').val();
numOut = $('input.out').val();
total = numIn-numOut;
$('span').remove();
$('body').append('<span>£'+total+'</span>');
$('span').fadeIn(250);
});
});
I want to create a sort of income/expenditure calculator. so my question is, say I had multiple income fields and multiple expenditure fields how would I take the total value from the income fields away from the total value of the expenditure fields.
Here is an example form in case I haven't been clear.
<form>
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="in" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input class="out" type="text">
<input type="submit" id="submit" value="Submit">
You could loop over the .in and .out fields, and add their values as you go.
Example: http://jsfiddle.net/tXPeg/3/
var numIn = 0;
var numOut = 0;
var total;
$('#submit').click(function() {
$('input.in').each(function() {
return numIn += (parseFloat(this.value) || 0);
});
$('input.out').map(function() {
return numOut += (parseFloat(this.value) || 0);
});
total = numIn - numOut;
$('span').remove();
$('body').append('<span>£' + total + '</span>');
$('span').fadeIn(250);
return false;
});
EDIT: Changed to use parseFloat() instead of parseInt().
Actually after testing a little further the only problem is that if one or more fields are empy it returns 'NaN'.
I tried adding conditional statements to check that the field had a value but no luck:
Feel free to edit my example: http://jsfiddle.net/QaEcD/3/
$('#submit').click(function() {
var numIn = 0;
var numOut = 0;
var total = 0;
$('input.in').each(function() {
if($(this).val().length !== 0){
return numIn = numIn + parseInt(this.value);
});
});
$('input.out').map(function() {
if($(this).val().length !== 0){
return numOut = numOut + parseInt(this.value);
});
});
total = numIn-numOut;
$('span').remove();
$('body').append('<span>£'+total+'</span>');
$('span').fadeIn(250);
return false;
});
});