2015-10-15 85 views
1

我有這個代碼,我使用,並點擊我把電子郵件字段,但我想要完成的是,下一次點擊相同的領域,它會刪除電子郵件,如果一個已經存在輸入。添加/刪除值輸入點擊

這裏是我的代碼:

<p class="email">[email protected]</p> 
    <p class="email">[email protected]</p> 
    <p class="email">[email protected]</p> 
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" /> 

和JS:

var $contact = $('#contact-email'); 
$('.email').on('click', function() { 
    if ($contact.val()) { 
     $contact.val($contact.val() +'; '+ $(this).text()); 
    } else { 
     $contact.val($(this).text()); 
    } 
}); 

和小提琴https://jsfiddle.net/2dffwew5/2/

+0

然後將其設置爲空值,即'「」' –

回答

3

我會選擇電子郵件地址保存到一個數組。然後推送或拼接點擊的電子郵件。

var $contact = $('#contact-email'); 
var emails = []; 

$('.email').on('click', function() { 
    var index = emails.indexOf($(this).text()); 
    if (index > -1) { 
     emails.splice(index, 1); 
    } else { 
     emails.push($(this).text()); 
    } 
    $contact.val(emails.join(";")); 
}); 

https://jsfiddle.net/jdgiotta/ze7zebzq/

+0

是的,這是比我的建議好得多。更可靠 – musefan

+0

啊,我的錯誤,你想點擊$ $ contact去掉。文字定位... –

+0

真棒,這是有效的。謝謝! – Alex

0

我建議你添加一個檢查,看看當前的文本包含所選的電子郵件地址。如果有,請將其移除。否則,添加它。

您還需要迎合前/後分隔線,這可以通過一些條件檢查輕鬆完成。

事情是這樣的:

var $contact = $('#contact-email'); 

$('.email').on('click', function() { 
    var text = $(this).text(); // Get the value to insert/remove. 
    var current = $contact.val(); // Get the current data. 

    // Check if the value already exists with leading seperator, if so remove it. 
    if (current.indexOf('; ' + text) > -1) { 
     $contact.val(current.replace('; ' + text, '')); 
    } 
    // Check if the value already exists with trainling seperator, if so remove it. 
    else if (current.indexOf(text + '; ') > -1) { 
     $contact.val(current.replace(text + '; ', '')); 
    } 
    // Check if the value already exists with no seperator (on it's own), if so remove it. 
    else if (current.indexOf(text) > -1) { 
     $contact.val(current.replace(text, '')); 
    } 
    // Otheriwse, it doesn't exist so add it. 
    else { 
     if (current) { 
      $contact.val(current + '; ' + text); 
     } else { 
      $contact.val(text); 
     } 
    } 
}); 

Here is a working example