views:

18

answers:

3

I have a series of fields created dynamically based on database records. They will be named cardObject1, cardObject2, and so on for as many rows as necessary. I'm now trying to access a specific cardObject field in a function where the number is passed in, but am getting an error message.

The field looks like this:

<input name="cardObject241" value="2,$25.00,1" type="hidden">

The js code I'm using looks like this:

function deleteFromCart(id){
  if (confirm("Are you sure you want to delete this item from your cart?")){
    var voucherNbr = document.getElementById("voucherNbr").value;
    var cardObjectArray = document.getElementById("cardObject"+id).value.split();
    var amtToDelete = cardObjectArray[1];
    alert("need to delete " + amtToDelete); 
  }

}

And the error I'm getting is

document.getElementById("cardObject" + id) is null

on this line:

 var cardObjectArray = document.getElementById("cardObject"+id).value.split(); 

How can I get a handle to the cardObject field that ends with the number passed in as the id param?

A: 

You need to add an id="" attribute with the same name as the name attribute.

<input id="cardObject241" name="cardObject241" value="2,$25.00,1" type="hidden">
Jeremy Goodell
Doh! Can't believe I missed that... thanks.
EmmyS
You're welcome.
Jeremy Goodell
A: 

Firstly, your input field needs an id as well as a name, so it would look like this:

<input name="cardObject241" id="cardObject241" value="2,$25.00,1" type="hidden">

Secondly, if you have an object that may or may not exist, it's always a good idea to check for existence before you start manipulating properties:

var tempObj=document.getElementById("cardObject"+id)
if(tempObj) {
    var cardObjectArray = tempObj.value.split();
    ...do your stuff with cardObjectArray....
}
Spudley
A: 

You can use document.getElementsByName() or (cross-browser back to the Stone Age)

document.forms[formIndexOrName].elements["cardObject" + id].value.split(",")
Stan Rogers
Stan, is that you? Domino stan? Hi! It's Esther Strom, former Domino dev. I haven't really been following Lotus blogs recently, but I'm glad to see you're still around!
EmmyS
Yep, that's I. Still alive, but the kicking's mostly involuntary these days. Can't do much but answer the few questions I can still figure out these days (and I've only updated the blog a couple of times a year for the past few years). It's good to see you're still around too -- last I remember there was a bit of a health scare.
Stan Rogers