Jump to content

How to enter JS variable into JS if statement


marmite

Recommended Posts

Hi, complete JS newbie, and struggling!

 

I have the following code, and all i need to do is pass the variable "i" correctly into it. Where code says qty_i, that is because elsewhere in the code there are a (dynamic) number of inputs, called: qty_1, qty_2 etc. So the line with the problem is:

 if (!(document.mycart.qty_+i == '')) { 

 

I want to check that at least one input ahs a value before user clicks add to cart. Grateful for any help!

 

function verify() {
alert ("hello");
var i=0;
var notblank=0;
var numrows=<?php print "'".$numrows3."'"; ?>;
for (i;i<=numrows;i=i+1) {

	if (!(document.mycart.qty_+i == '')) {
		notblank=1;
	}
}

if (!(notblank==1)) {
	alert("Please enter a quantity to add to the cart")
	return(false)
} else {
	return(true)
}
}

Thanks for this.. still struggling... your code works great, but with the code below, four empty text inputs return four alerts with nothing in them (i.e. they are passing the if condition, which says if NOT null...).

 

So they're null, but they're passing for not nulls. Confused!

 

Moreover, sometimes alert(nonblank) and alert(please enter a quantity...) run and sometimes not. I find this very odd.

 

Can you shed any light?

 

Thanks

Emma

 

function verify() {
var i=0;
var notblank=0;
var numrows=<?php echo $numrows3; ?>;
for (i;i<=numrows;i=i+1) {
	var instance="qty_" + i;
	if (document.getElementById(instance).value != null) {
		alert(document.getElementById(instance).value);
		notblank=1;
	}
}
alert(notblank);
if (notblank==1) {
	alert("Please enter a quantity to add to the cart")
	return(false)
}
return(true)

}

OK, scrap that, removed the .value from "if (document.getElementById(instance)!= null) {" and now I get all the pop-ups.

 

But still I am passing the if condition when I shouldn't be.

 

function verify() {
var i=0;
var notblank=0;
var numrows=<?php echo $numrows3; ?>;
for (i;i<=numrows;i=i+1) {
	var instance="qty_" + i;
	if (document.getElementById(instance)!= null) {
		alert(document.getElementById(instance).value);
		notblank=1;
	}
}
alert(notblank);
if (notblank==1) {
	alert("Please enter a quantity to add to the cart")
	return(false)
}
return(true)

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.