Michael Samuel
Michael Samuel

Reputation: 3920

Apply Jquery .one function on elements with the same class

I have the following simple Jquery:

<script type="text/javascript"> 
$(document).ready(function(){
     $(document).one('focus', 'input', function() {
          $(this).val('');
     });
});
</script>

<input type="text" value="Default 1" />
<input type="text" value="Default 2" />
<input type="text" value="Default 3" />
<input type="text" value="Default 4" />
<input type="text" value="Default 5" />

The above code will lead to running the focus function only once for all elements.

How to make it run the function once per each input element? Example:

Click the second element, run once. Click the first element, run once. And so on...

Upvotes: 0

Views: 121

Answers (2)

KyleMit
KyleMit

Reputation: 29889

The accepted answer works, but I'm guessing what you're really trying to do is use a placeholder:

<input type="text" placeholder="Default 1" />
<input type="text" placeholder="Default 2" />

In browsers that support placeholder, you'll get some startup text that clears on focus without taking the performance hit of using javascript. In unsupported browsers, you can use a polyfill to accomplish what you're trying to do anyway.

Also, the .each() function can be used to do something on every element returned by the selector.

Here's a simple placeholder polyfill:

$(function(){
    placeholderPolyfill();
});

function placeholderPolyfill() {
    if (!placeholderIsSupported()) {
        $("input[placeholder]").each(function() {
            this.value = this.placeholder;
            $(this).one('focus', function() {
                this.value = '';
            });
        });
    }
}

function placeholderIsSupported() {
    var test = document.createElement('input');
    return ('placeholder' in test);
}

Here's a demo in fiddle

Upvotes: 0

Ram
Ram

Reputation: 144659

You can use the not selector:

$(document).on('focus', 'input:not(.focused)', function() {
     $(this).addClass('focused').val('');
});

Upvotes: 1

Related Questions