2014-11-03 52 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"); 
} 
} 
相关问题