开发者

Where is this extra name/value pair coming from?

I have a form:

  <form id="f3" method="post" action="interface_add.php">
    <fieldset>
    <input onclick="this.value=''" class="te3" type="text" name="f3a" value="title"/>
    <input onclick="this.value=''" class="te3" type="text" name="f3b" value="url"/>
    <a id="f3c" class='but' href="javascript:void(0)" onclick="i3()">Add</a>
    <a id="f3d" class='but' href="j开发者_开发技巧avascript:void(0)" onclick="i3a()">Delete</a>
    </fieldset>
  </form>

and I use some Javsascript to "serialize" the element names and values like this:

function is(a)
  {
  var b='';
  var c=document.forms[a].elements;
  for(i=0;i<c.length;i++)
    {
    if(c[i].type=='checkbox'&&c[i].checked==false)
      {
      b+=c[i].name+"=NULL&";
      }
    else
      {
      b+=c[i].name+"="+c[i].value+"&";
      }
    }
    b=b.slice(0,-1);
  return b;
  }

which I call from here:

function i3()
  {
  var a='';
  a=is('f3');

However the return value I get from is() inserted into 'a' is

"undefined=undefined&f3a=title&f3b=url"

Funny thing is I had a similar problem previously but this was because I was not intializing 'a' which is why I broke this up, mostly out of paranoia that 'a' was not initialized properly.

Probably something simple I overlooked - but why is there undefined=undefined appearing.


It is coming from the <fieldset> element.

Just add a test for a name property inside the loop.

for(i=0;i<c.length;i++) {

    if( c[i].name ) {

       // your code

    }
}


You'd probably like to skip all unnamed elements, like fieldset.

function is(a)
{
    var b='';
    var c=document.forms[a].elements;

    for(i=0;i<c.length;i++)
    {
        if (c[i].name == undefined) continue; // skip all unamed elements

        if (c[i].type == 'checkbox' && c[i].checked == false)
        {
            b += c[i].name + "=NULL&";
        }
        else
        {
            b += c[i].name + "=" + c[i].value + "&";
        }
    }

    b = b.slice(0,-1);

    return b;
}


Rather than using name, you can just get the checkboxes:

if(c[i].type=='checkbox')
  {
  if (c[i].checked==false)
    {
    b+=c[i].name+"=NULL&";
    }
  else
    {
    b+=c[i].name+"="+c[i].value+"&";
    }
  }
}

Of course you could just use submit buttons instead of links and let the form submit itself:

<input name="add" type="submit" value="Add">
<input name="delete" type="submit" value="Delete">

If the user clicks the Add button, a value is sent as ...add=Add..., if they click on the Delete button, then ...delete=Delete... is sent instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜