0

I have an array which I used in the tag name :

<?php 

  echo "<td><select name='search[$field]'></select>"

?>

but how do I write the name in Javascript?

For example

<script language="javascript" type="text/javascript">

document.formname.---.options.length = 0;

</script>

How should I write in the "---" ?

Is it something like this?

<script language="javascript" type="text/javascript">

document.formname.search[$field].options.length = 0;

</script>
3
  • document.formname['search[$field]'].options.length = 0; Commented Apr 19, 2012 at 3:46
  • ya know, language="javascript" has not been require to use for almost 10 years now .. you might look into the age or quality of your tutorial. Commented Apr 19, 2012 at 5:03
  • The language attribute has been deprecated since HTML 4, so yeah, worth removing. Commented Apr 19, 2012 at 7:09

3 Answers 3

1

Where the name of a form control isn't a valid identifier, Use square bracket notation:

document.formname.elements['search[$field]'].options.length = 0;

Note that the full, formal method is:

document.forms['formName'].elements['elementName'].options.length = 0;

However each is made a named property of its "parent" so where the names are all valid identifiers:

document.formName.elementName;

works, and where they aren't:

document['formName']['elementName'];

will do the trick. Also use square brackets where the names are held in variables:

var fn = 'form[Name]';

can be used as:

var theForm = document[fn];

or

var theForm = document.forms[fn];
Sign up to request clarification or add additional context in comments.

2 Comments

$field is a PHP evaluated variable, not a string!
Just reflecting the OP's code. If server sdie code is posted, the answer should probably reflect that. It's irrelevant to the answer anyway - the "[" and "]" characters are illegal in javascript identifiers so must be used with square bracket notation, the "$" character isn't.
1

Give the select elemenent an id and use it to reference the element:

<?php 
  echo "<td><select name='search[$field]' id='mySelect'></select>"
?>

<script>
var select =  document.getElementById('mySelect');

2 Comments

Form controls must have a name to be sucessful, otherwise they aren't submitted with the form.
But you don't need an id, you can select the element using the name that it must already have. If you must have a name, it is a lot more convenient to set set the name and id to the same value.
0

try this

<script language="javascript" type="text/javascript">

document.formname.search[<?php echo $field; ?>].options.length = 0;

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.