简体   繁体   中英

How can I remove an icon from a table dynamically in javascript?

I want to delete an icon from a table dynamically. First, I will display icons on a table. The number of icons displayed depends on the value retrieved from a database.

When I clicked a button to remove the icon, it's not removed.

HTML

 <td class="actions">
     <a href="" class="icon" id="plus_bintang<?= $santri->id_santri ?>" onclick="add_ubah(<?= $santri->id_santri ?>); return false"> <i class="mdi mdi-plus-square"></i></a>
     <a href="" class="icon" id="minus_bintang<?= $santri->id_santri ?>" onclick="remove_ubah(<?= $santri->id_santri ?>); return false"> <i class="mdi mdi-minus-square"></i></a>
     <div id="bintang<?= $santri->id_santri ?>">
         <input type="hidden" name="nilai[]" value="<?=$santri->nilai?>" id="nilai<?= $santri->id_santri ?>">
         <?php for ($i=0; $i <$santri->nilai ; $i++) { ?>
                <i class='mdi mdi-star'></i>
         <?php } ?>
     </div>
 </td>

Javascript

function add_ubah($id = null) {
    let bintang = document.getElementById('bintang' + $id);
    let count_bintang = bintang.getElementsByTagName('i').length;

    if (count_bintang < 5) {
        $("#bintang" + $id).prepend("<i class='mdi mdi-star'></i>");
        count_bintang = bintang.getElementsByTagName('i').length;
        document.getElementById('nilai'+$id).value = count_bintang;  
        return false;
    }else if(count_bintang == 0){
        $("#bintang" + $id).prepend("<i class='mdi mdi-star'></i>");
        count_bintang = bintang.getElementsByTagName('i').length;
        document.getElementById('nilai'+$id).value = count_bintang;  
        return false;
    }else {
        return false;
    }
}

function remove_ubah($id = null) {
    let bintang = document.getElementById('bintang' + $id);
    let count_bintang = bintang.getElementsByTagName('i').length;
    if (count_bintang > 0) {
        document.getElementById('bintang' + $id).removeChild(bintang.childNodes[0]);
        count_bintang = bintang.getElementsByTagName('i').length;
        document.getElementById('nilai'+$id).value = count_bintang;  
    } else if(count_bintang == 0) {
        return false;
    } else{
        return false;
    }
}

Try removing all spaces inside of your div#bintangXYZ HTML. Remember that childNodes returns text nodes too, so sometimes when you click you just remove a whitespace between the stars. Also place the <input name="nilai[]> after all the stars (because you are prepending all the added stars).

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