Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

looping through form elements using get

Status
Not open for further replies.

travisbrown

Technical User
Joined
Dec 31, 2001
Messages
1,016
I'm playing around with this script, trying to do two things:

1. get the js function to pick up form elements inside spans or divs. If you try the code below, you will notice that it returns abc and def, but not ghi unless you remove the <span>

2. trigger the form action with a button outside the form

note: get.asp is just response.writing the form values. PHP would be
<?
print_r($_GET);
?>

Code:
<script type="text/javascript" language="javascript">
   var http_request = false;
   function makeRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      http_request.open('GET', url + parameters, true);
      http_request.send(null);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   
   function get(obj) {
      var getstr = "?";
      for (i=0; i<obj.childNodes.length; i++) {
         if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
               getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
            }
            if (obj.childNodes[i].type == "checkbox") {
               if (obj.childNodes[i].checked) {
                  getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
               } else {
                  getstr += obj.childNodes[i].name + "=&";
               }
            }
            if (obj.childNodes[i].type == "radio") {
               if (obj.childNodes[i].checked) {
                  getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
               }
            }
         }   
         if (obj.childNodes[i].tagName == "SELECT") {
            var sel = obj.childNodes[i];
            getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
         }
		 if (obj.childNodes[i].tagName == "TEXTAREA") {
            getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
         }
		 
         
      }
      makeRequest('get.asp', getstr);
   }
</script>

<form action="javascript:get(document.getElementByName('myform'));" name="myform" id="myform">
 <input type="text" name="abc" value="" />
 <textarea name="def"></textarea>
 
 
  <!-- BEGIN ITEM -->
<span>
    <input name="ghi" type="text" class="order" />
    </span>
  
  <input type="button" name="button" value="Submit" 
   onclick="javascript:get(this.parentNode);">
</form>
<br>
<br>
Server-Response:<br>
<span name="myspan" id="myspan"></span>
 
1. ghi is not a childNode of the form - it's a descendant. You should either remove the span, or change the way you're picking up your elements.

2. This should work:

Code:
<input type="button" onclick="get(document.forms['myform']);" value="Do it">

Hope this helps,
Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
hmm. Is there a way to scan through all the elements regardless of heritage? This is frontier-land for me.

I thought something like the submit method you suggeted would work too. I had already tried:

<img src="a.gif" onclick="get(document.forms[0]);" /> but to no avail


What am I doing wrong here?
Code:
  <input type="button" name="button" value="Submit" 
   onclick="javascript:get(this.parentNode);">
</form>
<input type="button" onclick="get(document.forms['myform']);" value="Do it">
 
[1]>[tt]action="javascript:get(document.getElementByName('myform'));"[/tt]
Either this...
[tt]action="javascript:get(document.getElement[red]s[/red]ByName('myform')[red][0][/red]);" [/tt]
or simply this?
[tt]action="javascript:get([blue]this[/blue]);" [/tt]

[2]>you will notice that it returns abc and def, but not ghi unless you remove the <span>
Use loop on getElementsByTagName("input") to start the loop for text, radio, checkbox. Use additionally loops with getElementsByTagName("textarea") and getElementsByTagName("select") for these two input elements. Then you do not have to worry the deep tree structure of form fields being embedded.

 
Dan, I'm trying to trigger the form action from outside the form. I thought something like you suggested would work and I'd already tried something similar, but in both cases it didn't do anything when I implemented it like I demonstrated above in post three. No error, no response.

I'm trying to do somethign like this:

Code:
<form...>
</form>
<input type="button" onclick="get(document.forms['myform']);" value="Do it">

Tsuji, looping through elements by tagname rather than childnode makes sense. would you mind giving me sample syntax to get started?
 
I just edit your function using that approach.
[tt]
function get(obj) { //obj being the form object
var getstr = "?";
var celem;
celem=obj.getElementsByTagName("input");
for (i=0; i<celem.length; i++) {
if (celem.type.toLowerCase() == "text") {
getstr += celem.name + "=" + celem.value + "&";
}
if (celem.type.toLowerCase() == "checkbox") {
if (celem.checked) {
getstr += celem.name + "=" + celem.value + "&";
} else {
getstr += celem.name + "=&";
}

if (celem.type.toLowerCase() == "radio") {
if (celem.checked) {
getstr += celem.name + "=" + celem.value + "&";
}
}
}
celem=obj.getElementsByTagName("select");
for (var i=0;i<celem.length;i++) {
getstr += celem.name + "=" + celem.value + "&";
}
celem=obj.getElementsByTagName("textarea");
for (var i=0;i<celem.length;i++) {
getstr += celem.name + "=" + celem.value + "&";
}
makeRequest('get.asp', getstr);
}
[/tt]
(ps: I just edit it in the box, check for typos and alignment and open-close paring. Also at the glance of the last moment, you have to take care of the last &. Use substring function to get rid of it.)
 
Thanks. I don't think the trailing ampersand will hurt; I often see them in querystrings, but for the sake of tidiness...

How would you call this then? I'm getting an "object expected" on this line, regardless of whether it is in or out of the form. I think this is what i want to be doing.

<input type="button" name="button" value="Submit" onclick="javascript:get(document.forms['myform']);">



Here's what I have now
Code:
<script type="text/javascript" language="javascript">
   var http_request = false;
   function makeRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      http_request.open('GET', url + parameters, true);
      http_request.send(null);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   
   function get(obj) {    //obj being the form object
      var getstr = "?";
      var celem;
      celem=obj.getElementsByTagName("input");
      for (i=0; i<celem.length; i++) {
        if (celem[i].type.toLowerCase() == "text") {
           getstr += celem[i].name + "=" + celem[i].value + "&";
        }
        if (celem[i].type.toLowerCase() == "checkbox") {
           if (celem[i].checked) {
              getstr += celem[i].name + "=" + celem[i].value + "&";
           } else {
              getstr += celem[i].name + "=&";
        }
        
        if (celem[i].type.toLowerCase() == "radio") {
           if (celem[i].checked) {
              getstr += celem[i].name + "=" + celem[i].value + "&";
           }
        }
      }
      celem=obj.getElementsByTagName("select");
      for (var i=0;i<celem.length;i++) {
          getstr += celem[i].name + "=" + celem[i].value + "&";
      }
      celem=obj.getElementsByTagName("textarea");
      for (var i=0;i<celem.length;i++) { 
         getstr += celem[i].name + "=" + celem[i].value + "&";
      }
      makeRequest('get.asp', getstr);
   }
</script>

<form action="javascript:get(document.getElementByName('myform'));" name="myform" id="myform">
  <input type="text" name="abc" value="" />
  <textarea name="def"></textarea>
  <!-- BEGIN ITEM -->
  <span>
  <input name="ghi" type="text" class="order" />
  </span>
</form>
<input type="button" name="button" value="Submit" 
   onclick="javascript:get(document.forms['myform']);">
<br>
<br>
Server-Response:<br>
<span name="myspan" id="myspan"></span>
 
[1] You action is still wrong syntactically. I pointed out and I am not going to change my statement as far as the syntax is concerned. getElementsByName with an "s" and return is a collection.

[2] Outside of form, you don't use <input> type button. Use <button> directly with onclick handler.
>[tt]<input type="button" name="button" value="Submit"
onclick="javascript:get(document.forms['myform']);">
[/tt]
[tt]<button value="Submit" onclick="get(document.forms['myform']);">Submit</button>[/tt]

 
Dan, you mean something like this, just to see if the alert gets triggered? Yes, I'd done that and the function wasn't called. Sorry, I'm holding onto js by my fingernails. I hardly ever get the opportunity with client-side scripting.

function get(obj) { //obj being the form object
alert('test');
var getstr = "?";

It isn't calling now, but I've switched the function to tsuji's code and now getting an object expected error.
 
Sorry guys. I feel daft. Tsuji, I'd seen your point about getElementsByName, with the 's'. I must have ctrl-Z'd my way back to what I had before. I had tried javascript:get(this);. But, is the form action triggered if I'm using the external button to trigger the function? I was thinking it bypassed the form action when using <button value="Submit" onclick="get(document.forms['myform']);">Submit</button>. Mind you, I barely know what I'm talking about.

This is what I have and getting an object expected error on both buttons. Tsuji, I don't understand what you mean when you say '...and return is a collection'. Do I need to do something like action="return javascript:get(document...? I think I'm misunderstanding.

Code:
<form action="javascript:get(document.getElementsByName('myform')[0]);" name="myform" id="myform">
  <input type="text" name="abc" value="" />
  <textarea name="def"></textarea>
  <span>
  <input name="ghi" type="text" class="order" />
  </span>
  <input type="submit" value="Submit" onclick="get(document.forms['myform']);">
</form>
<button value="Submit" onclick="get(document.forms['myform']);">Submit</button>
<br>
<br>
Server-Response:<br>
<span name="myspan" id="myspan"></span>


 
I suggest you download and install Firefox. Its JavaScript console gives pretty meaningful errors, and shows imemdiately why your code isn't working (you have a missing closing brace in your "get" function).

Hope this helps,
Dan



[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Finally got back to my office where I had Firefox and found missing }. The client environment I was in is IE only. Can't do user installs without admin rights.

I thought this would aggregate form items by name, but seems to only take the first of any type. Of the "text" inputs, it only sends "abc", not "ghi" as well. Do we have to loop through each name for each type?

Obviously I have no idea what I'm doing, but something like??
Code:
for (a=0; a<obj.getElementsByName.length; a++) {
           getstr += celem[i].name[a] + "=" + celem[i].value[a] + "&";}

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
	<title>Untitled</title>
	<meta name="generator" content="BBEdit 8.2" />
	<script type="text/javascript" language="JavaScript">
	var http_request = false;
   function makeRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      http_request.open('GET', url + parameters, true);
      http_request.send(null);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
	 function get(obj) {    //obj being the form object
      var getstr = "?";
      var celem;
      celem=obj.getElementsByTagName("input");
      for (i=0; i<celem.length; i++) {
        if (celem[i].type.toLowerCase() == "text") {
           getstr += celem[i].name + "=" + celem[i].value + "&";
        }
        if (celem[i].type.toLowerCase() == "checkbox") {
           if (celem[i].checked) {
              getstr += celem[i].name + "=" + celem[i].value + "&";
           } else {
              getstr += celem[i].name + "=&";
        }
        
        if (celem[i].type.toLowerCase() == "radio") {
           if (celem[i].checked) {
              getstr += celem[i].name + "=" + celem[i].value + "&";
           }
        }
      }
      celem=obj.getElementsByTagName("select");
      for (var i=0;i<celem.length;i++) {
          getstr += celem[i].name + "=" + celem[i].value + "&";
      }
      celem=obj.getElementsByTagName("textarea");
      for (var i=0;i<celem.length;i++) { 
         getstr += celem[i].name + "=" + celem[i].value + "&";
      }
      makeRequest('get.asp', getstr);
   }
}
</script>
</head>
<body>

<form action="javascript:get(document.getElementsByName('myform')[0]);" name="myform" id="myform">
<fieldset>
<input type="text" name="abc" value="" /> 
<input  type="text" name="ghi" value="" />
  <textarea name="def"></textarea>
  <input type="submit" value="Submit" onclick="get(document.forms['myform']);" />
</fieldset>
</form>
<button value="Submit" onclick="get(document.forms['myform']);">Submit</button>

<span name="myspan" id="myspan"></span>

</body>
</html>
 
You're calling getElementsByName, but not giving the name you want to get:

Code:
for (a=0; a<obj.getElementsByName[!]('someName')[/!].length; a++)

Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Of course, you'd be better off with:

Code:
var tempEls = obj.getElementsByName('someName');
for (var a=0; a<tempEls.length; a++)

as it won't have to do the getElementsByName call for each iteration of the loop.

Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Okay. Makes sense. I don't think I conveyed my meaning all that well through the pseudo-syntax. I don't know all the object names. The form names/ids are generated from keys of a database loop. What I was trying to get at was do I have to loop through the names collection for each object type?

Loop a collection of names for each type
typenames = obj.getElementsByName[j];
for...

Is this getting too convoluted? Is there a better way to create a collection of all the named elements in a form?
 
If all you want to do is get all form elements with a certain name, use:

Code:
formObj.getElementsByName('elName');

if you want to get all form elements with a ceratin tag type, you would use:

Code:
formObj.getElementsByTagName('tagName');

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top