简体   繁体   中英

How to add/remove html data in a span using javascript

I am currently doing a simple online bus seat booking system and i am stuck with one feature that whenever user selects more than one bus seat,corresponding seat number should be shown in a span or div separated by comma and whenever the user unselect the seat(by clicking selected seat again) that seat number must be removed.

I did the first part,ie adding seat number to the span but have no idea how to remove the unselected seat number.Also how to separate seat number by comma.My code is

 function bookSeat(seat) { var src = $("#" + seat).attr('src'); // alert(src); if (src === 'images/availableSeat.gif') { $("#" + seat).attr('src', 'images/selectedSeat.gif'); if ($('#seats').is(':empty')) { $("#seats").append(seat); } else { $("#seats").append(" , "+seat); } } else if (src === 'images/selectedSeat.gif') { $("#" + seat).attr('src', 'images/availableSeat.gif'); // code to remove the unselected seat number } } 

any help will be appreciated

Convert your string into a array and remove the seat value, join the array and append it to the seat div TRy:

  function remove(seat) {
    var array = $("#seats").html().split(",");
    $.each(array,function(i,v){
       if (v == seat) {
            array.splice(i,1);
         }
    });
    return array.join();
    }
data = remove('seat2');
 $("#seats").append(data);

see: https://jsfiddle.net/c5us7u23/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM