Anyone know javascript

Recommended Videos

iphonerose

New member
May 20, 2011
365
0
0
Hello everyone.

I currently have a user on a page called index.php. I want the user to be sent to a page called payment.php if a specified field in a form is empty, if not I want them to receive the error message and still be on the index page and able to enter into the field which was empty.

I have my attempt below but it?s not working. The error is appearing, but the user is still sent to payment.php.



function CheckifEmpty(Amount_field) {

var Amount_entered = document.getElementById(Amount_field);

if (Amount_entered.value == "") {
alert(Error: An amount must be entered.);
return false;
}
return true;
}


And then amidst my main body I have this:




Could anyone tell me what?s wrong with this code:
 

Zombie_Fish

Opiner of Mottos
Mar 20, 2009
4,584
0
0
First, by the looks of things you are trying to get the value of the form. The form itself doesn't have a value; that value is stored in the input fields inside the form. You need to get those elements and check their value.

Second, this doesn't return an id of the containing object; it returns the object itself [http://www.quirksmode.org/js/this.html#link7]. So getElementByID is in this case looking for an element whose ID is another element.

Third, your semi-colon is outside of the quote marks in the form tag when it should be inside. As in:

onsubmit="return CheckifEmpty(this);"
Try seeing if any of those fixes it. My JavaScript skills aren't the best in the world, not helped by JavaScript itself being a nasty language to mess around with.
 

iphonerose

New member
May 20, 2011
365
0
0
Zombie_Fish said:
First, by the looks of things you are trying to get the value of the form. The form itself doesn't have a value; that value is stored in the input fields inside the form. You need to get those elements and check their value.

Second, this doesn't return an id of the containing object; it returns the object itself [http://www.quirksmode.org/js/this.html#link7]. So getElementByID is in this case looking for an element whose ID is another element.

Third, your semi-colon is outside of the quote marks in the form tag when it should be inside. As in:

onsubmit="return CheckifEmpty(this);"
Try seeing if any of those fixes it. My JavaScript skills aren't the best in the world, not helped by JavaScript itself being a nasty language to mess around with.
Thanks for your response. I had spotted the error with the semi colon since. That didn't make a difference unfortunately.

I used document.getElementByID up above. It gives me a text field in the form whose id I had set to Amount_field. Apologies I didn't include my full form in the first post:






Considering the above, is there anything wrong you can spot. I've been messing around for a while and can't fix it and ye javascript is quite hard to debug
 

Zombie_Fish

Opiner of Mottos
Mar 20, 2009
4,584
0
0
iphonerose said:
If you're still using the same/similar javascript as before, the only thing I could guess is that getElementByID requires a string as input, so try something like:

document.getElementById("Amount_field");

...if you haven't done so already.
 

iphonerose

New member
May 20, 2011
365
0
0
Zombie_Fish said:
iphonerose said:
If you're still using the same/similar javascript as before, the only thing I could guess is that getElementByID requires a string as input, so try something like:

document.getElementById("Amount_field");

...if you haven't done so already.
hmmm I thought that could have been it! But no unfortunately. Thanks anyway
 

DoPo

"You're not cleared for that."
Jan 30, 2012
8,665
0
0
Zombie_Fish said:
iphonerose said:
If you're still using the same/similar javascript as before, the only thing I could guess is that getElementByID requires a string as input, so try something like:

document.getElementById("Amount_field");

...if you haven't done so already.
Erm, no - that would use the "Amount_field" as a string, while it's actually an input variable. OK, in this particular case, it's actually the same thing, but still. Anyway, you are also correct.

KK, OP, here is the stuff - I don't know how you got it to work in this state, but for me, the entire thing just broke, so I fixed some errors - the script type should be "text/javascript", also, you need to pass in a string to alert(), so you need the quotes around it, finally, you weren't using the input variable. Here is the revised code

Code:
	function CheckifEmpty(field_name) {
		
		var Amount_entered = document.getElementById(field_name);
		
		if (Amount_entered.value == "") {
				alert("Error: An amount must be entered.");
				return false;
			}
		return true;
	}
And when you're making the form, you'll have it like this

Code:
so you pass in the name of what you want to check. It's much more maintainable. Also, if that page you're building is not for an assignment, I'd suggest you drop the functionality from the presentation and use JS to attach the handler to the onSubmit event. You'll probably find it easier yo use a framework for that - jQuery is the one I've used, although Prototype should also be possible. Give me a shout if you need help with it.

Finally, that function would only check if the input field is empty, although calling it an amount field, suggests you'll be using it for numbers - you might want to consider validating if the input is actually a valid number (I'd assume that you might not want -100 to be paid for an item, i.e., you paying somebody to buy something). Also, don't forget server side validation, too. Never trust data you get from the client.

EDIT: Also, I think you probably didn't quite get that (no worries, it's a bit annoying anyway) but when you do onSubmit="CheckifEmpty(this)" you are passing in the whole form to the function, and then you tried getting element by ID but instead of an ID, you'd be searching by...well, the whole form object. That's mixing approaches - if you pass in the form to the function, you'd need to traverse the child nodes of the form, however, if you are using document.getElementById() you don't need to pass in the whole form, as that parses the whole page anyway. The latter is just easier to handle.
 

iphonerose

New member
May 20, 2011
365
0
0
DoPo said:
Zombie_Fish said:
iphonerose said:
snip
Hi DoPo. Thanks so much for your help. It works! I was just reusing some code which I had used before and it worked but it does make much more sense to pass the specific field. I sometimes forget the quotes in alerts because they work without anyway, so thanks for that :)

The code itself is for a short demo for an internship. It's not going to be launched or anything! With regard to using jQuery, they know I haven't used that framework before and the point of the assigned small app is just to show some basic coding knowledge so I think the more code I include which I done myself would be better than a jQuery.

With regard to the amount input validation I have a function for that too based on ascii chars and is run on 'onKeypress' (I didn't include it in the earlier post).I have that working to only allow numbers and a decimal point to be inputted. If a user inputs any other key, it doesn't appear on the form. It's essentially an empty string. The only issue I have now is only allowing the user to use a decimal point once :/

Edit:
Also sorry for the late reply. I live in Ireland so I'm probably in a different time zone

Thanks again!
 

DreadedTuesday

New member
Apr 15, 2009
6
0
0
I think that your "document.getElementById(field_name);" will return a reference to the field (the 'Element'), rather than the value stored therein. To get the amount entered you should use document.getElementById(field_name).value

Been a while though...
 

iphonerose

New member
May 20, 2011
365
0
0
DreadedTuesday said:
I think that your "document.getElementById(field_name);" will return a reference to the field (the 'Element'), rather than the value stored therein. To get the amount entered you should use document.getElementById(field_name).value

Been a while though...
I think I had that covered throught this declaration?

var Amount_entered = document.getElementById(Amount_field);

if (Amount_entered.value == "")
 

DoPo

"You're not cleared for that."
Jan 30, 2012
8,665
0
0
iphonerose said:
With regard to the amount input validation I have a function for that too based on ascii chars and is run on 'onKeypress' (I didn't include it in the earlier post).I have that working to only allow numbers and a decimal point to be inputted. If a user inputs any other key, it doesn't appear on the form. It's essentially an empty string. The only issue I have now is only allowing the user to use a decimal point once :/
That's an inefficient way to do it, IMO - aside from multiple decimal points, you would also get stuff like ".123" and "1.234" as valid amounts. You are better off checking the amount when it's submitted, so you know it's the final version and you can quickly know if it's correct or not. You could check if it's a valid numeric representation, but you'll still get 1.234 as valid. Instead, you could use regular expressions [http://www.w3schools.com/jsref/jsref_obj_regexp.asp]. Here is how to do that

var valid_pattern = /^\d{1,}(\.\d{1,2})?$/g;

if (valid_pattern.test(Amount_entered.value)) {
//snip
}


this would make sure the string starts with 1 or more numbers and if it has a decimal point, it also needs to have 1 or two digits following it. So it would accept "1", "1.2", "1.23" but not ".1" or "1.2.3", etc.

Also, make the form submission method POST rather than GET - with the latter, it's very easy for anybody to change the price - by going to http://wateverdomainname/payment.php?Amount=monies I'll be paying with "monies" rather than an actual number. You still need to validate the user's input on the server side, however, POST is the proper form in this case - the convention is that GET parameters should never bring any changes to the system but only retrieve information, while POST is used to modify things - create, update, delete.

EDIT: oops, had two different variable names instead of one in the snipped above
 

Zombie_Fish

Opiner of Mottos
Mar 20, 2009
4,584
0
0
DoPo said:
this would make sure the string starts with 1 or more numbers and if it has a decimal point, it also needs to have 1 or two digits following it. So it would accept "1", "1.2", "1.23" but not ".1" or "1.2.3", etc.
Wouldn't it be better to force the user to have two decimal places (ie
Code:
\\.\\d{2}
)? Not many currencies allow one decimal place.

Also, is there any particular reason for using
Code:
{1,}
instead of the
Code:
+
metacharacter?
 

DoPo

"You're not cleared for that."
Jan 30, 2012
8,665
0
0
Zombie_Fish said:
DoPo said:
this would make sure the string starts with 1 or more numbers and if it has a decimal point, it also needs to have 1 or two digits following it. So it would accept "1", "1.2", "1.23" but not ".1" or "1.2.3", etc.
Wouldn't it be better to force the user to have two decimal places (ie
Code:
\\.\\d{2}
)? Not many currencies allow one decimal place.
Well, yeah, but if you have 1.2, that would be the same as 1.20, so it usually works. You could force users to type out the zero at the end, also but I thought one could afford the extra flexibility.

Zombie_Fish said:
Also, is there any particular reason for using
Code:
{1,}
instead of the
Code:
+
metacharacter?
Both work, but I'm not sure how much OP knows about regexp, so wanted to be more explicit in pointing out it's one or more. Plus, it's easier to change, if OP decides that only, say, payments up to 9999 are accepted, or maybe the minimum is two digit long or something. Not that I think he's planning on that (it's just a demo work) but it's an extra.

So, for the record:

var valid_pattern = /^\d+(\.\d{2})?$/g;

this is also acceptable and probably a bit more correct, to be honest.
 

iphonerose

New member
May 20, 2011
365
0
0
DoPo said:
Hi again.
Ye I had been playing around with it since and the only way I could see to do the decimal point check was to set up flags for a decimal point and see if they come up more than once blah-de-blah. It would have been to complicated. I then found the reg expression you're talking about.

I'm currently now working on a validate form function that checks all functions with onsubmit. These other functions are checkifEmpty and checkCurrencyFormat. I haven't got it working yet, but hopefully soon. Here is the code in case you're still interested.

[script type="text/javascript"]
function ValidateForm(){
var isEmpty = CheckifEmpty();
if (!isEmpty) {
return false;
}

var Format = CheckFormat();
if (!Format) {
return false;
}
return true;
}

function CheckifEmpty(field_name) {

var Amount_entered = document.getElementById(field_name);

if (Amount_entered.value == "") {
alert("Error: An amount must be entered.");
return false;
}
return true;
}

function CheckFormat(field_name){

var Amount_entered = document.getElementById(field_name);
var Amount_valid=Amount_entered.value.match(/^\d+(?:\.\d{0,2})$/);

if (Amount_valid==null)

{
alert("Amount entered is invalid");
return false;
}

return true;
}
[/script]



[input type="text" name="Amount" id="Amount_field" ]

[input type="submit" value="Send" style="background-color:#4863A0;color:white; font-weight:bold;"]



p.s. I'm a she, not that it matters
 

Zombie_Fish

Opiner of Mottos
Mar 20, 2009
4,584
0
0
iphonerose said:
Firstly, get rid of the CheckIfEmpty and ValidateForm functions. CheckIfEmpty is redundant as the regular expression will reject empty strings anyway and ValidateForm will only ever return the same result as CheckFormat, so unless you want to do any other checks you might as well just call CheckFormat in the onsubmit field.

Your regular expression is almost there, but the question mark should be at the end of the brackets and there shouldn't be a colon - ie
Code:
(\.\d{0,2})?$
- this will check if there are zero or one occurences of the content in the bracket. Also, this will accept something like "1.", "2." etc. as input, even though there is nothing after the decimal point. There isn't anything inherently wrong with this and it would probably resolve to the same thing as "1.0" or "1.00" does depending on what you do with it in payment.php, but it is something you should know about anyway in case it is not intended.

DoPo said:
Well, yeah, but if you have 1.2, that would be the same as 1.20, so it usually works. You could force users to type out the zero at the end, also but I thought one could afford the extra flexibility.
I do agree with you - and again, 1.20 might just be resolved to 1.2 anyway in payment.php - I'm just petty like that. I also came up with a regular expression to remove leading zeroes -
Code:
^(0|[1-9]\d*)
etc. - but that really is the point where care for minor details is not worth the extra inconvenience.
 

DoPo

"You're not cleared for that."
Jan 30, 2012
8,665
0
0
iphonerose said:
DoPo said:
Hi again.
Ye I had been playing around with it since and the only way I could see to do the decimal point check was to set up flags for a decimal point and see if they come up more than once blah-de-blah. It would have been to complicated. I then found the reg expression you're talking about.

I'm currently now working on a validate form function that checks all functions with onsubmit. These other functions are checkifEmpty and checkCurrencyFormat. I haven't got it working yet, but hopefully soon. Here is the code in case you're still interested.

K, gotcha. It was a minor issue but...it's JavaScript. I know how it is - I suffered through it. Actually I still do, I can at least help out with other people's suffering.

Anyway, here is the code

function ValidateForm(field_name){
var isEmpty = CheckifEmpty(field_name);
if (!isEmpty) {
return false;
}

var Format = CheckFormat(field_name);
if (!Format) {
return false;
}
return false;
}

function CheckifEmpty(field_name) {

var Amount_entered = document.getElementById(field_name);

if (Amount_entered.value == "") {
alert("Error: An amount must be entered.");
return false;
}
return true;
}

function CheckFormat(field_name){
var Amount_entered = document.getElementById(field_name);
var Amount_valid=Amount_entered.value.match(/^\d+(\.\d{0,2})?$/);

if (Amount_valid==null) {
alert("Amount entered is invalid");
return false;
}

return true;
}

You were passing in the field ID to the function but the function itself didn't have an input parameter, so I changed the method signature to ValidateForm(field_name), also you had to pass in the parameter to both the other two functions, otherwise they tried looking up by ID but the ID was not specified at all. Also, I changed the regex - you used a non-capturing match (so \d+(?:\.\d{0,2}) this part, the ?: signifies non-capturing match) - what this does is it acts exactly like normal brackets, however, it doesn't store the match for later use (otherwise, you can extract captured patterns if they were in brackets). That regex still expected a decimal point, though, so "1" would fail but "1.23" wouldn't. I removed the non-capturing match (not really needed, although technically, you can put it back in) and instead made it a zero or one quantifier after the subpattern in the brackets. I'd suggest REGex Tester [http://www.regextester.com/] if you need to check...well, regex. You can put in your pattern and test it against any input. I find it quite useful.

Otherwise, the implementation was correct. What I'd point out is that you don't really need to check if the value is empty and if it's the correct format, as the latter would also cover the former. Well, you do get to throw different error messages, so it's not incorrect either. Also, if you create a Regex object, you can directly use .test() which would return a boolean, so it might be slightly shorter - from my example above

var valid_pattern = /^\d{1,}(\.\d{1,2})?$/g;

if (valid_pattern.test(Amount_entered.value)) {
//snip
}


iphonerose said:
p.s. I'm a she, not that it matters
Awww...damn. Sorry about that. I didn't mean to make assumptions, I tried to keep it gender neutral but I had a slip up, since I wasn't sure. Well, I could have checked your profile...but still :/

Zombie_Fish said:
DoPo said:
Well, yeah, but if you have 1.2, that would be the same as 1.20, so it usually works. You could force users to type out the zero at the end, also but I thought one could afford the extra flexibility.
I do agree with you - and again, 1.20 might just be resolved to 1.2 anyway in payment.php - I'm just petty like that. I also came up with a regular expression to remove leading zeroes -
Code:
^(0|[1-9]\d*)
etc. - but that really is the point where care for minor details is not worth the extra inconvenience.
So far, we've got
Code:
^(0|[1-9]\d*)(\.\d{2})?$
if we keep refining it, we'll be able to represent any currency ever, I suppose. And it'd be a huge incomprehensible beast, too. Like

(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\(?:(?:\r\n)?[ \t])*))*)?;\s*)

XD
 

Hagi

New member
Apr 10, 2011
2,741
0
0
Is the assignment to show off your Javascript skills or simply to show competency in web development?

I'm working in Web Development myself and whilst writing something like this wouldn't be all that hard it'd still take some time and the better solution for general problems like this is almost always to simply look around for a suitable plugin to do the work for you. No use reinventing the wheel.

You could take a look at this plugin here, seems to work just fine. There's undoubtedly many more around, simply google for javascript currency plugin.

https://code.google.com/p/jquery-formatcurrency/
 

Zombie_Fish

Opiner of Mottos
Mar 20, 2009
4,584
0
0
DoPo said:
So far, we've got
Code:
^(0|[1-9]\d*)(\.\d{2})?$
if we keep refining it, we'll be able to represent any currency ever, I suppose. And it'd be a huge incomprehensible beast, too. Like

[snip]OH GOD MY EYES![/snip]

XD
You should look into Malbolge some time. This [http://www.99-bottles-of-beer.net/language-malbolge-995.html] is a program to print out the song '99 Bottles of Beer on the Wall'.
 

DoPo

"You're not cleared for that."
Jan 30, 2012
8,665
0
0
Hagi said:
Is the assignment to show off your Javascript skills or simply to show competency in web development?

I'm working in Web Development myself and whilst writing something like this wouldn't be all that hard it'd still take some time and the better solution for general problems like this is almost always to simply look around for a suitable plugin to do the work for you. No use reinventing the wheel.

You could take a look at this plugin here, seems to work just fine. There's undoubtedly many more around, simply google for javascript currency plugin.

https://code.google.com/p/jquery-formatcurrency/
I agree, with jQuery would be just a line of code, however, OP said this is just to show coding competency. For what it's worth, I'd consider this to be adequate show of JS. Could be better but it's a good start. I would have been happier with jQuery in there but I wouldn't really be expecting it either - it's a simple enough problem for vanilla JS to handle, if there is more stuff to do, then I'll probably lean towards a framework.

Zombie_Fish said:
DoPo said:
So far, we've got
Code:
^(0|[1-9]\d*)(\.\d{2})?$
if we keep refining it, we'll be able to represent any currency ever, I suppose. And it'd be a huge incomprehensible beast, too. Like

[snip]OH GOD MY EYES![/snip]

XD
You should look into Malbolge some time. This [http://www.99-bottles-of-beer.net/language-malbolge-995.html] is a program to print out the song '99 Bottles of Beer on the Wall'.
Wat? Is...is Malbolge the name of somebody's cat and this is what was produced after it spent a day walking on the keyboard?