My jquery function is like this i want to check when user enter netWeight greater than gross weight at that i want to give alert on it's blur. But it's not working i get both weight on alert but i have with this condition
function checkWeight(aboj)
{
var row = $(aboj).parents('.itemRow');
var gWeight = row.find('.gWeight').val() != '' ? row.find('.gWeight').val() : 0;
var netWeight = row.find('.netWeight').val() != '' ? row.find('.netWeight').val() : 0;
if(gWeight > netWeight)
{
alert("Please Check Gross Weight");
}
}
my html is like this
<input type="text" class="input netWeight" name="netWeight[]" onblur=" checkWeight(this);>
You're comparing strings. You need to parse the string value to float or integer to make the numeric comparison:
parseInt
parseFloat
$('body').on('click', '#compare', function () {
var gross = parseFloat($('#gross').val());
var net = parseFloat($('#net').val());
if (gross>net) {
alert('gross: ' + gross + ' is greater than net: ' + net);
}
if(net>gross) {
alert('net: ' + net + ' is greater than gross: ' + gross);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Gross:<input type="text" id="gross"/>
<br/>
Net:<input type="text" id="net"/>
<br/>
<input type="button" id="compare" value="Compare"/>
me get salutation with using parseFloat
function checkWeight(aboj)
{
var row = $(aboj).parents('.itemRow');
var gWeight = row.find('.gWeight').val() != '' ? row.find('.gWeight').val() : 0;
var netWeight = row.find('.netWeight').val() != '' ? row.find('.netWeight').val() : 0;
if(parseFloat(gWeight) < parseFloat(netWeight))
{
alert("Please Check Gross Weight");
}
}
Related
I've been trying to mask the phone number into a region specific format.
$("input:text[name=phone_number]").keyup(function() {
var number = $(this).val().replace(/[^\d]/g, '');
number = number.replace(/(\d{3})(\d{3})(\d{3})/, "($1) $2-$3");
$(this).val(number);
});
The problem I am having with the script above is that regex is waiting for 3 numbers before it replaces the value in the input field.
And additionally I have to press enter for the effects to take place.
Is there a way I can make (\d{3}) this more dynamic. For example even if I've entered only 1 digit it should still display (0 ).
And then I continue entering (05 )... and so on...to a format that looks like this (051) 000-000?
I don't want to use additional plugins. I know there are many out there.
I made a simple mask, check:
$("input[name=phone_number]").keydown(function(e) {
var actualValue = e.key;
var baseMask = '(###) ###-###';
var valueInput = this.value.match(/\d/g);
if (actualValue !== 'Backspace' && /[^\d]/.test(actualValue)) {
return false;
}
if (actualValue === 'Backspace') {
if (!valueInput) {
return false;
}
valueInput.pop();
actualValue = '#';
}
var numsValues = valueInput ? valueInput.concat(actualValue) : [actualValue];
$.each(numsValues, function() {
baseMask = baseMask.replace(/\#/, this);
});
$(this).val(baseMask);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="phone_number">
$("#input").keyup(function() {
var number = $(this).val().replace(/[^\d]/g, "");
number = number.replace(/(\d{3})(\d{0,3})(\d{0,3})/, function(match, p1, p2, p3) {
if (p2.length < 1)
return "(" + p1 + ") ";
else if (p3.length < 1)
return "(" + p1 + ") " + p2;
return "(" + p1 + ") " + p2 + "-" + p3;
});
$(this).val(number);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id=input placeholder="type your number">
I have a textbox and onkeyup event I have to mask (with asterisk (*) character) a portion of the string (which is a credit card number) when user enter the values one after the other. e.g. say the value that the user will enter is 1234 5678 1234 2367.
But the textbox will display the number as 1234 56** **** 2367
I general if the user enters XXXX XXXX XXXX XXXX, the output will be XXXX XX** **** XXXX where X represents any valid number
The program needs to be done using jQuery. I have already made the program (and it is working also) which is as follows:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $(this).val();
var CCNLength = CCNValue.length;
$.each(CCNValue, function(i) {
if (CCNLength <= 7) {
$("#txtCCN").val(CCNValue);
} //end if
if (CCNLength >= 8 && CCNLength <= 14) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, CCNLength).replace(/[0-9]/g, "*"));
} //end if
if (CCNLength >= 15) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/[0-9]/g, "*") + CCNValue.substring(15));
} //end if
});
});
});
</script>
</head>
<body>
<input type="text" id="txtCCN" maxlength=19 />
</body>
</html>
But I think that the program can be optimized/re-written in a much more elegant way.
N.B. I don't need any validation at present.
No need of any condition of length, substring and replace can be directly used on the string of any length safely.
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $.trim($(this).val());
$(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/\d/g, "*") + CCNValue.substring(15));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
val can also be used
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
$(this).val(function(i, v) {
return v.substring(0, 7) + v.substring(7, 15).replace(/\d/g, "*") + v.substring(15);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
The same can be done in VanillaJS
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('txtCCN').addEventListener('keyup', function() {
var value = this.value.trim();
this.value = value.substring(0, 7) + value.substring(7, 15).replace(/\d/g, '*') + value.substring(15);
}, false);
});
<input type="text" id="txtCCN" required maxlength="19" />
Try It: Its 100% workable...
$(document).ready(function () {
$("#txtCCN").keyup(function (e) {
var CCNValue = $(this).val();
CCNValue = CCNValue.replace(/ /g, '');
var CCNLength = CCNValue.length;
var m = 1;
var arr = CCNValue.split('');
var ccnnewval = "";
if (arr.length > 0) {
for (var m = 0; m < arr.length; m++) {
if (m == 4 || m == 8 || m == 12) {
ccnnewval = ccnnewval + ' ';
}
if (m >= 6 && m <= 11) {
ccnnewval = ccnnewval + arr[m].replace(/[0-9]/g, "*");
} else {
ccnnewval = ccnnewval + arr[m];
}
}
}
$("#txtCCN").val(ccnnewval);
});
});
One thing you might consider is deleting the first two if statements. All of the work your function does is contained within the last one, so you could just change it from
if(CCNLength >= 15)
to
if(CCNLength >= 8)
This seems to maintain the functionality while cutting out some repetition in your code.
Adding a generic routine for customizing space points and mask range in the input data. This will also respect the space characters as you originally asked for.
$(function () {
$("#cardnum").keyup(function (e) {
var cardNo = $(this).val();
//Add the indices where you need a space
addSpace.call(this, [4, 9, 14], cardNo );
//Enter any valid range to add mask character.
addMask.call(this, [7, 15], $(this).val()); //Pick the changed value to add mask
});
function addSpace(spacePoints, value) {
for (var i = 0; i < spacePoints.length; i++) {
var point = spacePoints[i];
if (value.length > point && value.charAt(point) !== ' ')
$(this).val((value.substr(0, point) + " "
+ value.substr(point, value.length)));
}
}
function addMask(range, value) {
$(this).val(value.substring(0, range[0])
+ value.substring(range[0], range[1]).replace(/[0-9]/g, "*")
+ value.substring(range[1]));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cardnum" maxlength="19" />
How to check value in input using getElementsByClassName , Like this ?
When i load page, I want to alert
HAVE VALUE 3 INPUT
NOT HAVE VALUE 2 INPUT
How can i do that ?
................................................................................................................................................
http://jsfiddle.net/3AaAx/37/
<input type="text" class="xxx" value="111"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="222"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="333"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
// this function for use getElementsByClassName on IE 7 and 8 //
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', #class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
var xxx_var = document.getElementsByClassName('xxx');
alert(xxx_var.length);
});
</script>
Add below code after var xxx_var = document.getElementsByClassName('xxx');
var inputCount=0,nonInputCount=0;
for(var i=0;i<xxx_var.length;i++){
if(xxx_var[i].value != ""){
inputCount++;
}else{
nonInputCount++;
}
}
alert("Input Count " + inputCount + " , and non input count " +nonInputCount );
If you use jquery it will be very easier code.
Let me know if you didn't understand.
Thanks
Raviranjan
I currently have a javascript code below that calculates a grand total into a read only text field when dealing with currency formats i.e. $500.00. The problem that I am running into is how to handle the calculation when more than one negative number is entered in currency format (MinusSignNegative) i.e. ($500.00) instead of -$500.00. I am currently getting a NaN error in the grand total.
I believe that this regex should handle it but I can't figure out how to implement. http://www.regexlib.com/(X(1)A(bk8AHOFYowt7XHOC4WUCtfdM2LhlaovTNInhWLTrzAeoeq-c53XkkdwLD-WDe3OgQtJ7BLHSs0P-u-RrLbfVZaQIHkBH2exYGw0qtz6nqSamZNVqtnyufo9Y3nrEq5mq-mry63HY4Nnv0dfsQOZzKvuwcKAuwigyyQva-67laxr-ModxTQESW8fXx2XJL_0L0))/REDetails.aspx?regexp_id=625&AspxAutoDetectCookieSupport=1
Can anybody offer a solution?
<SCRIPT LANGUAGE="JavaScript">
<!--
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
if (what.elements['price' + i].value.replace(/\$|\,/g,'') == '')
what.elements['price' + i].value.replace(/\$|\,/g,'') == '0.00';
grandTotal += (what.elements['price' + i].value.replace(/\$|\,/g,'') - 0);
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}
//-->
</SCRIPT>
<FORM NAME="myName">
Tax Due/Refund: <input TYPE="text" NAME="price0" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Interest: <input TYPE="text" NAME="price1" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Penalty: <input TYPE="text" NAME="price2" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Total Amount Assessed: <INPUT TYPE="TEXT" NAME="grandTotal" class='currency' SIZE="25" READONLY="readyonly" style="background:#eee none; color:#222; font-weight:bold">
</FORM>
If you are trying to move a negative sign from the number to the left of a dollar sign,
do it when you write the total value field.
function total(what, number){
var grandTotal= 0, i= number, val, sign;
while(i){
val= what.elements['price' + i--].value.replace([$, ]+/g,'') ;
grandTotal+= parseFloat(val) || 0;
}
sign= grandTotal<0? '-' :'';
what.grandTotal.value= sign+'$'+ Math.abs(Math.round(grandTotal*100)/100);
}
You can do it with or without that regex.
Without:
fieldValue = field.value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
With:
fieldValue = field.value; // "(500.00)"
// test if the value matches that pattern for negative numbers
if (fieldValue.match(/PUT_THAT_REGEX_HERE/g)) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
it should look like this:
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
fieldValue = what.elements['price' + i].value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
} else if (fieldValue.replace(/\$|\,/g,'') == '') {
numberFieldValue = 0;
} else {
numberFieldValue = number(fieldValue.replace(/\$|\,/g,''));
}
grandTotal += numberFieldValue ;
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}
Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}