Page 1 of 1

Testing for the existence of variables in JavaScript

Posted: Wed Sep 03, 2003 6:22 am
by mikeb
Hi,

JavaScript problem:

I'm currently building an e-commerce site. I need to 'force' my customers to read my terms and conditions before parting with their hard earned cash through our WorldPay connection. I am using a checkbox and 'onsubmit' in the body tag to check that they have clicked on a 'I understand I am handing over all my rights etc.' checkbox. This works fine - almost! Some browsers are giving errors and here's the reason:

The status of the checkbox is being checked (i.e. is it clicked?), but to stop error messages that some browsers are giving me, I would like to add some extra JS to test for the 'existence' of the checkbox field first. So the pseudo-code would look like this:

if exists(checkbox-field){
if checkbox field has been clicked{
Allow the form post to be completed
{
}

I can check whether the checkbox has been clicked but not whether it exists in the first place. (I know this sounds a bit odd, but I have reasons which I will expand on if requested, it will just take even MORE verbosity than I am normally guilty of!)

Many thanks,

Mike B

Posted: Wed Sep 03, 2003 6:32 am
by JayBird
Give your checkbox and id (id=something)

Insert this code in your head tag

Code: Select all

<script language=JavaScript>
function getPageItem(itemID)
&#123;
    if (document.getElementById)
    &#123;
        return document.getElementById(itemID);
    &#125;
    
    if (document.all)
    &#123;
        return document.all&#1111;itemID];
    &#125;

    return null;
&#125;


function checkExists()
	&#123;
	var span_obj = getPageItem("InsertCheckboxIDhere"); <!-- dont forget to change this line -->
	if (span_obj)
	&#123;
	// Do your stuff
	&#125;
	else
	&#123;
	// Display error
	&#125;
&#125;
</script>
Then, on click execute the checkExists() function.

May need tweaking, but should work i think

Mark

Posted: Wed Sep 03, 2003 6:43 am
by patrikG
I am using the code below to check whether variables exist:

Code: Select all

if(typeof document.registration.organisation!="undefined")
		&#123;
                alert("Yipeeh! form-field 'organisation' exists in from 'registration'");
		&#125;
I suppose you can modify it to use getElementById easily.

Posted: Wed Sep 03, 2003 6:49 am
by mikeb
Thanks Bech100

That looks like the business! I'll stuff that into my offending page (with the local changes) and see what happens. I'm using Actinic Catalog for the e-commerce side and the prob is that it uses a templated html header which contains the <body onsubmit...>. This means that my code is getting exectuted on all pages and not just the one I need it on. Your code should allow for the code to execute without error on pages which don't contain the checkbox and still do the job on the cart page!

cheers,

Mike B