开发者

Why am I getting "undefined" when I call .options on my select box?

I am trying to follow this tutorial (http://railscasts.com/episodes/88-dynamic-select-menus) to get dynamic select boxes working with RoR. No need to worry about the RoR bit, this is a Javascript specific question.

Every time this function runs I get the error that the "options" is undefined. I've tried running the command manually in the console, but regardless, it spits out undefined. I have it typed exactly as I see it in the tutorial, but somehow it's not working for me...

Here's the javascript in question:

function clientSelected() {
var client_id = $('#piece_client_id').val();
// THIS IS THE PROBLEM LINE 
var options = $('piece_campaign_id').options;
options.length = 0;
ca开发者_JAVA百科mpaigns.each(function(campaign) {
    if (campaign[0] == client_id) {
        options[options.length] = new Option(campaign[1], campaign[2]);
    }
});
if (options.length == 1) {
  $('campaign_field').hide();
} else {
  $('campaign_field').show();
}
}

Here is the HTML that it's trying to work on:

<select id="piece_campaign_id" name="piece[campaign_id]"><option value=""></option> 
<option value="1">Feed The Dogs</option> 
<option value="2">Watch Television</option> 
<option value="3">End The Suffering</option> 
<option value="4">Brian Bilbrey</option> 
<option value="5">SummerHill Homes / Yes on A&amp;B</option>
</select> 

Thanks a bunch for taking a look! Let me know if there's anything else I can add to make my question more clear.


Try:

var options = $('#piece_campaign_id').get(0).options;

or

var options = $('#piece_campaign_id')[0].options;

As you were using a jQuery object, which doesn't have an options property. Also, make sure to include the id selector (#).


The following code in is not accurate.

 var options = $('piece_campaign_id').options;

Should be

 var options = $('#piece_campaign_id')[0].options;

You will notice two changes.

  1. The addition of the # in the selector
  2. The addition of the [0] after the jQuery object.

In jQuery to select an element by an ID you need to append # before the idvalue (which is similar to CSS. Here is some reference http://api.jquery.com/id-selector/

The next issue was you were trying to access a property that does not exist on a jQuery object. options is an HTML DOM property. Because of this you must access the DOM Object from inside the jQuery Object.

var options = $('#piece_campaign_id') //Returns jQuery Object

var options = $('#piece_campaign_id')[0] //Returns HTML DOM Object
//The line above will return the same as
var options = document.getElementById('piece_campaign_id')

NOTE

The following Selectors in your code are most likely inaccurate

  $('campaign_field').hide();
  ...
  $('campaign_field').show();


$('piece_campaign_id')

needs to be

$('#piece_campaign_id')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜