We have a quick order form which take in the product code (sku) and returns the product and enters a quantity of 1.
What we want to happen is any SKU that starts with EN9 we want the Quantity to be set to 0.
I have tried to work this out for myself but seem to be going no where as i have very minimum javascript experience.
This is the code which set everything
var _parent = $j(this).parent().parent().parent();
var _productid = $j(this).find('.prodid').val();
var _sku = $j(this).find('.sku').html();
var _name = $j(this).find('.name').html();
var _price = $j(this).find('.pprice').val();
var _temp_name = _name;
_temp_name = _temp_name.replace(/(<([^>]+)>)/ig,"");
_parent.find('.txt-sku').html(_sku);
_parent.find('.txt-pcode').val(_temp_name);
_parent.find('.txt-qty').val(1);
_parent.find('.pname').html(_name);
_parent.find('.pqty').html(_price);
_parent.find('.btn-addcart').attr('alt', _productid);
$j('#allid').val($j('#allid').val()+','+_productid);
$j(this).parent().hide();
_key = '';
I can see _parent.find('.txt-qty').val(1); sets the qty to 1 so i assumed i would have to wrap an IF statement around this.
I tried
if ( _sku == ('EN9)){
_parent.find('.txt-qty').val(1);}
else{
_parent.find('.txt-qty').val(0);
}
But with no luck. SO i change -sku to .sku but still no luck. If anyone could help it would be much appreciated.
3 Answers 3
I would use indexOf
Something like
if ( _sku.indexOf('EN9') > -1) {
_parent.find('.txt-qty').val(0);}
else{
_parent.find('.txt-qty').val(1);
}
This would set your quantity to 0 if EN9 is anywhere in the SKU.
If you need it at the start, specifically, check for the return of indexOf being 0 (I think should work).
if ( _sku.indexOf('EN9') == 0) {
_parent.find('.txt-qty').val(0);}
else{
_parent.find('.txt-qty').val(1);
}
2 Comments
String.prototype.startsWith method.You can use indexOf to check if a strings starts with another string, and then set the value accordingly
var qty = _sku.indexOf('EN9') === 0 ? '0' : '1';
_parent.find('.txt-qty').val(qty);
Comments
if ( _sku == ('EN9)){
This is a messed up statement, as evidenced by the lack of sensible coloring here. :)
You want to check if _sku starts with EN9. You can do that by checking if the first 3 characters are equal to that:
if (_sku.slice(0,3) == 'EN9') {}