1

I have this program that a user inputs a invoice number and then ajax goes and fills in the serial number, dealer name, number and invoice amount.

There are not a static amount of invoices. For the purpose of this example there are two invoice divs But there could be more or less. I have named my forms and divs differently however when it comes to the inputs they have the same names and ids. If i have different ids which I think i need too, I am not sure how to reference them with one java script function

Code HTML

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Untitled</title>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>

<body>


<script>
  function dealerinfo() {
      str= "detinv="+document.getElementById("detinv").value + "&dettype="+document.getElementById("dettype").value;
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 var splitResult = xmlhttp.response.split("/");
                 document.getElementById("detname").value=splitResult[0];
                 document.getElementById("detnum").value=splitResult[1];
                 document.getElementById("detamt").value=splitResult[2];
                 document.getElementById("detser").value=splitResult[3];

            }
        }
        xmlhttp.open("POST", "deallookup.php");
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(str);

    return false;       
  }
</script>


<div class="newboxes"  id="newboxes1">  
<form action="self.php" method="post" id="supplierform1" name="supplierform1">
Type: <input type="text" name="dettype" id="dettype" class="dettype" value = "C" >
<br>
Invoice Number: <input type="text" name="detinv" id="detinv" class="detinv" onblur="dealerinfo();">
<br>
Dealer Name :<input type="text" name="detname" id="detname" class="detname" ">
<br>
Amount:<input type="text" name="detamt" id="detamt" class="detamt" ">
<br>
Serial Number :<input type="text" name="detser" id="detser" class="detser" ">
<br>
Dealer Number:<input type="text" name="detnum" id="detnum" class="detnum" ">
<br>
<input type="submit" name="subbut" value="Submit" id="subbut">
<br><br><br>


</form>
</div>

<div class="newboxes"  id="newboxes2">  
<form action="self.php" method="post" name="supplierform2">
Type: <input type="text" name="dettype" id="dettype" class="dettype" value = "C" >
<br>
Invoice Number: <input type="text" name="detinv" id="detinv" class="detinv" onblur="dealerinfo();">
<br>
Dealer Name :<input type="text" name="detname" id="detname" class="detname" ">
<br>
Amount:<input type="text" name="detamt" id="detamt" class="detamt" ">
<br>
Serial Number :<input type="text" name="detser" id="detser" class="detser" ">
<br>
Dealer Number:<input type="text" name="detnum" id="detnum" class="detnum" ">
<br>
<input type="submit" name="subbut" value="Submit" id="subbut">
<br><br><br>


</form>
</div>


<br>


</body>
</html>

PHP CODE

<?
$db = "SalesView";
include("msiconnect.php");

if($_POST["dettype"]=='C'):
 $sql = "SELECT dba_name, dealer_no, serialno, balancedue from sales where invoiceno = ".$_POST["detinv"]."";
 $result = $link->query($sql);
 $r = $result->fetch_array();
 if($result->num_rows > 0):
  $dealerinfo =$r["dba_name"]."/".$r["dealer_no"]."/".$r["balancedue"]."/".$r["serialno"];
 else:
  $dealerinfo ="Invoice Number not Found";  
 endif;
endif;

if($_POST["dettype"]=='P'):
 $sql = "SELECT dba_name, dealer_no, total from parts where invoiceno = ".$_POST["detinv"]."";
 $result = $link->query($sql);
 $r = $result->fetch_array();
 if($result->num_rows > 0):
  $dealerinfo = $r["dba_name"]."/".$r["dealer_no"]."/".$r["total"];
 else:
  $dealerinfo = "Invoice Number not Found";
 endif;
endif;

echo $dealerinfo;



?>

Thanks I know this alot to look at. I am convinced I need different IDs in my forms however I don't know how to make my once function look for different IDS Maybe something with this.

Thanks

1
  • Without looking at your code, "I don't know how to make my once function look for different IDs" - don't. Use classes instead of IDs. <div class='data-c' ... then you can ref by classname $(".data-c")... to get all matching classes. classnames don't need to be used only for styling, they can also be used to group similar elements or for selection (in this case). Personally, I prefix with data- so that it's clear it's a data indicator, not a style indicator, but that's just preference - doesn't matter what you call the class [this could all be completely irrelevant to your problem...] Commented Dec 16, 2015 at 15:11

1 Answer 1

1

An alternative approach to using classes would be to use document.querySelectorAll to target the field elements by name within the parent form. It's not tested so you might need to tinker with it - but it does remove the need for recurring ids which are not valid.

<script>
    function dealerinfo( event ) {
        var el=typeof(event.target)!='undefined' ? event.target : event.srcElement;
        var parent = el.parentNode;
        var str= "detinv="+parent.querySelectorAll('detinv')[0].value + "&dettype="+parent.querySelectorAll('dettype')[0].value;

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
                cbdealerinfo.call( this, xmlhttp.response, parent );
            }
        }
        xmlhttp.open("POST", "deallookup.php");
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(str);      
    }

    function cbdealerinfo(response,parent){
        /* parent will be the form */
        var splitResult = response.split("/");
        parent.querySelectorAll('detname')[0].value=splitResult[0];
        parent.querySelectorAll('detnum')[0].value=splitResult[1];
        parent.querySelectorAll('detamt')[0].value=splitResult[2];
        parent.querySelectorAll('detser')[0].value=splitResult[3];

        /* call the function to reset the fields */
        resetfields.call( this, parent );
    }

    function resetfields( parent ){
        var col=parent.querySelectorAll('input');
        for( var n in col ) if( col[n] && col[n].nodeType==1 ) col[n].value='';
    }

</script>

In the code sample above, the javascript function is attached as an onblur event handler for a particular ( or series of ) form element. The parent in the original code is the form ( the text input is contained within the form - thus form is the parent. )

If there was a table within the form, like this:

<div class='newboxes'>  
    <form action='self.php' method='post'>
        <table>
            <tr>
                <td>Type:</td>
                <td><input type='text' name='dettype' class='dettype' value = 'C' ></td>
                <td>Invoice Number:</td>
                <td><input type='text' name='detinv' class='detinv' onblur='dealerinfo(event)'></td>
            </tr>
            <tr>
                <td>Dealer Name:</td>
                <td><input type='text' name='detname' class='detname' /></td>
                <td>Amount:</td>
                <td><input type='text' name='detamt' class='detamt' /></td>
            </tr>
            <tr>
                <td>Serial Number:</td>
                <td><input type='text' name='detser' class='detser' /></td>
                <td>Dealer Number:</td>
                <td><input type='text' name='detnum' class='detnum' /></td>
            </tr>
            <tr>
                <td colspan=3>
                    <input type='submit' name='subbut' value='Submit'>
                </td>
            </tr>
        </table>
    </form>
</div>

The parent node is the containing element, which is now a td and it's parent is tr and the parent of the table row is table

table -> tr -> td -> input[type='text']
Great Grandparent -> Grandparent -> Parent -> child

You MIGHT find that you need to also factor in the tbody tag when traversing this html, ie:

table -> tbody -> tr -> td -> input[type='text']
Great Great Grandparent -> Great Grandparent -> Grandparent -> Parent -> Child

So, within the javascript function dealerinfo, rather than var parent = el.parentNode; you would need to go up several parent levels to find the actual table element, something like:

var parent = el.parentNode.parentNode.parentNode;
Sign up to request clarification or add additional context in comments.

16 Comments

Thanks. I am very new to javascript/jquery. So when i run this in debugger mode on IE i get a message saying Unable to get property 'target' of undefined or null reference on the like var el = typeof(event.target) I am wondering what that means. Thanks Ram
ah - I forgot to mention that in the html, when you call the function it should be like this: onblur='dealerinfo(event)'
Thanks what I thought haha. Well that took that error away, now this one.Unable to get property 'value' of undefined or null reference. On the var str. I did take the [0]s away and there were no more errors. However then the program didn't work the way i needed it to. So i am not sure its getting the value its supposed to. Thanks again
What i ended up doing is changing the querySelectorAll('.detinv') placing .s in front of everything and It worked! Thanks so much ram
There is, for each of the elements in each form apart from the submit button and the detinv element, a spare quote which should be removed also. <input type="text" name="detname" id="detname" class="detname" "> should be <input type="text" name="detname" id="detname" class="detname" />
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.