/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] assigning method to prototype ‘Select’

Hi all,

I have a function that takes an array as a parameter and assigns the names/values in that array to the [I]options [/I] of a [I]select [/I]element.

Ideally, I would make that function a method of the [I]Select.prototype[/I], but my code errors during that assignment. I am able to assign to the [I]Object.prototype[/I] with no problems. I would [I]prefer [/I] to assign to the [I]Select.prototype[/I] ’cause that makes more intuitive sense…

Question:

There is NO constructor for the [I]Select[/I] object and I suspect that this is why I cannot assign to the prototype. True? If true, then [I]why[/I] is there no constructor for the [I]Select[/I] object?

[CODE]<html>
<head>
<title>Test</title>
<script type=”text/javascript”>
var newOpts = [
{name:”dog”,value:”lazy”},
{name:”cat”,value:”smug”},
{name:”fish”,value:”boring”}];

function setOpts( a ) {
if ( this.type.match(/^select/i) )
{
var a = arguments[0];
this.options.length = 0;
for ( var i=0; i < a.length; i++ )
{
this.options[i] = new Option(a[i].name, a[i].value);
}
}
}

// Does NOT work
//Select.prototype.setOptions = setOpts;

// Does work
Object.prototype.setOptions = setOpts;
</script>
</head>
<body>
<a href=”javascript:document.getElementById(‘oppy’).setOptions(newOpts);”>change select</a><br />
<form>
<select id=”oppy” name=”choice”>
<option value=”1″>one</option>
<option value=”2″>two</option>
<option value=”3″>three</option>
</select>
<input type=”submit” value=”submit” />
</form>
</body>
</html>[/CODE]

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@beef23authorMar 05.2006 — All,

It turns out that there [I]is [/I]a constructor -- called [B]HTMLSelectElement[/B]

when i change my code to:

[CODE]HTMLSelectElement.prototype.setOptions = setOpts[/CODE]

this works as expected...
×

Success!

Help @beef23 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...