2015-08-28 78 views
1

當我從輸入添加到div值,我需要點擊複選框,以便其警報(「檢查」)。我的代碼無法正常工作。你能告訴我我做錯了什麼嗎?不工作複選框檢查

這裏是我的代碼

HTML:

<div class="container"> 
    <form> 
     <p>Title:</p> 
     <input type="text" id="title"> 
     <p>Link:</p> 
     <input type="text" id="link"> 
    </form> 
    <br> 
    <button class="btn btn-success">Add</button> 
</div> 

<div class="content" style="margin-top:50px"></div> 

JQuery的:

$(function() { 
    $(".btn-success").click(function(){ 
     var title_val = $("#title").val(); 
     var link_val = $("#link").val(); 
     $(".content").append('<div class="col-xs-6 col-md-4"><ol class="breadcrumb"><h4>'+title_val+'</h4><input type="checkbox" id="checkbox"></ol><a href="http://'+link_val+'" class="thumbnail"></a></div>'); 
    }); 

    $("#checkbox").click(function(){ 
     if($(this).is(":checked")) { 
      alert("Checked"); 
     } 
    }); 
}); 

JSfiddle

+0

尤爲什麼你的代碼不能正常工作總是使用上,如果你的U [R動態添加HTML之後,其他從未使用的ID,如果你加入了同一個ID多個元素總是喜歡類的第一個原因。 – Developer

+0

@Gaurav沒有動態添加元素的委託,事件不起作用。我不知道是誰投了你的答案。嚴重的是,StackOverflow的質量已經下降。 –

回答

2

複選框動態添加。所以,你需要委派事件處理已經存在的元素,並確保不給同一ID S:

$(document).on("click", ".checkbox", function(){ 
    if($(this).is(":checked")) { 
     alert("Checked"); 
    } 
}); 

更改您的追加功能,而不是使用ID級別。

$(".content").append('<div class="col-xs-6 col-md-4"><ol class="breadcrumb"><h4>'+title_val+'</h4><input type="checkbox" class="checkbox"></ol><a href="http://'+link_val+'" class="thumbnail"></a></div>'); 
+1

我同意你的答案,正確 – Developer

+1

你的回答是最好的,我剛剛分享了我的想法 – Developer

+0

謝謝@Gaurav。 ':)' –

0

DEMO

$('.content').on('click', "input[type='checkbox']", function() { 
    if ($(this).is(":checked")) { 
     alert("Checked"); 
    } 
}); 
+0

ID不能被複制。基本規則。 –

+1

@PraveenKumar是的,你是對的。但我沒有注意到可以添加多個複選框。 – RRK

0

添加類的複選框,然後是jQuery的使用這個代碼:

$('.chk').live('click',function(){ 
     if($(this).is(":checked")) { 
      alert("Checked"); 
     } 
    }) 

檢查此鏈接Link

+1

請添加事件委託的概念。 –

+0

@PraveenKumar http://jsfiddle.net/ken94tz6/3/ – Developer

+0

1.您的代碼與小提琴不同。 2.使用'.live()'?尼斯。那已經很久沒有回來了。 –

0

Use this code 
 
$(document).on('click', '#checkbox' , function(){ 
 
    if($(this).is(":checked")) { 
 
    alert("Checked"); 
 
    } 
 
});