Forum Moderators: coopster

Message Too Old, No Replies

php arrays in javascript

         

MarquisMark

12:23 am on Feb 24, 2004 (gmt 0)

10+ Year Member



I hope I'm posting this in the right forum. Hopefully someone here will know the answer

I have a forum with checkboxes and the last choice says "Other" and has a text box next to it. Now I want to make the checkbox next to "Other" get checked when someone clicks on the text box. Problem is that the names for the checkboxes have brackets in them so Javascript spits out errors. I've got this to work perfectly with radio buttons since they don't require arrays in PHP.

Sample:


<input type="checkbox" name="ck[]" /> Choice 1
<input type="checkbox" name="ck[]" /> Choice 2
<input type="checkbox" name="ck[]" /> Choice 3
<input type="checkbox" name="ck[]" /> Other <input name="other" onfocus="this.form.[b]ck[][/b][3].checked = true;" />

Is there a way to escape those brackets?

thanks in advance.

Mark

jetboy_70

12:49 am on Feb 24, 2004 (gmt 0)

10+ Year Member



Not sure with checkboxes, but the usual way to access form elements with PHP-style names is to use the Javascript DOM's elements array instead.

document.forms[0].elements['ck[]'].value;

Any help?

coopster

1:48 am on Feb 24, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, MarquisMark!

jetboy_70 is on the money [us2.php.net]. I often use the getElementById() function (yeah, I know it's a radio button, but you get the point) ;) :


<input type="radio" name="name1" id="name1" value="Other"
onclick="document.getElementById('Other').focus()" />
<label for="name1" onclick="document.getElementById('Other').focus()">Other:</label>
<input name="Other" id="Other" type="text" size="5" maxlength="1"
onclick="getElementById('name1').checked = true"
onchange="getElementById('name1').checked = true"
onkeydown="getElementById('name1').checked = true" />

MarquisMark

2:06 am on Feb 24, 2004 (gmt 0)

10+ Year Member



Wow, that was fast. Thanks, both of you.

I ended up using jetboy's solution since I couldn't seem to get the getElementById working inline like that.

On a side note, I also figured out that you're not allowed to have numbers as names of elements. Makes javascript confused.

Thanks again. Still got a lot to learn about DOM.

Mark

coopster

7:46 pm on Feb 24, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



>>I couldn't seem to get the getElementById working inline like that.

You have to have the

id
attribute set on the element you want to get, if that makes sense. In the example shown, the radio button,
name1
has an event handler to throw the focus onto the element with the id of
Other
when the
name1
radio button is clicked.

Also, I have since removed the

onkeydown
event handler in this particular case because a tab will cause the 'Other' input text box to receive focus when we really don't want it to. The
onkeydown
is unnecessary in this case, don't use it.