user1006072
user1006072

Reputation: 963

unable to scroll to the label for input field with an error message

I earlier asked another question here However, I later realized that my requirements are a little different. The above referenced solution takes me only to the error div but I need to scroll up slightly above that to the label for the input text field. Below is the html.

<label class="label_required" for="phone_num_key"></label>
 <table class="table_Box">
  <tbody>
    <tr id="someId" class="redAlert">

       <Some more mark up here>

    </tr>
  </tbody>
 </table>

How can I scroll up to the label instead of the tr element with class 'redAlert' I tried the below but it didn't work for me.

var errorDiv= $('.redAlert:visible').first();
var errorLabel = errorDiv.parent("table").prev("label");
// also tried this
//var errorLabel = errorDiv.closest("label").prev();
var scrollPosition = (errorLabel.offset().top); 
    $(window).scrollTop(scrollPosition);

Looks like the .offeset() function cannot be called on Labels ?

Edit - Please note that there are multiple such labels on the form so I cannot basically use the class selector

Upvotes: -1

Views: 1080

Answers (1)

Ron
Ron

Reputation: 2790

offset() does work. problem is parent().

use errorDiv.parents('table').prev('label');

FYI,

.parent( [selector] )

Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.

                                           from http://api.jquery.com/parent/

Upvotes: 1

Related Questions