tags:

views:

29

answers:

2

Can someone tell me what this is doing? How should I refer to this in my html? What I want is to echo an error message in the html.

  $('#' + $field)
    .addClass('invalid')
    .siblings('.error')
      .text($message)
      .show();
A: 

Adds classname "invalid" (class="invalid") to selected field and then changes texts in siblings with class ".error" and shows them (removes display:none).

Māris Kiseļovs
Thanks Māris, now I just need to figure out how to use them. :)
jim
+1  A: 
  $('#' + $field)  
  // finding an element that has the `id` of the string/object referred to by $field
    .addClass('invalid')
     // adding the class-name 'invalid' to this element
    .siblings('.error')
      // selecting the sibling element of class-name 'error'
      .text($message)
      // replacing the text of that sibling, if any, with the value represented by the variable '$message'
      .show();
        // showing/un-hiding that element.

You could use this by first assigning an element to $field, adding an element of class-name 'error' as a sibling of that element, and assigning a message to the $message variable.


Edited in response to OP's request for clarification (in comment).

As a fairly basic example:

$(document).ready(
    function(){
        var $field = $('input[name=fieldName]').attr('id');
        var error = 'This field needs something else. Such as...';

        $('#'+$field).addClass('invalid').siblings('.error').text($message).show();
    }
);

<form action="" method="get">
    <fieldset>
        <label for="fieldName">This is a label:</label>
        <input type="text" name="fieldName" id="fieldName" />

        <div class="error"></div>
    </fieldset>
</form>

Rudimentary demo at JS Fiddle

David Thomas
David, thanks for the help and the explanation. I'm really new to JQ so most of what you're explaining isn't making it through. Whould you be able to show me how I need to use this in html? Like this?: `<div id="error"></div>`
jim
Am I correct in saying that the error message will be echoed in the div?
jim
Thank you for all your help, David. I can certainly digest this and finally understand how it all ties together.
jim
@Jim, yeah, the error from validation (I assume you're using a plug-in to generate that) should be echoed to the closest div to the input. Probably via a `.each()` jQuery loop.
David Thomas
@David, thanks for the explanation. I just ran your code but didn't see anything echoed in the error div. Unfortunately, I have no idea why. :) In reaponse to the validation plugin, the errors are being generated by my PHP then echoed out for JQuery.
jim
I'm going to start a new thread. I can't get this to work correctly.
jim