单击将文本从按钮添加到带有 jQuery 或 JS 的输入框

On click adding the text from a button to a Input box with jQuery or JS

我是一个代码,当我按下一个按钮时,值="first_name" 它会将按钮的值作为标签添加到列表中 class="tags".

如何更改按钮上的显示文本,使按钮上的文本变为 "Add tag",以及当我按下按钮时将文本 "first_name" 添加到列表中?

HTML

<input class="btn btn-info attribute-button" name="commit" readonly="readonly" type="button" value="first_name" />
<input class="btn btn-info attribute-button" name="commit" readonly="readonly" type="button" value="second_name" />



<div class="tags" contenteditable="false">
    <input class="newtag" type="text" name="newtag" readonly="readonly" placeholder="Add tags" />
</div>

CSS

.tags {
width: 100%;
height: 60px;
border: 0px solid #fff;
border-radius: 4px;
margin: 0 0 25px;
padding: 19px 0 0 20px;
font-size: 14px;
background-color: #fff;
background-image: none;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
overflow-x: hidden;
}
.tag {
padding: 1px;
background-color: blue;
color: #fff;
border-radius: 3px;
display: inline-block;
}
.newtag {
border: none;
outline: none !important;
}
.tag .remove {
margin-left:5px;
color: #aaa;
cursor:pointer;
font-size:10px;
}

JS

$(document).ready(function(){
$(".tags, .attribute-button").click(function(){
    $(".newtag").focus();
})
$(".newtag").keydown(function(e){
    if(e.which === 13 || e.which === 32 || e.which === 9){
        e.preventDefault();
        $(".newtag").before("<div class='tag'>" + $(this).val() + "<span class='remove'>X</span></div>");
        $(".newtag").val("");

    }
});
$(".attribute-button").click(function () {
    $(".newtag").before("<div class='tag'>" + $(this).val() + "<span class='remove'>X</span></div>");

    $('.remove').on('click', function () {
        $(this).parent().remove();
    });
});
});

谢谢。

您可以简单地使用原生 HTML button 元素而不是 input type="button":

<button class="btn btn-info attribute-button" value="first_name">Add tag</button>
<button class="btn btn-info attribute-button" value="second_name">Add another tag</button>

JSfiddle