单击时添加/删除值以输入

时间:2015-10-15 15:51:44

标签: javascript jquery

我有这个代码,我使用,点击我把电子邮件放在字段中,但我想要完成的是,在下一次点击相同字段时,如果输入中已存在电子邮件,则删除电子邮件。

这是我的代码:

<p class="email">mail1@gmail.com</p>
    <p class="email">something@gmail.com</p>
    <p class="email">third@gmail.com</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/

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/

答案 1 :(得分: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

相关问题