2017-03-13 23 views
1

我想添加/刪除類到類別爲"related-box-check"的上面的div,並在複選框被選中時更改標籤的內部HTML。它應該被刪除(回到默認),當方塊再次取消選中時。我的checkbox-id是動態生成的。當複選框被選中時,添加類並更改內部HTML

我該如何做到這一點?

我的HTML看起來像這樣:

<div class="related-box-check"> 
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox162569" name="related_products[]" value="162569"> 
<label class="label-related" for="related-checkbox162569">Add for check</label> 
</div> 

的jsfiddle:https://jsfiddle.net/ws7wk19g/

+1

你應該告訴你試了一下到目前爲止 –

回答

2

這會做你需要什麼...

$(function() { // document.ready handler 

    $("input[type=checkbox]").on("change", function() { 
    if (this.checked) { 
     $(this) 
     .closest(".related-box-check") 
     .addClass("new-class") 
     .find(".label-related").each(function() { 
      var $this = $(this); 
      $this.data("original-inner-html", $this.html()); 
      $this.html("Some new text because you checked the box!"); 
     }); 
    } 
    else { 
     $(this) 
     .closest(".related-box-check") 
     .removeClass("new-class") 
     .find(".label-related").each(function() { 
      var $this = $(this); 
      var original = $this.data("original-inner-html"); 
      $this.html(original); 
     }); 
    } 
    }); 

}); 

找到的每個複選框,將change事件處理程序,每當複選框值發生變化時執行。當它被選中時,代碼找到類.related-box-check(父div)最接近的父元素,並添加類new-class,然後更改標籤的html(在存儲原始值後)。然後,當您勾選複選框時,它會解除所有這一切 - 將標籤設置回其原始值並刪除添加的類。

這裏是展示在用行動表明一個更新的jsfiddle ...

https://jsfiddle.net/ws7wk19g/9/

1

這是一個純粹的JavaScript代碼。我已經在父元素中放置了一個目標元素,以確保不管你在目標元素內部做了什麼,它都不會受到影響。

function myFunction(chk) { 
 
var targetElement = document.getElementById('target-element'); 
 
console.log(targetElement) 
 
    if (chk.checked){ 
 
    targetElement.innerHTML= "I am checked!"; 
 
    } 
 
    else{ 
 
    targetElement.innerHTML="I am unchecked!" 
 
    } 
 
}
<div class="related-box-check"> 
 
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox162569" onchange="myFunction(this)" name="related_products[]" value="162569" > 
 
<label class="label-related" for="related-checkbox162569">Add for check</label> 
 
<div id="target-element"> 
 
</div> 
 
</div>

0

要隱藏/顯示您的div元素:

<script> 
$("input[type=checkbox]").click(function(){ 
if(this.checked) 
    $(".related-box-check").show(); // checked 
else 
    $(".related-box-check").hide(); 
}) 
</script> 
相關問題