0

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!

3 Answers 3

2

The focus event will not bubble, see http://www.quirksmode.org/dom/events/blurfocus.html#t06

Couple of other issues:

  1. 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.
  2. parentsUntil will return all ancestors until the form 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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
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

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.