0

I want to add an argument of a function to a string (iam not sure if thats the right word)

function changeChart(form, chart, bar) {

            //chart 2 (left)
            $(form).change(function (){

                console.log(form);

                $(form + "option:selected").each(function(){
                //rest of the function

I want the form added to the selection in Jquery.

Is this the right way?

2
  • Are you having trouble doing this? Commented Nov 30, 2012 at 17:04
  • 2
    What does form look like? Is it the actual object, such as $('#myForm'), or is it a string representation of the selector, such as #myForm? Commented Nov 30, 2012 at 17:04

2 Answers 2

4

If form is a string, you need to be sure there's a space before "option:selected".

$(form + " option:selected").each(function(){

If form is an element, pass it to the jQuery functin, then use find:

$(form).find("option:selected").each(function(){

Or use the context parameter (though IMO the code is less clear):

$("option:selected", form).each(function(){

Although, since you're in the handler, you could just use this to reference the form element.

$(this).find("option:selected").each(function(){
Sign up to request clarification or add additional context in comments.

3 Comments

$(form).find("option:selected") should be $('option:selected', form) in this scenario.
@Ohgodwhy: I added that, but why do you say it "should be"? It's a little less efficient to add form as the context.
@Ohgodwhy - does'nt matter, the latter is just a shortcut for the former. On the other hand inside the function it would be better to use this in the context .
0

If form is a string that corresponds to an ID

Then it's supposed to be

$('#' + form)

$('#' + form + " option:selected")

If its a class replace # with a .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.