if condition in javascript function not working - javascript

I need to compare the values and return the message.But the message returned always. How can i do it?
Javascript:
function Calculation() {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
for (var i = 0; i < grid.rows.length - 1; i++) {
var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]")
var cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text();
}
if (txtcurrentrcvamount > cell) {
alert("Receive quantity must be less or equal PO quantity");
return false;
}
return true;
}

You need to take the value of your input:
var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val()
// ^^^^^^
Since you're comparing numbers, and val() and text() return strings, you should convert your values to numbers before doing the comparison:
if (Number(txtcurrentrcvamount) > Number(cell))
Do note that Number(someStringThatIsNotANumber) will return NaN

Because your scope of a variable (txtcurrentrcvamount) is limited in between for loop, That's why this not working outside the loop scope.
for more detail, you can view this post...scope of variables
For using this variable in if condition you have initialized it before the for loop...
EDIT:
Try this may this help you either. I think there some other finding to suppose you have two rows in your grid then which row value you want to check because this always return last row value... and if there a number value for both of the variable assignment txtcurrentrcvamount ,cell then it should be work perfectly.
function Calculation() {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
var txtcurrentrcvamount ;
var cell;
for (var i = 0; i < grid.rows.length - 1; i++) {
txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val();
cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text();
}
if (Number(txtcurrentrcvamount) > Number(cell)) {
alert("Receive quantity must be less or equal PO quantity");
return false;
}
return true;
}

Related

Why Javascript console.log result is undefined while reversing the string?

var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
When I tried to run it it returned me "undefined". I wonder what's the problem here.
The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.
var a = "gsdgtrshghf";
function reverseString(strr){
var result="";
if (strr.length){
for(var i=strr.length-1;i>=0;i--){
var a=strr.charAt(i);
result+=a;
}
}
return result;
}
console.log(reverseString(a))
Have a look:
var a = "gsdgtrshghf";
function reverseString(strr) {
var result = "";
if (strr.length != null) {
for (var i = strr.length - 1; i >= 0; i--) {
var a = strr.charAt(i);
result += a;
}
}
return result;
}
console.log(reverseString(a));
// Better
const reverse = str => Array.from(str).reverse().join('');
console.log(reverse('foo 𝌆 bar mañana mañana'));
Explanation
It's charAt(i) not chatAt(i)
Loop should start from length - 1 and end at 0 and i should be decremented
And finally declare the variable outside of if
i.e for(var i = strr.length - ; i >= 0; i--){
not for(var i=strr.length;i>0;i++){
Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM

Issue with my var getting undefined

I am trying to create a reverse function to the String type in javascript. My code is like
String.prototype.reverse = function () {
var s = "";
for(var i=this.length;i>=0;i--){
s+=this[i];
}
return s;
}
When I try to use it on for example like "test".reverse();
instead of giving "tset" it's giving "undefinedtset"
I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?
You just need to change var i=this.length to var i=this.length-1, because an array starts at position 0 :
String.prototype.reverse = function () {
var s = "";
for(var i=this.length-1;i>=0;i--){
s+=this[i];
}
return s;
}
this.length gives you 4 (4 letters in test word) and you start iterating from 4 to 0.
The problem is that nothing exists under 4 index (your letters are stored in 0-3 positions).
Try with:
for (var i = this.length - 1; i >= 0; i--) {
s += this[i];
}
The reason why your code isn't working has been answered by the others already, but if you want a shorter version of the reverse, you can do it like this:
String.prototype.reverse = function(){
return this.split('').reverse().join('');
}
console.log('Hello World'.reverse())

multiple comma seperate value compare using JS

I want validation using a comma separated value.
Here in the image, there are two fields : one is "Saloon Price" (value : 10,10,10,10), and another is "Saloon Offer Price" (value : 11,11,11,11).
The first value must be lower than the second.
Saloon price Value >= Saloon Offer Price value
validations based on first value of saloon price and saloon offer price same for second , 3rd ...n
var size_weight_lengh = size_weight.split(',');
var saloon_price = validator.getFieldElements('saloon_price').val(),
saloon_price_lengh = saloon_price.split(',');
var saloon_offer = validator.getFieldElements('saloon_offer_price').val(),
saloon_offer_lengh = saloon_offer.split(',');
if(saloon_price_lengh.length === saloon_offer_lengh.length) {
for(var i=0; i<= saloon_price_lengh.length-1; i++) {
if((saloon_price_lengh[i]) >= (saloon_offer_lengh[i])) {
return true;
}
return false;
}
}
Split the string and then do a value comparison of two array elements.
It uses "break" and "continue" to reduce the unnecessary iterations over the loop.
Here is the full script. Adjust the functionality accordingly.
$(document).ready(function () {
var value = ComparePrice();
alert(value);
});
function ComparePrice() {
var salonOfferPrice = $('#saloon_offer_price').val();
var salonPrice = $('#saloon_price').val();
var offerPriceArray = salonOfferPrice.split(",");
var priceArray = salonPrice.split(",");
var isValid = false;
if (offerPriceArray.length == priceArray.length) {
for (var i = 0; i < offerPriceArray.length; i++) {
for (var j = 0; j < priceArray.length; j++) {
if (i == j) {
if (offerPriceArray[i] < priceArray[j]) {
alert(offerPriceArray[i] + "is less than" + priceArray[j]);
isValid = true;
}
else {
alert(offerPriceArray[i] + "is greater than or equal" + priceArray[j]);
return false;
}
}
else {
continue;
}
}
}
}
return isValid;
}
You have to do value by value comparison.
var sp="10,20,30"; //get your field values here
var sop="5,10,15";
var spArr = sp.split(','); //split the values using comma
var sopArr = sop.split(',');
if(spArr.length === sopArr.length){
for(var i in spArr){
if(parseInt(spArr[i])<parseInt(sopArr[i])){
//throw some error or your logic goes here.
}
}
}
Just make sure that you accept only numbers and comma using some regex check in the text field.

Check Duplicate Value in array javascript

I need to check to 1 array value, if value duplicated, it will pop up alert.
Here is the function :
function checkDuplicateTenure(){
var f = document.frmPL0002;
var supplgrid = document.getElementById("mdrPymtGrid2");
var len = (supplgrid.rows.length) - 1;
for(var i=0;i<len;i++){
if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
alert("DUPLICATE LOAN TENURE IN MONTH(S)");
}
}
return false;
}
That function is works if got duplicate value in array, but if all value is different, its will hit js error if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) { Unable to get property 'value' of undefined or null reference.
Thanks
This is a simple out of bounds error. Fix it by using this:
for (var i=0;i<len-1;i++) {
So, i+1 will never be the same as len.
change it
for(var i=0;i<len-1;i++){
if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
alert("DUPLICATE LOAN TENURE IN MONTH(S)");
}
}
suppose your loop runs 5 times and you can set i+1 inside the loop it comes 6 which is undefined index that why js error occurs
Try this:
function checkDuplicateTenure(){
var f = document.frmPL0002;
var supplgrid = document.getElementById("mdrPymtGrid2");
var len = (supplgrid.rows.length) - 1;
for(var i=0;i<len-1;i++){
if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
alert("DUPLICATE LOAN TENURE IN MONTH(S)");
}
}
return false;
}

Compare 2 records on screen with javascript

Im looking for a way to compare 2 json records on screen. The way i want is that, i want to show these 2 records side by side and mark the matched or unmatched properties.
Is there a library that does it already, and if not, how can i do it ??
Edit
My goal is to identify the same/different properties & to show them to users with different styles, rather than comparing the objects as a whole.
Someone made a jQuery plugin for this - jQuery.PrettyTextDiff.
https://github.com/arnab/jQuery.PrettyTextDiff
$("input[type=button]").click(function () {
$("#wrapper tr").prettyTextDiff({
cleanup: $("#cleanup").is(":checked")
});
});
JSFiddle
Here is a quick JavaScript function to help you compare the to JSON strings.
First, it checks that they have same number of properties, then compares that they have the same properties (by name) and then it compares the values.
You may want to tweak the value comparison (to allow for undefined or null).
Hope it is a good starter for you.
<script type="text/javascript">
var so = {}; // stackoverflow, of course.
so.compare = function (left, right) {
// parse JSON to JavaScript objects
var leftObj = JSON.parse(left);
var rightObj = JSON.parse(right);
// add object properties to separate arrays.
var leftProps = [];
var rightProps = [];
for(var p in leftObj) { leftProps.push(p); }
for(var p in rightObj) { rightProps.push(p); }
// do they have the same number of properties
if (leftProps.length != rightProps.length) return false;
// is every right property found on the left
for (var r = 0; r < rightProps.length; r++) {
var prop = rightProps[r];
if (leftProps.indexOf(prop) < 0) {
return false;
}
}
// is every left property found on the right
for (var r = 0; r < leftProps.length; r++) {
var prop = leftProps[r];
if (rightProps.indexOf(prop) < 0) {
return false;
}
}
// do the values match?
for (var q = 0; q < leftProps.length; q++) {
var propname = leftProps[q];
var leftVal = leftObj[propname];
var rightVal = rightObj[propname];
if (leftVal != rightVal) {
return false;
}
}
return true;
}
</script>

Categories