bluefiredragon
bluefiredragon

Reputation: 55

Adding drop-down list options to a price calculator using JavaScript / jQuery

I have a problem with my price calculator when I've tried to add options. (jsFiddle here = http://jsfiddle.net/wemdragon/ZG8m)

What I'm trying to do is where it says:

var firstoption=$('select#myselect')

I would like the options' value turned into the price value but I can't seem to do it. It works in my shopping cart but not in the JavaScript.

Maybe I'm trying to add the value in the wrong place, I don't know what's going wrong.

Upvotes: 0

Views: 880

Answers (1)

veeTrain
veeTrain

Reputation: 2915

Your select id (at least in the fiddle) was camelCased as mySelect but you were trying to access the id #myselect. This should look like the following unless you change your markup's id:

var firstoption = $('select#mySelect');

I also noticed that you specified a default value of 0 for not selecting an option. For some reason, !firstoption.val(), when the val() was zero, returns false instead of true like your if statement seemed to be expecting. !0 is apparently true in this instance.

I changed the logic to match your mark-up and it seemed to behave like you might have expected or want:

if (firstoption.val() == 0) {
    error.html('Please include an option!');
    firstoption.focus();
}

Edit Updated fiddle: http://jsfiddle.net/ZG8mv/8/

Now the focus() executions will show in the order that they are wrong. I.e., if there is no width and no option specified, that box will receive focus. Previously, the option message would trump the other two.

Upvotes: 2

Related Questions