0

I have the following function:

if ($(this).find('#sel').length == 0) {
    var before = $(this).text();
    var title_id = $(this).parent().attr('id');
    $(this).html("<select id='sel' onchange='selectdone(this, title_id=title_id)>
                   ...</select>");
}

From this I get Uncaught ReferenceError: title_id is not defined. Why isn't the onchange function inside on line 4 not picking up on the variable that I've defined previously? How would I rewrite the above correctly?

3 Answers 3

2

Did you mean this?

$(this).html("<select id='sel' onchange='selectdone(this, "+title_id+");'>...</select>");
Sign up to request clarification or add additional context in comments.

Comments

0

Use string concatenation here:

$(this).html("<select id='sel' onchange='selectdone(this, title_id=" + title_id +");'>...

Comments

0

It's happening because you're defining the "change" handler as part of a string, so the language has no idea that there's code in there.

Try this:

$(this).html($("<select/>", {
  id: 'sel',
  change: function() { selectdone(this, title_id) }
}));

Since you're using jQuery anyway, you should get in the habit of managing your event handlers via the library instead of with "onfoo" attributes.

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.