Counter char script for many fields - javascript

Hi I want use this script to count char in form with many fields,
but not want duplicate code, I want use only one code for all fields,
how can pass to javascript name fields count and display this count...
As one counter for many fields input type...
thanks
Salvatore
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('#charNum').text(65 - len);
}
};
</script>
<div id="charNum"></div>
<input type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />

the problem is that you are using ids several times. Try to work with classes and generate the selectors from the class name of the element.
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('.' + val.className + '_charNum').text(65 - len);
}
};
</script>
<div class="name_var1_charNum"></div>
<input class="name_var1" type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var2_charNum"></div>
<input class="name_var2" type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var3_charNum"></div>
<input class="name_var3" type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />

As far as I understood you do need to display characters left value for each field (depending on max-length) and restrict user from adding extra characters (more than allowed limit). Probably that's what you need.
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any" class="countable" max-length="66" />
</div>
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any2" class="countable" max-length="66" />
</div>
<script>
(function($){
var restrictMaxLength = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
if (currentLength >= maxLength) {
return false;
}
},
displayCountCharacters = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
$(this).closest('.countable-item')
.find('.char-num')
.text(maxLength - currentLength);
};
$(document)
.on('keypress', '.countable', restrictMaxLength)
.on('keyup', '.countable', displayCountCharacters);
})(jQuery);
</script>

Related

getting values to populate a text instead of the span

I have pieced together a script that adds the values in text boxes and displays the sums in a span. I have tried a ton of things, but I can not get it to display the sums in a input textbox. Here is a fiddle that I have been working in ..
http://jsfiddle.net/elevationprint/MaK2k/17/
Basically I want to change the spans to input text boxes. If anyone can take a look and let me know what I am missing, I would appreciate it!
The code is this
HTML
Red<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br>
Blue<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br><br>
Total = <span class="qty12lable"></span> x $.95<br>
Total = <span class="qty24lable"></span> x $1.40<br>
SCRIPT
$('.qty12').keyup(function(){
var qty12Sum=0;
$('.qty12').each(function(){
if (this.value != "")
qty12Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty12lable").text(qty12Sum);
//console.log(amountSum); });
$('.qty24').keyup(function(){
var qty24Sum=0;
$('.qty24').each(function(){
if (this.value != "")
qty24Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty24lable").text(qty24Sum);
//console.log(amountSum); });
You can target the input fields like so:
Total = <input class="qty12lable" value=""> x $.95<br>
Total = <input class="qty24lable" value=""> x $1.40<br>
$("input.qty12lable").val(qty12Sum);
$("input.qty24lable").val(qty24Sum);
To set the text (value) of a textbox you have to use .val() not .text(). Like this:
$('.qty12').keyup(function() {
var qty12Sum = 0;
$('.qty12').each(function() {
if (this.value != "")
qty12Sum += parseInt(this.value);
});
$(".qty12lable").val(qty12Sum);
});
$('.qty24').keyup(function() {
var qty24Sum = 0;
$('.qty24').each(function() {
if (this.value != "")
qty24Sum += parseInt(this.value);
});
$(".qty24lable").val(qty24Sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Red
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>Blue
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>
<br>Total = <input class="qty12lable"/> x $.95
<br>Total = <input class="qty24lable"/> x $1.40
<br>
This snippet has some logic about how you can attach event listeners on input fields and how you can get their values. It's not perfect and has quite a few bugs from production level perspective but this will give a hint about how you can listen and manipulate DOM using Jquery. Which is what Jquery is all about.
$( "input" )
.change(function () {
var prevVal = ($('#total').html() !== '') ? $('#total').html() : 0;
if(parseInt($(this).val()) === NaN) {
return;
}
$('#total').html(parseInt($(this).val()) + parseInt(prevVal));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="1"></input><br>
<input type="text" id="2"></input><br>
<hr>
Total = <span id="total" class="qty12lable"></span> <br>

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

Why this function not work on IE 7 , 8?

How to apply for work on IE7 , 8
for test, fill 1 into input and then press button , input will change border to red and return false.
But ie7 8 not work all.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
<div>
<p>
<label>
<input type="text" class="price" size="20" name="price[]">
</label>
</p>
</div>
<div>
<p>
<label>
<input type="text" class="price" size="20" name="price[]">
</label>
</p>
</div>
<div>
<p>
<label>
<input type="text" class="price" size="20" name="price[]">
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var list = document.querySelectorAll(".price");
var z;
var input;
var isValid = true;
var value;
// Loop through the list
for (z = 0; z < list.length; ++z) {
console.log("z = " + z);
// Get this input
input = list[z];
// Check its value
if (input.value != "" && parseInt(input.value, 10) < 1.5) {
input.style.border = "1px solid red";
isValid = false;
}
else {
input.style.border = "1px solid #d5d5c5";
}
}
// Return result
return isValid;
}
</script>
querySelectorAll is an HTML5 DOM API, IE7, 8 are not ready for it.
See this page for more info.
Alternatively, since you are using jquery, you can use $(".price") instead.

JQuery to add (math) up values of inputs

I have an html form, and I want to only show the last section of the form if the value of all the other inputs is <= 500. Here is some simple html, mine is slightly more complicated, but it should be the same idea:
<div id="addSection">
<input type="text" id="retire" />
<input type="text" id="child" />
<input type="text" id="military" />
<input type="text" id="nurse" />
<input type="text" id="other" />
</div>
<div id="random" class="hidden">
<input type="text">
</div>
And here my jQuery that doesn't get close to working :)
$('#addSection :input').keyup(function(){
$('#addSection').each(function(){
var totalAmt = 0;
$(this).find('input').each(function(i,n){
totalAmt += parseInt($(n).val(), 10)
});
});
});
//if totalAmt <= 500 then $('#random').show();
Any ideas on how to get it to add as the user goes through the form? Thanks for the help, if you ahve any questions, I will answer quickly.
I'd suggest (on reviewing and subsequently rewriting my previous attempt):
$('#addSection').on('keyup', function(){
var total = $(this).children().map(function(){
return parseInt(this.value,10) || 0;
}).get().reduce(
function(a, b){
return parseInt(a,10) + parseInt(b,10);
});
$('#random').toggle(total <= 500);
}).trigger('keyup');
JS Fiddle demo.
References:
Plain JavaScript:
Array.prototype.reduce().
parseInt().
jQuery:
children().
get().
on().
toggle().
This should do the trick:
$('#addSection :input').keyup(function(){
var totalAmt = 0
$('#addSection :input').each(function(){
totalAmt += parseInt($(this).val(), 10) || 0
});
$('#random').toggle(totalAmt <= 500);
});
Live example: http://jsfiddle.net/ZL3q4/2/
Try this:
<div id="addSection">
<input type="text" id="retire" />
<input type="text" id="child" />
<input type="text" id="military" />
<input type="text" id="nurse" />
<input type="text" id="other" />
</div>
<div id="random" style="display: none;">
<input type="text">
</div>
$('#addSection :input').keyup(function () {
var totalAmt = 0;
$('#addSection :input').each(function (i, n) {
if (parseInt($(n).val(), 10)) totalAmt += parseInt($(n).val(), 10);
});
if (totalAmt > 500) $("#random").show();
else $("#random").hide();
});

validate a text field with only 5 value

<label class="user-reg-label fl">Percentage:<span class="required">*</span></label>
<input class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" maxlength="5" />
this is my html code.
i need to validate this input field with javascript to enter only 5 values like 99.99
This is formatting, not validating, but it seems to be what the OP is really looking for ( I think ).
var input = document.getElementById("Percentage1"),
onlyNumbers = input.value.replace(/\D/g,""), // Remove all nondigits
cleanNumbers = onlyNumbers.substr( 0, 4 ); // Limit to four digits
// Add decimal if more than two digits in length
if( cleanNumbers.length > 2 )
{
cleanNumbers = cleanNumbers.substr( 0, 2 ) + "." + cleanNumbers.substr( 2 );
}
input.value = cleanNumbers;
Using Jquery something like the below works.
Textbox
<input class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" onpaste="return false"
onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" maxlength="6" />
Jquery
$(document).ready(function ()
{
$('#Percentage1').keyup(function (event)
{
var currentValue = $(this).val();
var length = currentValue.length;
if (length == 2)
{
$(this).val(currentValue + ".");
}
else if (length == 5)
{
$(this).val(currentValue + "%");
}
});
});
This works for your basic requirements however there are a few things that need to be improved. If a user tries to delete multiple numbers it doesn't work or if they try to use the backspace key
You can use keyup or keypress function for this
<input onkeyup="myFunction()" class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" maxlength="6" />
function myFunction()
{
var input = document.getElementById("Percentage1");
if( input.value.length > 6 )
{
alert( "too many characters" );
return false;
}
}
UPDATED:
<input type="text" id='text_field' onkeyup="check()"/>
<script>
function check()
{
var len=document.getElementById('text_field').value.length;
if (len==2)
document.getElementById('text_field').value=document.getElementById('text_field').value+".";
if (len==5)
document.getElementById('text_field').value=document.getElementById('text_field').value+"%";
}
</script>
Okay then there is a text field where only if you put "99.99%" type pattern it will validate
<script type="text/javascript">
function fnc(){
pattern=/\d+[.]+\d+[%]/g;
text=document.getElementById("atext").value;
x=pattern.test(text);
alert(x);
}
</script>
<input type="text" maxlength="6" id="atext">
<input type="button" onClick="fnc()" value="click me">
Try this one,
With Script portion
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#test').blur(function() {
if ($(this).val().match('(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)')) {
alert("Percentage Matched");//Any thing which you want
}
else
alert("Not Valid Input");
});
});
</script>
And Code for Textbox
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="test" runat="server"></asp:TextBox>
</div>
</form>

Categories

Resources