Enabling decimals for price input

Hello there guys can someone help me editing these code to let price input have the ability to type decimals
these the code thanks in advance

if(!(globalSize)) {
   var globalSize = new Array();
}
var specials = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;
var alpha = /[a-zA-Z]/gi;
var numric = /[0-9]/gi;

$(document).on('keyup', '.option, .quantity, .price', function() {
	if($('.option-add-btn').is(':disabled')) { 
		$('.option-add-btn').removeAttr('disabled');
	}
});

$(document).on('keyup',
		'#Products_price, #Products_quantity, .quantity, .price', function() {
			var $th = $(this);
			$th.val($th.val().replace(/[^0-9]/g, function(str) {
				return '';
			}));
		});
		
function composeOptions() {
	// Products[productCondition]
	var alpha = /[a-zA-Z]/gi;
	$('#Products_sizeOption_em_').hide();
	var size = $('.option').val().trim();
	var quantity = $('.quantity').val().trim();
	var price = $('.price').val().trim();
	var output = '';
	var quantity = quantity.replace(/\s/g, "");
	var price = price.replace(/\s/g, "");
	$('.quantity').val(quantity);
	$('.price').val(price);
	if (specials.test(size) || specials.test(quantity) || specials.test(price)) {
		$('#Products_sizeOption_em_').html(
				Yii.t('admin', 'Special Characters not allowed.'));
		$('#Products_sizeOption_em_').show();
		$('.option-add-btn').attr('disabled', 'disabled');
		setTimeout(function() {
			$('#Products_sizeOption_em_').fadeOut();
		}, 5000);
		return false;
	}

	if (alpha.test(quantity) || alpha.test(price)) {
		$('#Products_sizeOption_em_').html(
				Yii.t('admin', 'Only numbers are allowed for quantity and price.'));
		$('#Products_sizeOption_em_').show();
		$('.option-add-btn').attr('disabled', 'disabled');
		setTimeout(function() {
			$('#Products_sizeOption_em_').fadeOut();
		}, 5000);

		return false;
	}

	if (size == '' || quantity == '' || price == '') {
		$('#Products_sizeOption_em_').html(
				Yii.t('admin', 'Variant or Quantity or Price cannot be empty'));
		$('#Products_sizeOption_em_').show();
		$('.option-add-btn').attr('disabled', 'disabled');
		setTimeout(function() {
			$('#Products_sizeOption_em_').fadeOut();
		}, 5000);
		return false;
	}else if(size.length > 80){
		$('#Products_sizeOption_em_').html(
				Yii.t('admin', 'Variant should not exceed 80 characters'));
		$('#Products_sizeOption_em_').show();
		$('.option-add-btn').attr('disabled', 'disabled');
		setTimeout(function() {
			$('#Products_sizeOption_em_').fadeOut();
		}, 5000);
		return false;
	}

	if (price < 1 || quantity < 1) {
		$('#Products_sizeOption_em_').html(
				Yii.t('admin', 'Price and Quantity should be greater than zero'));
		$('#Products_sizeOption_em_').show();
		$('.option-add-btn').attr('disabled', 'disabled');
		setTimeout(function() {
			$('#Products_sizeOption_em_').fadeOut();
		}, 5000);
		return false;
	}
	if (globalSize.indexOf(size) == -1) {
		globalSize.push(size);
		var sizeClass = size.replace(/\s/g, "-");
		output += '<div class="option-' + sizeClass + '">';
		output += '<input class="disp-size" type="text" style="width: 100px; margin-right: 4px;" name="Products[productOptions]['
				+ size
				+ '][option]" value="'
				+ size
				+ '" readonly onfocus="this.blur()">';
		output += '<input class="disp-qty" type="text" style="width: 100px; margin-right: 4px;" name="Products[productOptions]['
				+ size
				+ '][quantity]" value="'
				+ quantity
				+ '" readonly onfocus="this.blur()">';
		output += '<input class="disp-price" type="text" style="width: 100px; margin-right: 4px;" name="Products[productOptions]['
				+ size
				+ '][price]" value="'
				+ price
				+ '" readonly onfocus="this.blur()">';
		output += '<span class="display-delete" style="cursor: pointer; color: rgb(255, 51, 51); font-weight: bold; margin-left: 18px;" onclick="deleteOption(\''
				+ size + '\')">X</span></div>';
		$('.added-options').append(output);
	} else {
		$('#Products_sizeOption_em_').html('Varient already exist');
		$('#Products_sizeOption_em_').show();
		setTimeout(function() {
			$('#Products_sizeOption_em_').fadeOut();
		}, 5000);
	}
	$('.option').val('');
	$('.quantity').val('');
	$('.price').val('');
	$('.option').focus();
	return false;
}

function selectSize() {
	var size = $(".item-qty").val();
	var price = $(".item-qty option:selected").attr("pricetag")
	// var currency = $("#currency_symbol").val();
	// var value = $("#currency_value").val();
	// var original = price * value;
	// var size_price = currency+" "+original;
	$('.buy-price').html(price);
	// $('.out').html(size);
}

function selectedOptionPrice() {
	var price = $(".item-qty option:selected").attr("pricetag");
	$('.option-price').css({
		"opacity" : "1"
	});
	$('.option-price-value').html(price);
}

			if (specials.test(couponValue)) {
				$('.option-error').show();
				$(".option-error").html(
						'<b>' + Yii.t('app', 'Special Characters not allowed.')
								+ '</b>');
				$("#couponValue").val('');
				setTimeout(function() {
					$('.option-error').fadeOut();
				}, 500);
				return false;
			} else if (alpha.test(couponValue)) {
				$('.option-error').show();
				$(".option-error").html(
						'<b>' + Yii.t('app', 'Only Numeric values allowed.')
								+ '</b>');
				$("#couponValue").val('');
				setTimeout(function() {
					$('.option-error').fadeOut();
				}, 500);
				return false;
			} else if (Number(price) <= Number(couponValue)) {
				$('.option-error').show();
				$(".option-error")
						.html(
								'<b>'
										+ Yii
												.t('app',
														'Coupon value is equal to or greater than product price.')
										+ '</b>');
				setTimeout(function() {
					$('.option-error').fadeOut();
				}, 3000);
				return false;
			} else {
				if (generateCouponAjax == 1) {
					generateCouponAjax = 0;
					$.ajax({
						type : 'POST',
						url : yii.urls.base + '/products/generateCoupon',
						data : {
							productId : pid,
							userId : uid,
							price : price,
							couponValue : couponValue,
							currency : currency,
						},
						success : function(data) {
							$(".generate-coupon-container").hide();
							$('.new-coupon-link').show();
							$(".coupon-code").html(
									"<div style='font-size:25px'>"
											+ Yii.t('app', 'Coupon Code')
											+ " :" + "<b>" + data
											+ "</b></div>");
							$(".coupon-code").fadeIn(1500);
							generateCouponAjax = 1;
						}
					});
				}
			}
		}
	}
}

function validateProduct() {
	var name = $("#Products_name").val().trim();
	var desc = $("#Products_description").val().trim();
	var cat = $("#Products_category").val();
	var price = $("#Products_price").val().trim();
	//var qty = $("#Products_quantity").val().trim();
	var insbuy = $("#Products_instantBuy").val();
	var proCond = $("#Products_productCondition").val();
	var location = $("#Products_location").val();
	var latitude = $("#latitude").val();
	var longitude = $("#longitude").val();
	var pattern = /^\d+$/;

	if (productImage == 0) {
		$("#image_error").show();
		$("#badMessage").hide();
		$('#image_error').text(
				Yii.t('admin', 'Minimum one image is required with good resolution'));
		return false;
	}
	if (cat == "") {
		$("#Products_category_em_").show();
		$("#badMessage").hide();
		$('#Products_category_em_').text(
				Yii.t('admin', 'Product Category cannot be blank'));
		$('#Products_category').focus();
		$('#Products_category').change(function() {
			$('#Products_category_em_').hide();
		});
		return false;
	}
	if (name == "") {
		$("#Products_name_em_").show();
		$("#badMessage").hide();
		$('#Products_name_em_').text(
				Yii.t('admin', 'Product Name cannot be blank'));
		$('#Products_name').focus();
		$('#Products_name').keydown(function() {
			$('#Products_name_em_').hide();
		});
		return false;
	} else {
		name = name.replace(/\s{2,}/g, ' ');
		$('#Products_name').val(name);
		$('#Products_name_em_').hide();
	}
	if (desc == "") {
		$("#Products_description_em_").show();
		$("#badMessage").hide();
		$('#Products_description_em_').text(
				Yii.t('admin', 'Product Description cannot be blank'));
		$('#Products_description').focus();
		$('#Products_description').keydown(function() {
			$('#Products_description_em_').hide();
		});
		return false;
	}
	if (price == "" || price == 0) {
		$("#Products_price_em_").show();
		$("#badMessage").hide();
		$('#Products_price_em_').text(
				Yii.t('admin', 'Product Price cannot be blank'));
		$('#Products_price').focus();
		$('#Products_price').keydown(function() {
			$('#Products_price_em_').hide();
		});
		return false;
	}else if(!pattern.test(price)){
		console.log(price);
		$("#Products_price_em_").show();
		$("#badMessage").hide();
		$('#Products_price_em_').text(
				Yii.t('admin', 'Product Price should be numeric'));
		$('#Products_price').focus();
		$('#Products_price').keydown(function() {
			$('#Products_price_em_').hide();
		});
		return false;
	}
	if (proCond == "") {
		console.log("product condition: "+proCond);
		$("#Products_productCondition_em_").show();
		$("#badMessage").hide();
		$('#Products_productCondition_em_').text(
				Yii.t('admin', 'Product Condition cannot be blank'));
		$('#Products_productCondition').focus();
		$('#Products_productCondition').change(function() {
			$('#Products_productCondition_em_').hide();
		});
		return false;
	}
	if ($('#Products_instantBuy').is(':checked') == true) {
		var paypalid = $('#Products_paypalid').val();
		var shippingCost = $('#Products_shippingCost').val();
		//var shippingTime = $('#Products_shippingTime').val();
		if (paypalid == '') {
			$("#Products_paypalid_em_").show();
			$("#badMessage").hide();
			$('#Products_paypalid_em_').text(
					Yii.t('admin', 'Paypal ID cannot be blank'));
			$('#Products_instantBuy').focus();
			$('#Products_paypalid').keydown(function() {
				$('#Products_paypalid_em_').hide();
			});
			return false;
		} else if (!(isValidEmailAddress(paypalid))) {
			$("#Products_paypalid_em_").show();
			$("#badMessage").hide();
			$('#Products_paypalid_em_').text(
					Yii.t('admin', 'Paypal ID should be a valid email id'));
			$('#Products_instantBuy').focus();
			$('#Products_paypalid').keydown(function() {
				$('#Products_paypalid_em_').hide();
			});
			return false;
		}
		if (shippingCost == ''){
			$("#Products_shippingCost_em_").show();
			$("#badMessage").hide();
			$('#Products_shippingCost_em_').text(
					Yii.t('admin', 'Shipping Cost cannot be blank'));
			$('#Products_shippingCost').focus();
			$('#Products_shippingCost').keydown(function() {
				$('#Products_shippingCost_em_').hide();
			});
			return false;
		}
	}
	if (location == "") {
		console.log("location: "+location);
		$("#Products_location_em_").show();
		$("#badMessage").hide();
		$('#Products_location_em_').text(Yii.t('admin', 'Location Required'));
		$('#Products_location').focus();
		$('#Products_location').keydown(function() {
			$('#Products_location_em_').hide();
		});
		return false;
	}
	if (latitude == "" || longitude == "" || latitude == "0"
			|| longitude == "0") {
		console.log("latitude: "+latitude);
		console.log("longitude: "+longitude);
		$("#Products_location_em_").show();
		$("#badMessage").hide();
		$('#Products_location_em_').text(
				Yii.t('admin',
						'Invalid Location.Select Location From Drop Down.'));
		$('#Products_location').focus();
		$('#Products_location').text('');
		$('#Products_location').keydown(function() {
			$('#Products_location_em_').hide();
		});
		return false;
	} else {
		$('#Products_location_em_').hide();
	}
	
	var updateFlag = $('.product-update-flag').val();
	
	if(updateFlag == 0){
		$('.btnUpdate').attr('disabled', 'disabled');
		$.post($('#products-form').attr('action'), $('#products-form').serialize(), function(res){
	        // Do stuff with your response data!
			var resultData = res.split('-_-');
			$('.promotion-cancel').attr('href', resultData[1]);
			$('.promotion-product-id').val(resultData[0]);
	        $('#post-your-list').modal('show');
	    });
		return false;
	}else{
		$(document).on('submit', '#products-form', function() {
			$('.btnUpdate').attr('disabled', 'disabled');
		});
	}
}

function changeQuantity() {
	var selectedQty = $(".product-quantity").val();
	$(".product-quantity-hidden").val(selectedQty);
	var unitPrice = $(".product-unit-price").val();
	var currency = $('.currency').val();
	var total = selectedQty * unitPrice;
	var oldTotal = total;
	var couponType = $(".coupon-type-hidden").val();
	var couponValue = $(".coupon-value-hidden").val();
	var shipping = $(".item-shipping").val();

	if (couponType == "1") {
		if (couponValue > 0) {
			total = Number(total) - (selectedQty * Number(couponValue));
			$(".product-coupon-discount")
					.val(selectedQty * Number(couponValue));
			$(".coupon-discount")
					.html(
							Yii.t('app', 'Discount')
									+ ': ( - ) <span class="amnt product-item-coupondiscount">'
									+ Number(selectedQty) * couponValue + " "
									+ currency + '</span>');
		}
	} else {
		discount = (Number(total) * (Number(couponValue) / 100));
		if (discount > 0) {
			if ($(".coupon-max-hidden").val() != ""
					&& $(".coupon-max-hidden").val() < discount) {
				discount = $(".coupon-max-hidden").val();
			}
			total = Number(total) - Number(discount);
			$(".product-coupon-discount").val(discount);
			$(".coupon-discount")
					.html(
							Yii.t('app', 'Discount')
									+ ': ( - ) <span class="amnt product-item-coupondiscount">'
									+ discount + " " + currency + '</span>');
		}
	}
	var grandTotal = Number(total) + Number(shipping);

	$(".product-sub-total").html(
			Yii.t('app', 'Subtotal')
					+ ':<span class="amnt product-item-total"> ' + oldTotal
					+ " " + currency + ' </span>');
	$('.product-sub-total-hidden').val(oldTotal);
	$(".sub-total-hidden").val(total);
	$(".product-grand-total").html(
			Yii.t('app', 'Order Total')
					+ ': <span class="amnt product-item-grandtotal"> '
					+ grandTotal + " " + currency + ' </span>');
}

function shippingChange() {
	var shipCost = $(".shipping-cost-hidden").val();
	var shipp = $(".shipping-range-hidden").val();
	var shippingReturn = $(".shipping-addresses").val().split('-');
	var nickname = shippingReturn[1];
	var shippingId = shippingReturn[0];
	$(".country-error").hide();
	$.ajax({
		type : 'POST',
		url : yii.urls.base + '/item/buynow/getShippingAddress',
		data : {
			nickname : nickname,
			shippingId : shippingId,
			shipCost : shipCost,
			shippingRange : shipp
		},
		success : function(data) {
			var output = JSON.parse(data);
			checkRange(output.country);
			var currency = $('.currency').val();
			$(".selected-shipping").val(output.shippingId);
			$(".fullname").val(output.username);
			$(".address1").val(output.address1);
			$(".address2").val(output.address2);
			$(".city").val(output.city);
			$(".pincode").val(output.pincode);
			$(".state").val(output.state);
			$(".country").val(output.country);
			$(".phone").val(output.phone);
			$(".product-item-shippingcost").html(
					output.shipPrice + " " + currency);
			$(".item-shipping").val(output.shipPrice);
			var subtotal = $(".product-sub-total-hidden").val();
			var discount = $(".product-coupon-discount").val();
			var shipping = $(".item-shipping").val();
			var grandTotal = (Number(subtotal) + Number(shipping))
					- Number(discount);
			console.log(subtotal + " " + shipping + " " + discount);
			$(".product-item-grandtotal").html(grandTotal + " " + currency);
		}
	});
}

Hi @med190d, you can allow points like

this.value = this.value.replace(/[^\d\.]/g, '')

allowing only one single point is a bit trickier though; you’ll have to split the value to pre-decimal and decimal strings, and perform the replacement on them. You might do this using the .split() method, or using another regular expression with capturing parentheses, like e.g.

$('.price').keyup(function keyup () {
  this.value = this.value.replace(
    /([^\.]+\.?)(.*)/, 
    (match, predec, dec) => 
      predec.replace(/[^\d\.]/g, '') + dec.replace(/\D/g, '').slice(0, 2)
  )
})

Thanks @m3g4p0p but it says on price input Product Price should be numeric? should i past the whole javascript that includes these option!!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.