javascript - Why does not this work with id when working with class -
this question has answer here:
if make remove button id attribute isnt working. when make class attribute working. why not working id?
$(function() { $("#btn").on("click", function() { var val = $("#yzbr").val(); if (val !== '') { var elem = $("<li></li>").text(val); $(elem).append("<button id='rem'>remove</button>"); $("#ekl").append(elem); $("input").val(""); $("#rem").on("click", function() { $(this).parent().remove(); }) } }) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>list</h1> <input type="text" id="yzbr"> <button id="btn">add</button> <ol id="ekl"></ol>
you cannot have multiple id on same page. use classes or...
...don't use @ all!
assign click behavior directly created button.
jquery(function( $ ) { // use named functions, // you'll know without reading code function additemtolist () { var val = $.trim( $("#name").val() ); // trim whitespaces!! if (val === '') return; // nothing if no value $("#name").val(""); // reset input field $("<li/>", { // create li text: val, appendto: "#list", // appendto #list sonds poetry append: $("<button/>", { // append button text: "remove", on: { click: function() { $(this).closest("li").remove(); } } }) }); } $("#add").on("click", additemtolist); // :) // other dom ready code here });
<input type="text" id="name"> <button id="add">add</button> <ol id="list"></ol> <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Comments
Post a Comment