Stoic
Stoic

Reputation: 10754

Exclude an element with a specific attribute from jQuery selectors

I am using this javascript to empty an input/textarea when focussed.

   $(document).ready(function() {
    $('input[type="text"],textarea').not('[readonly="readonly"]').addClass("idleField");
    $('input[type="text"],textarea').focus(function() {
        $(this).removeClass("idleField").addClass("focusField");
        if (this.value == this.defaultValue){
            this.value = '';
        }
        if(this.value != this.defaultValue){
            this.select();
        }
    });
    $('input[type="text"],textarea').blur(function() {
        $(this).removeClass("focusField").addClass("idleField");
        if ($.trim(this.value) == ''){
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });
   });

I am looking for a way to exclude those input fields, which are set readonly via readonly="readonly". I know I should be using .not (I guess), but I can not figure out how.

Upvotes: 5

Views: 4667

Answers (1)

jthompson
jthompson

Reputation: 7266

If you want all input elements that are writable (not readonly), you can use the following selector:

$("input:not([readonly])")

The parameter after :not is the selector to match. [readonly] will match anything where readonly is set. Note that the following will not always work:

[readonly="readonly"]

As you could have both of these:

<input readonly type="text">
<input readonly="readonly" type="text">

You can also use the ":input" psuedo-selector instead of "input,textarea". See the documentation here.

Upvotes: 11

Related Questions