2013-02-15 42 views
2

我用下面自動jQuery的填充基礎上,選中或取消選中複選框自動填充的複選框選中值的文本框的值,但保留該手動輸入

function updateTextArea() { 
     var allVals = []; 

     $('#all :checked').each(function() { 
       allVals.push($(this).val()); 
     }); 

     document.getElementById('txtbox').value = allVals; 
    } 
    $(function() { 
     $('#all input').click(updateTextArea); 
     updateTextArea(); 
    }); 

和我的HTML值的文本框的值代碼是

<div id="all"> 
<input id="txtbox" type="text" Height="100px" Width="770px" /> 
    <input id="Checkbox2" type="checkbox" value="[email protected]" /> 
    <input id="Checkbox3" type="checkbox" value="[email protected]" /> 
    <input id="Checkbox4" type="checkbox" value="[email protected]" /> 
    <input id="Checkbox5" type="checkbox" value="[email protected]" /> 

</div> 

以上的jQuery工作井,每檢查和複選框取消選中事件和填充其值的文本框用逗號隔開,我的問題是,如果有人手動輸入一些電子郵件由逗號在上述文本框中我想分開該值爲r並且不會刷新檢查並取消選中我的複選框的事件。我怎樣才能做到這一點?

回答

2

的一般技術,我會用它來解決這個問題是:

在每張支票或取消:
1.拆分列表由逗號到一個數組。
2.收集所有預設的電子郵件值(已經這樣做)。
3.找到不在預設數組中的每個拆分值,並將其置於一旁。
4.插入所有檢查的預設值,然後添加所有奇怪的球,反之亦然。

這不會保留順序,但它確實保留了任何手動輸入的值。保留秩序可以完成,但會更棘手一些。

您可能還會考慮只是有一個單獨的「額外的電子郵件」文本框,這將減少複雜性,並可能使用戶更直觀。

代碼:

function updateTextArea() { 
    var allVals = []; 
    var checkedVals = []; 

    $('#all input[type=checkbox]').each(function() { 
     allVals.push($(this).val()); 
    }); 

    $('#all :checked').each(function() { 
     checkedVals.push($(this).val()); 
    }); 

    var potentialOtherEmails = $("#txtbox").val().split(","); 
    var confirmedOtherEmails = []; 
    $(potentialOtherEmails).each(function(index,value) { 
     if ($.inArray(value, allVals) == -1) { 
      confirmedOtherEmails.push(value); 
     } 
    }); 

    $("#txtbox").val($.merge(checkedVals,confirmedOtherEmails));  
} 

$(function() { 
    $('#all input').click(updateTextArea); 
    updateTextArea(); 
}); 
+0

試試這個演示:http://jsfiddle.net/k8mh8/10/ – lmortenson 2013-02-15 12:17:06

+0

哇,這很酷謝謝:) – Dolo 2013-02-15 12:20:23

1

你去那裏....

$(function() { 
    txtbox = $("#txtbox"); 
    var prevVal; 
    $("input[type='checkbox']").click(function() { 
     prevVal = txtbox.val(); 
     if($(this).is(":checked")) 
     { 
      txtbox.val(prevVal + $(this).val() + ", "); 
     } 
     else 
     { 
      prevVal = prevVal.replace($(this).val()+", ", ""); 
      txtbox.val(prevVal); 
     } 
    }); 
}); 

一個說明在現有的代碼謹慎,你查詢DOM太多(遍歷每個複選框檢查),不要這樣做。另外,爲什麼你有jQuery可用時使用document.getElementById? :-)這可能不是一個完美的解決方案,但工程!