Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event when I remove the cursor from an Input field

At the moment I have following JQuery

$(document).ready(function(){
	var suchfeld =  $("#suchfeld");
	if(suchfeld.val()==0){
		suchfeld.val("Suche...");
	}
	suchfeld.click(function(){
		if(suchfeld.val()=="Suche..."){
		suchfeld.val("");
		}
	});
});

I want that the if(suchfeld.val()==0){ also excutes when the User click on any other thing outside suchfeld on my site. How can I handle this?

like image 683
Jürgen Hohlkopf Avatar asked Nov 28 '25 08:11

Jürgen Hohlkopf


1 Answers

Use blur event to track it. This is an event called, whenever the user leaves an element.

suchfeld.blur(function() {
    if( suchfeld.val() == 0 ) {
        suchfeld.val("Suche...");
    }
});

The opposide is focus, not click.

$(function() {
    var suchfeld = $("#suchfeld");

    // or suchfeld.focus(function() {});
    suchfeld.on("focus", function() {
        if( suchfeld.val() == "Suche..." ) {
            suchfeld.val("");
        }
    });

    // or suchfeld.blur(function() {});
    suchfeld.on("blur", function() {
        if( suchfeld.val() == 0 ) {
            suchfeld.val("Suche...");
        }
    });
});

You can chain these too:

$(function() {
    $("#suchfeld").focus(function() {
        if( suchfeld.val() == "Suche..." ) {
            suchfeld.val("");
        }
    })
    .blur(function() {
        if( suchfeld.val() == 0 ) {
            suchfeld.val("Suche...");
        }
    });
});
like image 91
eisbehr Avatar answered Nov 29 '25 20:11

eisbehr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!