开发者

jQuery events not firing

I have been trying to get this to work. Basically I have a sear开发者_运维百科ch box that has a default string in it (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 the value of the textbox)

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

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

$('#searchBox').focus(function() {
clearDefault();
});


Problem is here:

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

Change it with:

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

Update: Check it here: http://jsfiddle.net/mr3T3/2/


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();
    });
});


It could be that event in fact is firing and your problem is in

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

is "defaultString" properly defined?

put a simple alert() inside clearDefaults() and see if the event works.


i don't think clearDefault is reusable function, so don't create unnecessary function for small block of code. See the following code sample, i added a small 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 a default attribute to store default value and used it later on blur event.

See the example in jsFiddler

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜