如何在列表框中添加关闭按钮

时间:2016-06-15 10:35:20

标签: javascript jquery html html5

我使用文本框将城市名称添加到列表框以及城市名称我想添加关闭按钮,因此我可以轻松地从列表框中删除城市名称。
下图是为了更好地理解 enter image description here

HTML

$("#btnAddcity").click(function () {
  var txt = $("#txtcity").val();
  $('[id$=listBoxcity]').show();
  var alreadyExist = false;
  $('[id$=listBoxcity] option').each(function () {
  if ($(this).val() == txt) {
    $("#spcity").text('City alread exists');
     alreadyExist = true;
     return;
  }
});
if (!alreadyExist) {
  $('[id$=listBoxcity]').append($('<option></option>').attr('value', txt).text(txt));
 }
});

JQuery的

git checkout A
git merge B --no need changes

2 个答案:

答案 0 :(得分:1)

我删除了选项选项,cus你无法在选项上添加删除按钮。如果您正在尝试这样做,请查看:

&#13;
&#13;
$("#btnAddcity").click(function () {
  var txt = $("#txtcity").val();
  $('[id$=listBoxcity]').show();
  var alreadyExist = false;
  $('[id$=listBoxcity] option').each(function () {
  if ($(this).val() == txt) {
    $("#spcity").text('City alread exists');
     alreadyExist = true;
     return;
  }
});
if (!alreadyExist) {
  $('[id$=listBoxcity]').append($('<span></span>').attr('value', txt).text(txt));
   $('[id$=listBoxcity]').append($('<a href="#" class="delete">x</a><br>'));
 }
});

$(document).on('click', 'a.delete', function(event){ 
    $(this).prev('span').remove();
    $(this).next('br').remove();
    $(this).remove();
});
&#13;
a.delete {
    margin-left: 10px;
    width: 20px;
    height: 20px;
    background: #82854C;
    border-radius: 100%;
    text-align: center;
    display: inline-block;
    color: #fff;
    vertical-align: middle;
    text-decoration: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<table>
<tr>
  <td><input id='txtcity' type="text" /></td>
  <td><input id='btnAddcity' type='button' value='Add' /></td>
</tr>
</table>
<!-- <select id='listBoxcity' multiple="multiple" style='width:300px; height:100px;'>

</select> -->
<div id='listBoxcity' multiple="multiple" style='width:300px; height:100px;'>
  
</div>
  <span id='spcity'></span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这段代码对我有用:)

$(document).ready(function(){
$("#btnAddcity").click(function () {
  var txt = $("#txtcity").val();
  $('[id$=listBoxcity]').show();
  var alreadyExist = false;
  $('[id$=listBoxcity] option').each(function () {
  if ($(this).val() == txt) {
    $("#spcity").text('City alread exists');
     alreadyExist = true;
     return;
  }
});
var count = 0;
if (!alreadyExist) {
count++;
  $('[id$=listBoxcity]').append($('<span></span>').attr('value', txt).text(txt));
   $('[id$=listBoxcity]').append($('<div class="delete">x</div><br>'));
 }

 $('.delete').on('click',function(e){
    console.log($(this).closest('span'));
   $(this).next('br').remove();
   $(this).prev('span').remove();
   $(this).remove(); 
  });
});

});