0 votes
by (230 points)

Hi. I'm relatively new to JQuery and despite several Google searches, I can't seem to find an answer to what I thought was a relatively obvious question.

I'm creating several checkboxes using this method:

var box = $("<input>").attr("type", "checkbox")
	.attr("name", name).val(name)

Then, in the method "changeTraits()" I need to access the checkbox whose change triggered the event. I've seen how to do this using the ".on" or ".one" method of assigning handlers, but not using this method. This is my current attempt that isn't working:

function changeTraits() 

I also tried it by passing in a parameter with the name "event", but I still get an error because "event" is undefined. I'm sure I'm missing something really obvious, but it's so obvious that no one seems to have explained it. Or, maybe I'm just not wording the question correctly. Anyway, any help would be appreciated!

1 Answer

0 votes
by (68.6k points)

Your identifier event is undefined because you never defined the appropriate parameter on your event handler function.  Additionally, you cannot use the <jQuery>.val() method on an unwrapped DOM object.

For a pure DOM approach, you need to define your handler something like the following:

function changeTraits(event) {

For an idiomatic jQuery approach, I'd suggest simply using the this keyword (as jQuery attempts to set this to the event target):

function changeTraits() {


by (230 points)
Okay, I was kind of dancing around the solution, but just didn't quite understand how everything was working. Those both work perfectly. Thank you very much!