Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 577
Stoic Avatar asked Dec 10 '10 06:12

Stoic


People also ask

How do I select a specific tag in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Can you use CSS selectors in jQuery for selecting elements?

Projects In JavaScript & JQueryjQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element. name − The name of the property to access.

What is EQ jQuery?

jQuery eq() Method The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.


1 Answers

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.

like image 189
jthompson Avatar answered Sep 21 '22 09:09

jthompson