簡體   English   中英

用jQuery替換輸入值.val()

[英]Replace input value .val() with jQuery

所以基本上這里是我的jsFiddle- http://jsfiddle.net/CmNFu/

還有代碼在這里-

HTML-

<b style="float: left; margin-right: 10px;">category 1</b><input type="checkbox" value="category1" style="float: left;" class="portfolio-category" /><br />
<b style="float: left; margin-right: 10px;">category 2</b><input type="checkbox" value="category2" style="float: left;" class="portfolio-category" /><br />
<br />
<br />
<input type="text" name="categories" id="portfolio-categories" />​

jQuery-

jQuery(document).ready(function() {
    jQuery(".portfolio-category").click(function() {
        if(jQuery(this).is(":checked")) {
            jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+" "+jQuery(this).val());
        }
        else {
            var portfolioCategories = jQuery("#portfolio-categories").val();    
            alert("before + "+portfolioCategories);
            var currentElement = jQuery(this).val()+" ";
            alert(currentElement);
            portfolioCategories = portfolioCategories.replace(currentElement, "");
            alert(portfolioCategories);
        }
    });
});

基本上我想實現的是,當用戶選中復選框時,該值會自動添加到輸入字段中(完成,它正在工作,哇!),但是問題是當它取消選中該復選框時,應該從中刪除該值輸入框(問題從此處開始),它不會刪除任何內容。 您可以看到我嘗試將val()函數分配給變量,但是也沒有成功。 查看我在jsFiddle上的示例以實時觀看。

有什么建議么? 我猜replace()對val()不起作用,對嗎?

那么,還有其他建議嗎?

我會這樣做:

jQuery(document).ready(function() {
    jQuery(".portfolio-category").on('change', function() {
        var string = "";
        $('input[type="checkbox"]').each(function() {
            var space = string.length>0?' ':'';
            string += this.checked?space+this.value:'';
        });
        $("#portfolio-categories").val(string);
    });
});

小提琴

您在該輸入框中存在空格問題。 但我們稍后會解決。

首先,這將是一種工作(如果不是因為空間問題):

在最后一個警報之前添加此行:

 jQuery("#portfolio-categories").val(portfolioCategories);

這將起作用,但並非總是如此,因為您添加的最后一個元素后面沒有空格。

但是,如果將第四行更改為:

jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+jQuery(this).val()+" ");

它會起作用,因為它會在每個元素之后而不是之前添加空格。

http://jsfiddle.net/CmNFu/5/

您的問題是您更改了以下變量的值: portfolioCategories ,但尚未更新輸入本身。 (注意,更改字符串的值不會更改其原始來源的輸入的值)

您需要將字符串PortfolioCategories插入回輸入中。 同樣,空間也產生了很多問題。 您可以使用$ .trim(str)從字符串中刪除任何前導和尾隨空格。 已使用有效的解決方案更新了您的小提琴。

http://jsfiddle.net/CmNFu/11/

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM