user2823525 user2823525 - 1 month ago 8
HTML Question

multiple comma seperate value compare using JS

enter image description here

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;
}
}

Answer

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(",");

    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]);

                    }
                    else {
                        alert(offerPriceArray[i] + "is greater than or equal" + priceArray[j]);
                        return false;
                    }
                }
                else {
                    continue;
                }

            }
        }
    }
    return true;
}
Comments