Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Mixing Javascript & PHP arrays problem

  • 14-03-2007 12:30PM
    #1
    Closed Accounts Posts: 511 ✭✭✭


    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, Registered Users 2 Posts: 68,173 ✭✭✭✭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: 511 ✭✭✭Drax


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


Advertisement