Reputation: 21
I have a javascript function that runs quite nicely from html
'onClick="my_function(this.form)"
but I also want to call this function if a specific element within the form has data keyed in I have tried
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form').options-i-have-tried();
my_function(myform);
});
});
options-i-have-tried() include html() (and that shows that I have html inside of the correct form ok),
get() a bit of a stab in the dark,
serializeArray() from some answers to similar questions,
and nothing at all.
In each case my function complains that its argument form, or more specifically form.myelement is undefined
Many thanks in anticipation
Upvotes: 0
Views: 691
Reputation: 3376
I think if you use the first element from the closest
call you will be successful:
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form')[0];
my_function(myform);
});
Upvotes: 0
Reputation: 237875
this
in a jQuery callback will be the element where the handler is attached. It is the native DOM element, without any jQuery wrapper.
So presuming that #option_field_bizpostcode
is a form element, you should be able to do this.form
just as you would in the onclick
method.
my_function(this.form);
Upvotes: 0
Reputation: 166
Well your passing the FORM Element into the function in the inline handler (onclick attribute) so you need to do the same with the jQuery handler.
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form')[0]; //because the form element is at the first index in the jquery object
my_function(myform);
});
});
OR even better, why don't you just stick to doing this:
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
my_function(this.form);
});
});
Upvotes: 3