2014-11-03 21 views
0

我創建了一個複選框,當選中時,添加到DOM。我一直在嘗試排除故障的問題是,無論複選框是選中還是取消選中,標記都會添加到DOM中,而不僅僅是在選中時。複選框沒有綁定到他們在DOM上創建的標籤jquery

我也不知道如何在關聯複選框未選中時從DOM中刪除標記。我有多少複選框,可以檢查最大值在6,這是我所期待的,但是有沒有辦法最大限度地提高父div內的子div的數量?這樣可以再次保證可以一次選擇不超過6個標籤。

這是一個jsfiddle http://jsfiddle.net/co5w7c9j/與我有什麼,希望我已經足夠解釋,而不會讓它聽起來太混亂。

下面是我到目前爲止寫的jquery,我想我錯過了一個步驟來實現我所尋找的。

感謝您花時間瀏覽我的代碼。

// When specilaty is checked, add tag to profile page 
$('[name=specialty]').click(function() { 
    $newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>"); 
    $(this).attr('value'); 
    $('.Specialties').append($newTag); 

    /* if ($('.Specialties > .specTag').has(('[name=specialty]:checked').attr('value'))) { 
     $('.Specialties > .specTag').has((this).txt()).remove(); 
     } */ 

    // Count number of checkboxes selected and display in modal 
    var increment = 0; 
    $('[name=specialty]:checked').each(function() { 
     if (this.checked) { 
      increment++; 
     } else { 
      increment--; 
     } 
     $('#specCount').html(increment); 
    }); 

    // Disable checkboxes when 6 (maximum) are selected 
    $("input[type=checkbox][name=specialty]").click(function() { 
     var bol = $("input[type=checkbox][name=specialty]:checked").length >= 6; 
     $("input[type=checkbox][name=specialty]").not(":checked").attr("disabled", bol); 
    }); 

    // Create array of checked items - add on checked - remove on uncheck 
    specialtyArray = $('[name=specialty]:checked').map(function() { 
     return $(this).val(); 

     // if item is in the array, then remove it from the DOM 
     if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {} 
    }); 
    console.log(specialtyArray.get()); 

}); 

// When Specialties modal closes, uncheck all checked boxes, reset count 
$(document.body).on('click', '.close', function() { 
    $('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked'); 
    $('#specCount').html(0); 
}) 

// Fade out specialty tags when x is clicked 
$(document.body).on('click', '.xOut', function() { 
    $(this).parent().fadeOut('slow'); 
    $(this).parent().remove(); 
}); 

回答

0

小號有時更容易通過將代碼的一部分設置爲函數來區分代碼,以便條件方面更易於閱讀。

您的代碼中最大的問題是未檢測複選框是否已在點擊處理程序中進行檢查。

由於複選框需要執行的操作與點擊新標籤時的操作相同,因此所有邏輯都會通過複選框的更改事件流動。請注意,在標籤的X單擊處理觸發的變化也

var maxChecked = 6; 

// use change handler on checkboxes, will get triggered also below in another click handler 
var $checkboxes = $('[name=specialty]').change(function() { 
    var value = $(this).val(); 

    if(this.checked){ 
     addTag(value); 
    }else{ 
     removeTag(value); 
    }  
    checkBoxStatus(); 

}); 

function removeTag(checkBoxValue){ 
    /* we stored the checkbox value as data attribute, use that to filter*/ 
    $('.specTag').filter(function(){ 
     return $(this).data('value') === checkBoxValue; 
    }).slideUp(function(){ 
     $(this).remove(); 
    }) 
} 

function addTag(checkBoxValue){ 
    $newTag = $("<div class='specTag'>" + checkBoxValue + "<div class='xOut'>x</div></div>"); 
    /* store the value in elment data so we can reference back to checkbox */ 
    $newTag.data('value', checkBoxValue); 
    $('.Specialties').append($newTag); 

} 
/* use this to both disable and enable checkboxes */ 
function checkBoxStatus(){ 
    var limitReached = $checkboxes.filter(':checked').length === maxChecked; 
    $checkboxes.not(':checked').prop('disabled',limitReached);  
} 

$(document.body).on('click', '.xOut', function() { 
    var $element = $(this).parent(), 
     $checkbox = $checkboxes.filter(function(){ 
      return this.value === $element.data('value'); 
     /* trigger change to remove element and reset disabled checkboxes */ 
     }).prop('checked',false).change(); 


}); 

DEMO

+0

感謝您的幫助,並對邏輯做出了一些解釋。我知道我很接近,我更新與JavaScript和jQuery,所以我仍然摸索了一下。我非常感謝幫助 – Jhauge 2014-11-03 13:38:28

1

嘗試

// When specilaty is checked, add tag to profile page 
 
$('input[name=specialty]').change(function() { 
 
    var value = this.value; 
 

 
    //if checked add a new item else remove item. 
 
    if (this.checked) { 
 
    var $newTag = $("<div class='specTag'>" + value + "<div class='xOut'>x</div></div>").attr('data-id', value); 
 
    $('.Specialties').append($newTag); 
 
    } else { 
 
    //use the attribute value which is the same as the input value to find out the item to be removed 
 
    $('.Specialties').find('div.specTag[data-id="' + value + '"]').remove() 
 
    } 
 

 
    //cache the result since it is used multiple times 
 
    var $checked = $('input[name=specialty]:checked'); 
 

 
    // Count number of checkboxes selected and display in modal 
 
    var increment = $checked.length; 
 
    $('#specCount').html(increment); 
 

 
    // Disable checkboxes when 6 (maximum) are selected 
 
    var bol = increment.length >= 6; 
 
    //use prop instead of attr to set the disabled state 
 
    $("input[type=checkbox][name=specialty]").not(":checked").prop("disabled", bol); 
 

 
    // Create array of checked items - add on checked - remove on uncheck 
 
    var specialtyArray = $checked.map(function() { 
 
    return $(this).val(); 
 
    }); 
 
    console.log(specialtyArray.get()); 
 

 
}); 
 

 
// When Specialties modal closes, uncheck all checked boxes, reset count 
 
$(document.body).on('click', '.close', function() { 
 
    $('.modal-body > #updateSpecForm > .columns').children().prop('checked', false); 
 
    $('#specCount').html(0); 
 
}) 
 

 
// Fade out specialty tags when x is clicked 
 
$(document.body).on('click', '.xOut', function() { 
 
    $(this).parent().fadeOut('slow', function() { 
 
    $(this).remove(); 
 
    }); 
 
    //uncheck the corresponding checkbox 
 
    $('input[name=specialty][value="' + $(this).closest('.specTag').attr('data-id') + '"]').prop('checked', false) 
 
});
.Specialties { 
 
    background-color: #FFFFFF; 
 
    width: 350px; 
 
    height: 135px; 
 
    margin-left: 249px; 
 
    margin-top: 125px; 
 
    top: 0; 
 
    position: absolute; 
 
    z-index: 1; 
 
} 
 
.specTag { 
 
    background-color: #51b848; 
 
    color: #FFFFFF; 
 
    font-weight: 200; 
 
    letter-spacing: 1px; 
 
    font-size: 12px; 
 
    width: 150px; 
 
    height 30px; 
 
    padding: 8px; 
 
    position: relative; 
 
    margin-left: 10px; 
 
    margin-bottom: 5px; 
 
    border-radius: 5px; 
 
    display: inline-block; 
 
} 
 
.xOut { 
 
    background-color: #FFFFFF; 
 
    width: 25px; 
 
    padding: 3px; 
 
    position: absolute; 
 
    right: 5px; 
 
    text-align: center; 
 
    color: #333333; 
 
    top: 5px; 
 
    border-radius: 0 3px 3px 0; 
 
    cursor: pointer; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form action="#" method="GET" id="updateSpecForm"> 
 
    <!-- ATHLETIC TRAINER OPTIONS --> 
 
    <div class="columns" id="athleticTrainer"> 
 
    <input type="checkbox" name="specialty" value="Boot Camp" />Boot Camp 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Children's Fitness" />Children's Fitness 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Circuit Training" />Circuit Training 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Core Training" />Core Training 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Cycling/Spinning" />Cycling/Spinning 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Dance" />Dance 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Flexibility/Balance" />Flexibility/Balance 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Meal Planning" />Meal Planning 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Men's Fitness" />Men's Fitness 
 
    <br /> 
 
    <input type="checkbox" name="specialty" value="Women's Fitness" />Women's Fitness 
 
    <br /> 
 
    </div> 
 
    <div class="Specialties"> 
 
    <!-- SHOW BELOW DIV ONLY IF LOGGED IN --> 
 
    <!-- <div class="updateOn"><a href="#updateSpecialties" class="updateSpecialties" role="button" data-toggle="modal">+ Update My Specialties</a></div> --> 
 
    <!-- ***PRO CAN ADD UP TO 6 SPECIALY TAGS*** --> 
 
    </div> 
 
</form>

+0

謝謝@Arun P約翰尼拉,這是沿着whatI的線路想實現的方式更多。感謝您的快速回復 – Jhauge 2014-11-03 13:36:33

0

工作小提琴:

http://jsfiddle.net/co5w7c9j/1/

// When specilaty is checked, add tag to profile page 
$('[name=specialty]').click(function() { 

$newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>"); 
$(this).attr('value'); 
$('.Specialties').append($newTag); 

EnableDisableCheck(); 


// Create array of checked items - add on checked - remove on uncheck 
specialtyArray = $('[name=specialty]:checked').map(function(){ 
    return $(this).val(); 

    // if item is in the array, then remove it from the DOM 
    if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) { 
    } 
}); 
console.log(specialtyArray.get()); 

}); 

// When Specialties modal closes, uncheck all checked boxes, reset count 
    $(document.body).on('click', '.close', function() { 
    $('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked'); 
    $('#specCount').html(0);  
}) 

// Fade out specialty tags when x is clicked 
$(document.body).on('click', '.xOut', function() { 
    $(this).parent().fadeOut('slow'); 
    $(this).parent().remove(); 
    var text = $(this).parent().text(); 
    $('[name=specialty]:checked').filter(function() { 

     return text.indexOf($(this).val()) > - 1; 

    }).removeAttr('checked'); 
    EnableDisableCheck(); 
}); 

function EnableDisableCheck(){ 
if($('[name=specialty]:checked').length >=5) 
{ 
$('[name=specialty]').attr("disabled","disabled"); 
} 
else 
{ 
$('[name=specialty]').removeAttr("disabled"); 
} 
} 
相關問題