Jump to content

Recommended Posts

Hi,

 

I'm tryign to do a simple (!) function to calculate the total of a group by male/female....  This will display a total that is used to book places in that group, and the male/female count is required.

 

Here's the code so far:

	<script type="text/javascript">

	function addTotal() {

		var boyval 		= document.getElementById('boyval').value;
		var girlval             = document.getElementById('girlval').value;
		var memtot 		= document.getElementById('memtot');

		if((boyval == null) || (isNaN(boyval))) {
			var boyval = 0; 
		}
		if((girlval == null) || (isNaN(girlval))) {
			var girlval = 0;
		}

                        var boyval = parseInt(boyval);
                        var girlval = parseInt(girlval);


		alert(boyval);
		alert(girlval);

		memtot.value = boyval + girlval;

	}


</script>

 

However, I type in say 3 males, and the total is coming up as NaN, something I thought I'd covered.  How can I get this to do :

 

1.  Total of the two entries if they have numbers entered?

2. Total of the two entries if either one or the other is blank?

 

(There is separate empty form error checking, which works off the total.

 

TIA for any help :)

Your code is pretty comprehensive in the erro handling. The problem is that an empty field does not have a NULL value - it has an empty string value. There is a fine distinction between the two.

 

I took the liberty of making some other modifications

    function addTotal()
    {
        var boyObj  = document.getElementById('boyval');
        var girlObj = document.getElementById('girlval');
        var memtot  = document.getElementById('memtot');
    
        if(boyObj.value=='' || isNaN(boyObj.value))
        {
            boyObj.value = '0';
        }
        if(girlObj.value=='' || isNaN(girlObj.value))
        {
            girlObj.value = '0';
        }
  
        memtot.value = parseInt(boyObj.value) + parseInt(girlObj.value);
    }

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.