当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Insert text before existing textbox content with jQuery

问题描述:

I have a short jQuery script that adds text like images: into a search box when a user clicks a link. However, if the user clicks a different tab instead the search they have typed is deleted. I want to keep what the user has typed (if they have typed anything) which will always be after the :. Anything before it can be deleted.

How do I do this?

My current jQuery is:

$(document).ready(function(){

$("#navigation a").click(function(){

$("#search").val($(this).attr("id")+': ').focus();

return false

});

});

My HTML is:

<ul id="navigation">

<li><a href="#" id="images">Images</a></li>

<li><a href="#" id="videos">Videos</a></li>

<li><a href="#" id="articles">News</a></li>

<li><a href="#" id="weather">Weather</a></li>

</ul>

<input type="text" id="search">

You can see a working example of the current code on JSFiddle: http://jsfiddle.net/Zusnw/

网友答案:

I'd suggest:

$("#navigation a").click(function(){
    var search = $('#search'),
        curVal = $('#search').val(),
        i = curVal.indexOf(':'),
        newVal = i !== -1 ? curVal.substring(i) : ': ' + curVal;
    $('#search').focus().val(this.id + newVal);
});

JS Fiddle demo.

网友答案:

Here is the fix you want.

$(document).ready(function(){
    $("#navigation a").click(function(){
        var searchBox = $("#search");
        var searchBoxVal = searchBox.val();     
        var newVal = '';
        if(searchBoxVal.indexOf(":") > -1)
        {
            // get the content after the colon...
            newVal = this.id + ":" +searchBoxVal.substring(searchBoxVal.indexOf(":")+1);
        }
        else
        {
            newVal = this.id + ": ";
            if(searchBoxVal.length > 0) 
            {
                // if colon not found but user has type anythings...
                newVal += searchBoxVal;
            }
        }
        searchBox.val(newVal);
        searchBox.focus();
        return false;
    });
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: