Reputation: 174
I'm using Textbox to add cities name to Listbox along with cities name i want to add close button, so i can remove cities names from listbox easily.
below image is for better understand
HTML
<asp:TextBox ID="txtcity" runat="Server"></asp:TextBox>
<asp:Button ID="btnAddcity" runat="server" Text="Add" />
<asp:ListBox ID="listBoxcity" runat="server"></asp:ListBox>
<span id="spcity"></span>
JQuery
$("#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));
}
});
Upvotes: 0
Views: 507
Reputation: 117
This snippet is work for me :)
$(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();
});
});
});
Upvotes: 0
Reputation: 1898
I removed option select, cus you cannot add delete button on option. Just take a look if you were trying to do this:
$("#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();
});
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;
}
<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>
Upvotes: 1