User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the JavaScript / DHTML / AJAX section within the Web Development category of DaniWeb, a massive community of 426,589 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 1,708 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our JavaScript / DHTML / AJAX advertiser: Lunarpages Web Hosting
Views: 2616 | Replies: 17 | Solved
Reply
Join Date: Jun 2006
Location: India
Posts: 6,858
Reputation: ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold 
Rep Power: 23
Solved Threads: 344
Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Lazy, Useless & Apathetic

Re: how to change name attributes with Javascript

  #11  
Jul 10th, 2008
Originally Posted by jakesee View Post
I need to change the names to

hobby[0], hobby[1], hobby[2], hobby[3] ...

so that I can pass POST the values to a PHP script...

Maybe something along the lines of the following snippet. Rigorous error checking omitted for brevity.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example</title>
    <script type="text/javascript">
    /**
     *  Dynamically create form elements with incremental names.
     *
     *  @param tableId The ID of the table element.
     *  @param elemName The name of the element to be dynamically created.
     */
    function addRow(tableId, elemName) {
      if(!tableId || !elemName) return;
      
      // Grab hold of a reference to the table element and return from the 
      // function if no table element exists for the given table id.
      var tblElem = document.getElementById(tableId);
      if(!tblElem)  return;
      
      // Insert a new row at the end of the table, a new cell at the start
      // of that row and a new text node to the newly created cell.
      var newRow = tblElem.insertRow(-1);
      var newCell = newRow.insertCell(0);
      var txtElem = document.createElement("INPUT");
      txtElem.name = elemName + "[" + (tblElem.rows.length - 1) + "]";
      newCell.appendChild(txtElem);
      
      alert(document.getElementsByTagName("BODY")[0].innerHTML);
    }
    </script>
</head>
<body>
  <form id="frm" name="frm" action="#">
    <table id="tbl">
    <tbody>
      <tr id="dolly">
        <td><input name="hobby[0]"></td>
      </tr>
    </tbody>
    </table>
    <div>
      <input type="button" value="Append" onclick="addRow('tbl', 'hobby');">
      <br>
      <input type="submit">
    </div>
  </form>
</body>
</html>
I don't accept change. I don't deserve to live.

Happiness corrupts people.

Failing to value the lives of others cheapens your own.
Reply With Quote  
Join Date: Aug 2006
Location: Noida, India
Posts: 158
Reputation: Luckychap is an unknown quantity at this point 
Rep Power: 3
Solved Threads: 17
Luckychap's Avatar
Luckychap Luckychap is offline Offline
Junior Poster

Re: how to change name attributes with Javascript

  #12  
Jul 10th, 2008
Above code is working fine on FF but on IE7 name attribute is not set at all.
I had modified the above code to work on both the browsers.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example</title>
    <script type="text/javascript">
    /**
     *  Dynamically create form elements with incremental names.
     *
     *  @param tableId The ID of the table element.
     *  @param elemName The name of the element to be dynamically created.
     */
    function addRow(tableId, elemName) {
      if(!tableId || !elemName) return;
      
      // Grab hold of a reference to the table element and return from the 
      // function if no table element exists for the given table id.
      var tblElem = document.getElementById(tableId);
      if(!tblElem)  return;
      
      // Insert a new row at the end of the table, a new cell at the start
      // of that row and a new text node to the newly created cell.
      var newRow = tblElem.insertRow(-1);
      var newCell = newRow.insertCell(0);
      //var txtElem = document.createElement("INPUT");
      
      //newCell.appendChild(txtElem);
	newCell.innerHTML = "<input type='text' name='" + elemName + "[" + (tblElem.rows.length - 1) + "]'" + ">";
      
      alert(document.getElementsByTagName("BODY")[0].innerHTML);
    }
    </script>
</head>
<body>
  <form id="frm" name="frm" action="#">
    <table id="tbl">
    <tbody>
      <tr id="dolly">
        <td><input name="hobby[0]"></td>
      </tr>
    </tbody>
    </table>
    <div>
      <input type="button" value="Append" onclick="addRow('tbl', 'hobby');">
      <br>
      <input type="submit">
    </div>
  </form>
</body>
</html>
Last edited by Luckychap : Jul 10th, 2008 at 2:16 pm.
When you think you have done a lot, then be ready for YOUR downfall.
Reply With Quote  
Join Date: Jun 2006
Location: India
Posts: 6,858
Reputation: ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold 
Rep Power: 23
Solved Threads: 344
Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Lazy, Useless & Apathetic

Re: how to change name attributes with Javascript

  #13  
Jul 10th, 2008
> Above code is working fine on FF but on IE7 name attribute is not set at all.

Just because the 'NAME' attribute is not shown in the alert doesn't mean that it is not set. Try to submit the form and take a look at the submitted query string i.e. the URL, it still submits the newly created form fields. Likewise the code works perfectly fine on the recent version of Opera.
I don't accept change. I don't deserve to live.

Happiness corrupts people.

Failing to value the lives of others cheapens your own.
Reply With Quote  
Join Date: Jul 2008
Posts: 33
Reputation: jakesee is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 1
jakesee jakesee is offline Offline
Light Poster

Re: how to change name attributes with Javascript

  #14  
Jul 11th, 2008
Originally Posted by ~s.o.s~ View Post
Maybe something along the lines of the following snippet. Rigorous error checking omitted for brevity.


That was finer than my original addRow code! I added another function and a button to illustrate my problem.

function TryToGetName(tableId)
{
    var tblElem = document.getElementById(tableId);
    if(!tblElem)  return;
    
    // this is correct, with 3 buttons
    alert("total <inputs> = " + (document.getElementsByTagName("INPUT").length - 3));

    for(var i = 0; i < tblElem.rows.length; i++)
    {
        var hobby = document.getElementsByName("hobby[" + i + "]")[0];
  
        // But suppose I want to do validation and
        // value formatting with hobby.value,
        // IE will give a problem here.
       alert("hobbies["+i+"].value = " + hobby.value);
     }
}


The full version:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example</title>
    <script type="text/javascript">
    /**
     *  Dynamically create form elements with incremental names.
     *
     *  @param tableId The ID of the table element.
     *  @param elemName The name of the element to be dynamically created.
     */
    function addRow(tableId, elemName) {
      if(!tableId || !elemName) return;
      
      // Grab hold of a reference to the table element and return from the 
      // function if no table element exists for the given table id.
      var tblElem = document.getElementById(tableId);
      if(!tblElem)  return;
      
      // Insert a new row at the end of the table, a new cell at the start
      // of that row and a new text node to the newly created cell.
      var newRow = tblElem.insertRow(-1);
      var newCell = newRow.insertCell(0);
      var txtElem = document.createElement("INPUT");
      txtElem.name = elemName + "[" + (tblElem.rows.length - 1) + "]";
      newCell.appendChild(txtElem);
      
      alert(document.getElementsByTagName("BODY")[0].innerHTML);
    }
    
function TryToGetName(tableId)
{
    var tblElem = document.getElementById(tableId);
    if(!tblElem)  return;
    
    // this is correct, with 3 buttons
    alert("total <inputs> = " + (document.getElementsByTagName("INPUT").length - 3));

    for(var i = 0; i < tblElem.rows.length; i++)
    {
        var hobby = document.getElementsByName("hobby[" + i + "]")[0];
  
        // But suppose I want to do validation and
        // value formatting with hobby.value,
        // IE will give a problem here.
       alert("hobbies["+i+"].value = " + hobby.value);
     }
}

    </script>
</head>
<body>
  <form id="frm" name="frm" action="#">
    <table id="tbl">
    <tbody>
      <tr id="dolly">
        <td><input name="hobby[0]"></td>
      </tr>
    </tbody>
    </table>
    <div>
      <input type="button" value="Append" onclick="addRow('tbl', 'hobby');">
      <br>
      <input type="button" value="getElementsByName('hobby[x]')" onclick="TryToGetName('tbl');">
      <br>
      <input type="submit">
      <br>
      
    </div>
  </form>
</body>
</html>
Last edited by jakesee : Jul 11th, 2008 at 2:43 am.
Reply With Quote  
Join Date: Jun 2006
Location: India
Posts: 6,858
Reputation: ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold 
Rep Power: 23
Solved Threads: 344
Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Lazy, Useless & Apathetic

Re: how to change name attributes with Javascript

  #15  
Jul 12th, 2008
The getElementsByName seems to be flawed when working with dynamically added elements in IE. I guess adding elements by using innerHTML is the only way of making IE aware of the existence of new elements.

Anyways, try something simple like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example</title>
    <script type="text/javascript">
    /**
     *  Dynamically create form elements with incremental names.
     *
     *  @param tableId The ID of the table element.
     *  @param elemName The name of the element to be dynamically created.
     */
    function addRow(tableId, elemName) {
      if(!tableId || !elemName) return;
      
      // Grab hold of a reference to the table element and return from the 
      // function if no table element exists for the given table id.
      var tblElem = document.getElementById(tableId);
      if(!tblElem)  return;
      
      // Insert a new row at the end of the table, a new cell at the start
      // of that row and a new text node to the newly created cell.
      var newRow = tblElem.insertRow(-1);
      var newCell = newRow.insertCell(0);
      var txtElem = document.createElement("INPUT");
      txtElem.name = elemName + "[" + (tblElem.rows.length - 1) + "]";
      newCell.appendChild(txtElem);
    }
    
    function getElementsThatStartWith(frmObj, str) {
      if(!str || !frmObj)  return;
      var elems = frmObj.elements, returnElems = [];
      for(var i = 0, maxI = elems.length; i < maxI; ++i) {
        var elem = elems[i];
        if(elem.name.indexOf(str) == 0) {
          returnElems[returnElems.length] = elem;
        }
      }
      return(returnElems);
    }
    
    function validateHobbies(frmObj) {
      var elems = getElementsThatStartWith(frmObj, "hobby");
      for(var i = 0, maxI = elems.length; i < maxI; ++i) {
        var elem = elems[i];
        alert(elem.name + ": " + elem.value);
      }
    }
    </script>
</head>
<body>
  <form id="frm" name="frm" action="#">
    <table id="tbl">
    <tbody>
      <tr id="dolly">
        <td><input name="hobby[0]"></td>
      </tr>
    </tbody>
    </table>
    <div>
      <input type="button" value="Append" onclick="addRow('tbl', 'hobby');">
      <br><br>
      <input type="button" value="Get All Hobbies" onclick="validateHobbies(this.form);">
      <br><br>
      <input type="submit">
    </div>
  </form>
</body>
</html>
I don't accept change. I don't deserve to live.

Happiness corrupts people.

Failing to value the lives of others cheapens your own.
Reply With Quote  
Join Date: Jul 2008
Posts: 33
Reputation: jakesee is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 1
jakesee jakesee is offline Offline
Light Poster

Re: how to change name attributes with Javascript

  #16  
Jul 12th, 2008
Thanks to everyone with the help and especially SOS for the neater code suggestions. I think i can solve my problems from here on already.

anyway, nice efficient for loop here:

Originally Posted by ~s.o.s~ View Post
for(var i = 0, maxI = elems.length; i < maxI; ++i) { ... }
Reply With Quote  
Join Date: Jul 2008
Posts: 1
Reputation: michalsrodek is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
michalsrodek michalsrodek is offline Offline
Newbie Poster

Re: how to change name attributes with Javascript

  #17  
Jul 22nd, 2008
I dont understand you guys. There is a easier way to send array of elements.
Check this out:
<input name="something[]" />
<input name="something[]" />
<input name="something[]" />
And now to add/delete elements you can set id parametr. It works in IE/Fx very well.
Reply With Quote  
Join Date: Jul 2008
Posts: 33
Reputation: jakesee is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 1
jakesee jakesee is offline Offline
Light Poster

Re: how to change name attributes with Javascript

  #18  
Jul 22nd, 2008
Originally Posted by michalsrodek View Post
I dont understand you guys. There is a easier way to send array of elements.
Check this out:
<input name="something[]" />
<input name="something[]" />
<input name="something[]" />
And now to add/delete elements you can set id parametr. It works in IE/Fx very well.


In any case, your method is indeed clever, which I just learnt recently. But the problem is illustrated below:

<script type="text/javascript">
function AddRow()
{
  var hobby = document.getElementsByName('hobby[]');
  alert(hobby.length);
  
  var formObj = document.getElementById('form_form');
  var i = document.createElement("input");
  i.name = "hobby[]";
  formObj.appendChild(i);
  
  // doesn't work in IE when it should
  var hobby = document.getElementsByName('hobby[]');
  alert(hobby.length);
  hobby[hobby.length - 1].value = "I am the latest input box";
  // this makes validation problematic
}
</script>

<form id="form_form" method="POST">
<input type="button" value="Add Row" onclick="AddRow();" />
<input type="submit" value="submit" />
<input type="text" name="hobby[]" />
</form>
Last edited by jakesee : Jul 22nd, 2008 at 11:46 am.
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb JavaScript / DHTML / AJAX Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the JavaScript / DHTML / AJAX Forum

All times are GMT -4. The time now is 10:37 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC