JQuery events do not fire

I'm trying to get this to work. Basically, I have a search box in which there is a default line (i.e.Search), and it should go away when the user clicks on the input field.

Here is the code:

HTML:

<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' value="Search <?php print $row[0]?> tweets!" autocomplete="off" />
</form>

Javascript / jQuery: (defaultString is a global variable that has a text field value)

function clearDefault() {
var element = $('#searchBox');

if(element.attr('value') == defaultString) {
    element.attr('value',"");
}
element.css('color','black');
}

$('#searchBox').focus(function() {
clearDefault();
});
+3
source share
4 answers

The problem was that the event binding was not inside the $ (document) .ready () handler.

Fixed

function clearDefault() {
var element = $('#searchBox');

if(element.val() == defaultString) {
element.val("");
}
element.css('color','black');
}

$(document).ready(function() {
    $('#searchBox').focus(function() {
    clearDefault();
    });
});
+5
source

The problem is here:

if(element.attr('value') == defaultString) {
    element.attr('value',"");
}

Change it with

if(element.val() == defaultString) {
    element.val('value');
}

Update: check here: http://jsfiddle.net/mr3T3/2/

+5
source

, ,

if(element.attr('value') == defaultString) {
    element.attr('value',"");
}

defaultString?

() clearDefaults() , .

+1

I don't think clearDefault is a reusable function, so don't create an unnecessary function for a small block of code. See the following code example, I added a slight improvement in your functionality.

<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' default="Search tweets!"  value="Search tweets!" autocomplete="off" />
</form>

$(document).ready(function() {
    $("#searchBox").focus(function(e){
        var $this = $(this);
        if($this.val() == $this.attr('default')) $this.val('');
        else if($this.val().length == 0 ) $this.val($this.attr('default'));
    });
    $("#searchBox").blur(function(e){
        var $this = $(this);
        if($this.val().length == 0 ) $this.val($this.attr('default'));
    });
});

I added an attribute to store the default value and later used it on the event . default blur

See an example in jsFiddler

0
source

Source: https://habr.com/ru/post/1794970/


All Articles