www.webdeveloper.com
Results 1 to 8 of 8

Thread: help w/javascript syntax

  1. #1
    Join Date
    Apr 2013
    Location
    gastonia NC
    Posts
    93

    help w/javascript syntax

    Hi, no doubt, the following should be - is a simple little project.
    Please, someone tell me why it doesn't work. submitting the acct#, entering
    the paidamt enters the date. Only those two fields are updated.
    Below is the relevant code. thanks.
    Code:
    function $_(IDS) { return document.getElementById(IDS); }
    function calculate_paid() {
       var paidamt = document.getElementById("paidamt");
         var amtdue = document.getElementById("amtdue");
       var prevbal = document.getElementById("prevbal");
         var status = document.getElementById("status"); 
                 var pd = document.getElementById("pd");
       var checkno = document.getElementById("checkno");
     var datepaid = document.getElementById("datepaid");
          var dateNow = new Date();
      var dayNow = dateNow.getDate();
      var paydate = (dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear();
    datepaid.value = paydate;
      amtdue.value = parsefloat(amtdue.value)
    paidamt.value = parsefloat(paidamt.value) 
    prevbal.value = parsefloat(prevbal.value)
      checkno.value = parseint(checkno.value)
    checkno = checkno + 1;
        if(status=="N") {amtdue = amtdue + prevbal - paidamt;}
       if(status=="Y") {prevbal = prevbal + amtdue - paidamt;}
    
         if(amtdue==0.00) { pd = "P"; }
        if(prevbal==0.00) { pd = "P"; }
       }
    PHP Code:
    <script type="text/javascript" src="paytest.js"></script>
          
       <td><input type='text' size=7 id='paidamt' name='paidamt' value='" . $row['paidamt'] ."' 
    onBlur='calculate_paid(this)'></td>
    <td><input type='text' size=7 id='amtdue' name='amtdue' value='" . $row['amtdue'] . "'></td>
    <td><input type='text' size=7 id='prevbal' name='prevbal' value='" . $row['prevbal'] . "'></td>
    <td><input type='text' size=10 id='datepaid' name='datepaid' value='" . $row['datepaid'] . "'></td>
    <td><input type='text' size=1 id='pd' name='pd' value='" . $row['pd'] . "' ></td>    
    <td><input type='text' size=5 id='checkno' name='checkno' value='" . $row['checkno'] . "' 

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,507
    If you are pulling data from a database as the PHP seems to hint at, why are you using JavaScript?

    You don't give enough of either code to allow people to understand the issues you are experiencing

    You have no <input> called status but you reference it.

    If you want any help it would help to have more code and HTML code as well.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  3. #3
    Code:
    checkno = checkno + 1;
     if(status=="N") {amtdue = amtdue + prevbal - paidamt;}
       if(status=="Y") {prevbal = prevbal + amtdue - paidamt;}
    Those are INPUT, not values. ALL of those should probably say .value on them, just as with your parseFloats.

    That said there's a lot wrong there and a lot of "code for nothing". IF that's your actual markup, you can't have a SCRIPT tag as a sibling to TD... since the parent tag should be a TR and the ONLY elements that can be a direct-child of a TR is TD and TH.

    That looks like PHP output, you should probably flip your quote usage and use comma delimits instead of string addition, it runs a hair faster and is more consistent; otherwise if you're going to use double quotes why the string additions?

    IF that's actually a table can I assume you'd have multiple rows of this? If so how are you dealing with the fact that ID's are unique and can only be used once per page? If you don't have multiple rows, WHY IS THIS A TABLE? (and where are your LABELS?)

    As to your scripting -- if you have multiple variables in a row you don't have to say VAR on each of them, if you're going to perform the same operaton over and over functionalizing it can help greatly keep things clean (which it LOOKS like you started to do with the $_ function but then you didn't use it), your method of determining the next month is flawed... If you're going to have the same result of two back to back if use a single OR so you don't end up running the same assignment twice..

    So, TRYING to clean up your scripting:

    Code:
    function _get(id, cleanValue) {
    	var e = document.getElementById(id);
    	if (cleanValue) switch (cleanValue) {
    		case 'real': e.value = parsefloat(e.value); break;
    		case 'int': e.value = parseint(e.value); break;
    	}
    	return e;
    }
    
    function daysInMonth(year, month) {
    		var d = new Date(year, month + 1, 0);
    		return d.getDate();
    }
    
    function calculate_paid() {
    	var
    		amtDue = _get('amtdue', 'real'),
    		paidAmt = _get('paidamt', 'real'),
    		prevBal = _get('prevbal', 'real'),
    		checkNo = _get('checkno', 'int'),
    		status = _get('status'),
    		datePaid = _get('datepaid'),
    		pd = _get('pd'),
    		now = new Date(),
    		payMonth = (now.getMonth() + 1) % 12,
    		payYear = now.getFullYear() + (payMonth == 0 ? 1 : 0),
    		payDate = now.getDate(),
    		lastDate = daysInMonth(payYear, payMonth);
    
    	if (payDate > lastDate) payDate = lastDate;
    	datePaid.value = payMonth + '/' + payDate + '/' + payYear;
    	checkNo.value++;
    	switch (status) {
    		case 'N': amtDue.value += prevBal.value - paidAmt.value; break;
    		case 'Y': prevBal.value += amtDue.value - paidAmt.value; break;
    	}
    	if ((amtDue.value == 0) || (prevBal.value == 0)) pd.value='P';
    }
    You should probably also be attaching your scripting from the scripting swinging an axe at the 'onblur' attribute, and trapping 'change' instead of 'blur' (though for legacy IE you may need to add BOTH - which is annoying as hell.

    Though really your logic here doesn't make any sense since if you blur that input multiple times the values are going to skew all over the place. I'm stuck wondering just what you're trying to accomplish with this -- hell, some of your input don't even look like they should BE input.

  4. #4
    Join Date
    Apr 2013
    Location
    gastonia NC
    Posts
    93
    hi, below is the entire code. Status is a field in the "numbers" table
    (totals such as receipt#, check#, etc,) which are updated as well as
    in the one selected for display. It is for a condition;
    not input, not updated.

    HTML Code:
     <!DOCTYPE html><html>
    <head>
    <meta charset=utf-8>
    <title>invoice payment </title>
    <script>
    function $_(IDS) { return document.getElementById(IDS); }
    function calculate_paid() {
       var paidamt = document.getElementById("paidamt");
         var amtdue = document.getElementById("amtdue");
       var prevbal = document.getElementById("prevbal");
         var status = document.getElementById("status");
                 var pd = document.getElementById("pd");
       var checkno = document.getElementById("checkno");
     var datepaid = document.getElementById("datepaid");
          var dateNow = new Date();
      var dayNow = dateNow.getDate();
      var paydate = (dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear();
    datepaid.value = paydate;
    amtdue.value = parsefloat(amtdue.value)
    paidamt.value = parsefloat(paidamt.value)
    prevbal.value = parsefloat(prevbal.value)
    checkno.value = parseint(checkno.value)
    checkno = checkno + 1;
        if(status=="N") {amtdue = amtdue + prevbal - paidamt;}
    if(status=="Y") {prevbal = prevbal + amtdue - paidamt;}
    
        if(amtdue==0.00) { pd = "P"; }
        if(prevbal==0.00) { pd = "P"; }
       }
    </script>      
    <script type="text/javascript">
    window.google_analytics_uacct = "UA-256751-2";
    </script>
    <script type="text/javascript">
    window.google_analytics_uacct = "UA-256751-2";
    </script>
    <style>body { width: 960px; margin: 0 auto; }</style>
    </head><body><b>
    
    <?php       
    //    error_reporting(0);
    error_reporting(E_ALL ^ E_NOTICE);
            $con=mysqli_connect("localhost","root","cookie","homedb");
        //============== check connection
        if(mysqli_errno($con))
        {echo "Can't Connect to oocust:".mysqli_connect_error();}
        else
        {echo "</br>";} 
        if(isset($_POST['acctno']))
      {
            $id = $_POST['id'];
        $acctno = $_POST['acctno']; 
        $name = $_POST['acctno'];
    Last edited by jedaisoul; 08-18-2014 at 04:30 PM. Reason: code tags added

  5. #5
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,507
    Well thats just the beginning... you don't show much in the way of things to help our understanding of your page and validation needs.

    I note this line

    var paydate = (dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear();

    IMHO should be

    var paydate = ""+(dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear();

    or if you are using PHP this could be as simple as

    var paydate = "<?php echo date("m"/d/Y");?>";

    if a variable is not a number and a string, it really needs to be quoted

    If these items in your script are in a web form

    Code:
    function calculate_paid() {
    var paidamt = document.getElementById("paidamt");
    var amtdue = document.getElementById("amtdue");
    var prevbal = document.getElementById("prevbal");
    var status = document.getElementById("status");
    var pd = document.getElementById("pd");
    var checkno = document.getElementById("checkno");
    var datepaid = document.getElementById("datepaid");
    IMHO you should on update of the form use the form itself as a parameter that is passed to the function

    Code:
    function calculate_paid(f) {
    var paidamt = f.paidamt.value;
    var amtdue = f.amtdue.value;
    var prevbal = f.prevbal.value;
    var status = f.status.value;
    var pd = f.pd.value;
    var checkno = f.checkno.value;
    var datepaid = f.datepaid.value;
    and so on

    if you have a string that is a number that you need to be a numerical value, simply subtract zero from the string, eg

    Code:
    var paidamt = f.paidamt.value - 0;
    var amtdue = f.amtdue.value - 0;
    var prevbal = f.prevbal.value - 0;
    You will only need parseInt and parseFloat where you get numpties that enter values like $14.99 as the amount paid rather than 14.99

    You have been advised NOT TO use variable names that are also field identifiers, so a minor case change would suffice, eg.

    Code:
    var paidAmt = f.paidamt.value - 0;
    var amtDue = f.amtdue.value - 0;
    var prevBal = f.prevbal.value - 0;
    that way you will know and the JavScript interpreter knows what you are referring to.

    As for some elements on the form, it would be advised to have them set to "readonly" so that the only thing that can alter the values will be the script, the reason being that theres nothing to stop someone altering a field that has an outstanding balance of $100 and making it $0 so when your script updates and your PHP updates, unless you have some checks in place with script on the server, your update would simply do as it is told.

    You should not rely on clientside validation to be 100% correct or truthful, always double check with a server side, the use of client side validation is helpful because it basically stops people being dicks or trying to fool the system.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  6. #6
    Quote Originally Posted by \\.\ View Post
    You should not rely on clientside validation to be 100% correct or truthful, always double check with a server side, the use of client side validation is helpful because it basically stops people being dicks or trying to fool the system.
    Which is why I'd probably not even be using JS on said page in the first place, unless I was AJAXing the calculations and even then, I'd likely make it work without scripting FIRST, then enhance it with scripting after.

  7. #7
    Join Date
    Apr 2013
    Location
    gastonia NC
    Posts
    93
    I very much appreciate your response, thanks. I haven't had time to absorb it but note a couple of things.
    The last code is original working version . I messed up trying to edit it, decrementing the amount paid
    instead of incrementing. Got to study.

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,507
    Basically, from a security stand point, putting your eggs in the client-side basket is likely to result in an omelet.

    If you strip down your code so it is just an update routine that is fed data via an AJAX routine that passes values to the server to validate and return the correct updated versions to your web page, you will be putting the processing and calculations in to an area that the client has no access to.

    In addition, you are best setting form fields to read only that would allow entry of data that is likely to compromise the script validation and what is served to the server

    Example...

    if you have <input name="paidamt" type="text" value="" /> then you would need it to be changeable, so in this case you should limit the size of the data set to something like <input name="paidamt" type="text" maxlength="8" value="" /> this would stop the user dumping a code string that may compromise the script and server-side.

    Your other number fields like <input name="prevbal" type="text" value="" /> should be readonly so that the value can't be altered by any external influence <input name="prevbal" type="text" value="" readonly /> and <input name="amtdue" type="text" value="" readonly /> this will ensure that only the script will be able to change the values.

    As we don't have your page script to understand your current form, how it is created, it is like shooting in the dark with answers. So far we have provided some assistance but would appreciate your entire page code posted here.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles