Set the name of a Jquery selector as a string in a variable
I'm quite a noob at Jquery but I'm trying to set a variable based on the name of a form element.
I.e. variable = "someForm" based on this example:
<form id="hello" name="someForm" >
First name: <input type="text" name="firstname" />
Last name: <input type="text" name="lastname" />
Email: <input type="text" name="email" />
<input type="submit" value="Subscribe" />
</form>
I'm using the following code which doesn't seem to work:
var formName = 0;
$('input').parentsUntil('form', this开发者_运维问答).focus(function() {var formName = this.name;})
if (stTime == 0) { // This ensures someone cannot start a form multiple times
var stTime = new Date();
stDelay = stTime - loTime;
alert(formName);
}
Thanks in advance!
The focus
event will not bubble, see http://www.quirksmode.org/dom/events/blurfocus.html#t06
Couple of other issues:
- The
formName
variable being assigned to inside the event handler isn't the same variable as the first line since you're re-declared it, it then exists only inside the scope of that event function. parentsUntil
will return all ancestors until theform
element, not the element itself which is presumably what you want.
Your code is out of context so it's difficult to understand how formName
and the timer variables should be used and where they should be declared, but this should work for the event:
$('form :input').focus(function() {
formName = $(this).parents('form').attr('name');
});
:input
is a jQuery selector that matches all <input>
types, along with <textarea>
and <select>
The focus
event will bubble, so you can just use:
$('form').focus(function() {
formName = this.name;
});
But it'd be better to store your timer when it's submitted, for example:
$('form').submit(function() {
formName = this.name;
});
Also don't use var
inside the event handler, as this will create a new, local variable, not set your formName
variable declared above it.
var formName = 0;
$('input').parentsUntil('form', this).focus(function() {var formName = this.name;})
This can't work. You are trying to assign to the formName variable defined in the first line, but you're redefining the variable in the second line. You are actually dealing with two different variables, one in the function scope and one in global scope.
Solution:
var formName = 0;
$('input').parentsUntil('form', this).focus(function() {formName = this.name;})
// --- no var here
精彩评论