jim
jim

Reputation: 15

Jquery addClass question

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();

Upvotes: 0

Views: 266

Answers (2)

David Thomas
David Thomas

Reputation: 253308

  $('#' + $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

Upvotes: 1

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17275

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

Upvotes: 0

Related Questions