Array of form elements javascript problem

Discussion in 'JavaScript' started by Lucky Bastard, Jan 26, 2006.

  1. #1
    Why would this cause problems (in Firefox, haven't checked IE):
    onClick="javascript:document.checkout.message[0].disabled=false;"

    however
    onClick="javascript:document.checkout.message_0.disabled=false;" works.

    I want the fields to be named .message[0] ...... message[10] for server side reasons.

    Can anyone re-work the first javascript to make it work with [0] etc?
     
    Lucky Bastard, Jan 26, 2006 IP
  2. Lucky Bastard

    Lucky Bastard Peon

    Messages:
    406
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Anyone????
     
    Lucky Bastard, Jan 27, 2006 IP
  3. Sham

    Sham Peon

    Messages:
    136
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    try something like:

    give your form elements ID properties too (i.e. id="message[0]")

    then you can use

    document.getElementByID('message[0]').disabled=false;
     
    Sham, Jan 28, 2006 IP
  4. torunforever

    torunforever Peon

    Messages:
    414
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Sham, I think you're on the right track, but my recommendation to Lucky Bastard is instead of setting id="message[0]", set name="message[0]" and set the id to a name without the brackets.

    Basically, the PHP requirement here is that the name have the brackets to signify an array.

    The javascript requirement is that it'll mess things up if you try to reference an id or name with brackets, because it thinks it's a javascript array. So the thing you're referencing in javascript (the id) should have no brackets.
     
    torunforever, Jan 28, 2006 IP
  5. Sham

    Sham Peon

    Messages:
    136
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    It should be ok when using getElementById since its a string literal, but yeh, it would make more sense to have something obvious like id="formElement1"
     
    Sham, Jan 28, 2006 IP
  6. torunforever

    torunforever Peon

    Messages:
    414
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Sham,

    I was off base about it causing a problem with the javascript to have brackets in the id and referencing it with getElementById, but the html doesn't validate if you run it through the W3's validator.
    character "[" is not allowed in the value of attribute "id"

    However, browsers don't seem to mind. I tried it in IE and Firefox and the id didn't cause problems.
     
    torunforever, Jan 28, 2006 IP
  7. Lucky Bastard

    Lucky Bastard Peon

    Messages:
    406
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Thanks guys, will give it a go tomorrow.
     
    Lucky Bastard, Jan 29, 2006 IP