Hafiz Abdullah
Hafiz Abdullah

Reputation: 248

using HTML select tag name in javascript

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>

Upvotes: 0

Views: 292

Answers (3)

Nauphal
Nauphal

Reputation: 6192

try this

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

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

</script>

Upvotes: 0

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17772

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');

Upvotes: 1

RobG
RobG

Reputation: 147553

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];

Upvotes: 1

Related Questions