0 votes
asked by (180 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)
	.change(changeTraits);

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() 
{
	window.alert(event.currentTarget.val());
}

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
answered by (60.1k 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) {
	window.alert(event.currentTarget.value);
}

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() {
	window.alert($(this).val());
}

 

commented by (180 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!
Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...