Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Mixing Javascript & PHP arrays problem

Options
  • 14-03-2007 12:30pm
    #1
    Closed Accounts Posts: 512 ✭✭✭


    I seem to be having a problem with javascript operating on PHP arrays.

    The code is written in PHP. As an example, Ihave 3 text fields on a page like such:
    [PHP]echo("<input type=\"text\" name=\"field[0]\"......>");
    echo("<input type=\"text\" name=\"field[1]\"......>");
    echo("<input type=\"text\" name=\"field[2]\"......>")[/PHP]
    I can then read in the POSTed values at the start of the script like this before performing data validation.
    [PHP]$field = isset($field) ? $field : NULL;[/PHP]
    My problem occurs when I want to reference the field using javascript. I think it is because the field name already contains square brackets.

    For example, I want a button on each field which will set the field value to todays date, So the following code is added to the <input> definition, where todaybutton() is a function that returns today's date.

    [PHP]onclick=\"document.form.field[0].value=todaybutton()"[/PHP]

    This doesn't seem to work properly!

    I can work around by using fieldnames such as 'field0', 'field1' etc... and reference it as onclick=\"document.form.field0.value=todaybutton(), but it requires extra code getting POST values etc.

    Any ideas? Much appreciated!


Comments

  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    Yeah, tis a bit of a collision.

    Try using the ID attribute for Javascript names and the NAME attribute for PHP names, so for e.g.
    [PHP]echo("<input type=\"text\" id=\"field0\" name=\"field[0]\"......>");
    echo("<input type=\"text\" id=\"field1\" name=\"field[1]\"......>");
    echo("<input type=\"text\" id=\"field2\" name=\"field[2]\"......>")[/PHP]

    The you can use the getElementById reference to access the input boxen:
    [HTML]onclick="document.getElementById('field0').value=todaybutton()"[/HTML]

    This should prevent the PHP and Javascript variables from clashing.


  • Closed Accounts Posts: 512 ✭✭✭Drax


    Thanks Seamus - I'll give that a go...


Advertisement