pass option value as variable for javascript function

  • Thread starter David Shorthouse
  • Start date
D

David Shorthouse

Folks,

I have a drop-down select menu generated server-side. I was hoping to
pass more than a single variable from the option value to a javascript
function. Is this possible? At the moment, my option values consist of three
numbers separated by commas. I thought I could pass these three numbers as
three distinct variables to the javascript function, but it obviously
doesn't work this way.

e.g.

<select name="selectname">
<option value="1,2,3">first selection</option>
etc.
</select>

<input type=button
onclick="dothis(document.form.selectname.options[document.form.selectname.selectedIndex].value)">

can't evidently be used as

<script lang="javascript">
function dothis(a,b,c) {
etc.
}
</script>

Any suggestions?

Dave
 
G

Georg Puchta

You can use custom attributes like this.

<form>
<select name="selectname">
<option value="a,b,c" val1="a" val2="b" val3="c">first
selection</option>
</select>

<input
type="button"
value="Click Me"

onclick="dothis(this.form.selectname.options[this.form.selectname.selectedIndex].getAttribute(
'val1'))">

</form>

You still need the "value" tag since it contains the value that's
submitted.

Cheers,

-Georg
 
G

Georg Puchta

I also should say that the W3C DOM getAttribute() method allows you to
read any attribute from any tag. I haven't checked that on all current
browser versions though.

-Georg
 
L

Lee

David Shorthouse said:
Folks,

I have a drop-down select menu generated server-side. I was hoping to
pass more than a single variable from the option value to a javascript
function. Is this possible? At the moment, my option values consist of three
numbers separated by commas. I thought I could pass these three numbers as
three distinct variables to the javascript function, but it obviously
doesn't work this way.

Nope. A value of "1,2,3" is a string (because it's in quotes).
But you can use a string method to split it into three separate
values:

<html>
<head>
<script type="text/javascript">
function dothis(abc) {
var arg=abc.split(",");
alert("arg[0]="+arg[0]+", arg[1]="+arg[1]+", arg[2]="+arg[2]);
}
</script>
</head>
<body>
<form>
<select name="sel">
<option value="1,2,3">First Three</option>
<option value="4,5,6">Second Three</option>
<option value="7,8,9">Third Three</option>
</select>
<input type="button"
value="dothis"
onclick="dothis(this.form.sel.options[this.form.sel.selectedIndex].value)">
</form>
</body>
</html>


--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top