TDG TDG - 3 months ago 19
jQuery Question

JQuery on click remove bracket text and show only city name

On click 'a', it have to get city name and display in 'filter_selected_det'. It adds correctly with present code. But, i want to remove (PER)..etc. It has to show only 'City Name' without code.

Also once 5 cities are added.. have to prevent further addition of cities. Maximum 5 cities only.

Thanks for your valuable comments.

HTML:

<div class="filter_selected_det">
<div class="allCities">All Cities</div>
</div>
<div class="city_container">
<a href="#">Perth (PER)</a>
<a href="#">Sydney (SYD)</a>
<a href="#">Krabi (KRB)</a>
<a href="#">Melbourne (MLB)</a>
<a href="#">Adeliade (ADL)</a>
<a href="#">London (LDN)</a>
<a href="#">Flordia (FLO)</a>
</div>


JS:

$('.city_container a').on('click', function (e) {
e.preventDefault();
$(this).addClass('selected');
$('.allCities').remove();
var newCity = $('<div/>').html($(this).html());
$('.filter_selected_det').append(newCity);
});

Answer

$('.city_container a').on('click', function(e) {
  e.preventDefault();
  $(this).addClass('selected');
  $('.allCities').remove();



  var newCity = $('<div/>').html($(this).text().split('(')[0]);//remove the (

  if ($('.filter_selected_det div').length < 5) {// only allow 5 cities
    $('.filter_selected_det').append(newCity);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filter_selected_det">
  <div class="allCities">All Cities</div>
</div>
<div class="city_container">
  <a href="#">Perth (PER)</a>
  <a href="#">Sydney (SYD)</a>
  <a href="#">Krabi (KRB)</a>
  <a href="#">Melbourne (MLB)</a>
  <a href="#">Adeliade (ADL)</a>
  <a href="#">London (LDN)</a>
  <a href="#">Flordia (FLO)</a>
</div>

  1. To make only five cities count the div inside the container and do conditional statement.
  2. To remove the () use split then get the first element.