0

Desired Result

I'm attempting to create a generic method in Javascript (JQUERY) which checks the page for any and every element whether it is nullable or not.

As a example I'm using a login.

Both the username and password are not nullable. In my head I think it may be possible to have a error label, which is standard hidden, with a for='<inputbox name here>'. Then I can loop through all labels which have the class that shows that the label belongs to a input.

Example

<label for="i_1_s_1">Name: </label>
<input type="text" name="i_1_s_1">
<label class="notnullerror" for="i_1_s_1">hidden</label>
<label for="i_1_s_2">Password: </label>
<input type="text" name="i_1_s_2">
<label class="notnullerror" for="i_1_s_2">hidden</label>

Problem

I'm unaware what the best practice is for this. Basicly what I want is a

foreach (var element = document.getElementsByClass('notnullerror')
{
     document.getElementsByName(element.for.value);

} 

However, this is done in javascript and not jquery and ofcourse, this will not work. How can I manage to make this the way I want?

And, if this is not best practice for showing a error message on a not nullable input, please comment on what is.

Pete
  • 57,112
  • 28
  • 117
  • 166
Theun Arbeider
  • 5,259
  • 11
  • 45
  • 68

2 Answers2

1

This will work: it finds all notnullerror elements and gets the element that corresponds to the for attribute for each of them.

$(function() {
   $('.notnullerror').each(function() {
       var forEl=  $('input[name="' + $(this).attr('for') + '"]');
       //do something here
   });
});
cfs
  • 10,610
  • 3
  • 30
  • 43
0

It is more common to validate form controls when the form is submitted, rather than running individual tests. You can loop over the controls and validate each based on an attribute value, e.g. if it has a class of notnullerror, test it and display an appropriate error message if necessary.

e.g. (assuming you have a hasClassName function or similar):

var element, elements = form.elements;

for (var i=0, iLen=elements.length; i<iLen; i++) {
    element = elements[i];

  if (hasClassName(element, 'notnullerror') &&  element.value == '') {
      // deal with error
  }

  // perform other validation tests

}

Incidentally, the value of a form control is always a string, and therefore can never be == or === to null, though it might be equal to the string "null".

RobG
  • 142,382
  • 31
  • 172
  • 209