Checkbox div double the label? - javascript

I don't know why when a checkbox is clicked, it double the label text associated. Could anyone help me?
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.child').attr('checked', this.checked);
$('.ck,.chkbox,.checkAll ,input:radio').DcustomInput();
});
jQuery.fn.DcustomInput = function(){
$(this).each(function(i){
if($(this).is('[type=checkbox],[type=radio]')){
var input = $(this);
var id=input.attr('id');
// get the associated label using the input's id
var forlabel = $('label[for='+input.attr('id')+']');
var chklabel = forlabel.text();
forlabel.hide();
var label = $("<label for='"+id+"' class='checker'>"+chklabel+"</label>");
//get type, for classname suffix
var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
// alert(label);
// wrap the input + label in a div
$('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input, label);
// find all inputs in this set using the shared name attribute
if(input.is(':disabled')){
if(inputType == 'checkbox' && input.is(':checked')){
label.addClass(' checkedDisabled ');
} else{
label.addClass(' disabled ');
}
}
// necessary for browsers that don't support the :hover pseudo class on labels
label.hover(
function(){
if(!input.is(':disabled') ){
$(this).addClass('hover');
}
if(inputType == 'checkbox' && input.is(':checked') && !input.is(':disabled')){
$(this).addClass('checkedHover');
}
},
function(){ $(this).removeClass('hover checkedHover focus'); }
);
//bind custom event, trigger it, bind click,focus,blur events
input.bind('updateState', function(){
if (input.is(':checked') && !input.is(':disabled')) {
if (input.is(':radio')) {
var allInputs = $('input[name='+input.attr('name')+']');
allInputs.each(function(){
$('label[for='+$(this).attr('id')+']').removeClass('checked');
});
};
label.addClass('checked ');
}
else { label.removeClass('checked checkedHover checkedFocus '); }
})
.trigger('updateState')
.click(function(){
$(this).trigger('updateState');
})
.focus(function(){
label.addClass('focus');
if(inputType == 'checkbox' && input.is(':checked')){
$(this).addClass('checkedFocus');
}
})
.blur(function(){ label.removeClass('focus checkedFocus'); });
}
});
};
</script>

I'm not really aware of what DcustomInput does but I could guess that $('.ck,.chkbox,.checkAll ,input:radio').DcustomInput(); need to be placed on document ready and not on click handler

ok, I've found the solution, just comment these 2 lines:
forlabel.hide();
$('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input, label);
so that the old label is not hidden and we don't try to duplicate the input and the old label.

Related

How to reset or unselect multi select box using jQuery?

I have one bootstrap tab and i create multi select box using jQuery and the all functions are working properly but the RESET button only not working.
i try my all ways but its waste, anyone can you help me..
Please check my full code on fiddle,
MY FULL CODE IS HERE
Just want how to reset the field using jQuery
(function($) {
function refresh_select($select) {
// Clear columns
$select.wrapper.selected.html('');
$select.wrapper.non_selected.html('');
// Get search value
if ($select.wrapper.search) {
var query = $select.wrapper.search.val();
}
var options = [];
// Find all select options
$select.find('option').each(function() {
var $option = $(this);
var value = $option.prop('value');
var label = $option.text();
var selected = $option.is(':selected');
options.push({
value: value,
label: label,
selected: selected,
element: $option,
});
});
// Loop over select options and add to the non-selected and selected columns
options.forEach(function(option) {
var $row = $('<a tabindex="0" role="button" class="item"></a>').text(option.label).data('value', option.value);
// Create clone of row and add to the selected column
if (option.selected) {
$row.addClass('selected');
var $clone = $row.clone();
// Add click handler to mark row as non-selected
$clone.click(function() {
option.element.prop('selected', false);
$select.change();
});
// Add key handler to mark row as selected and make the control accessible
$clone.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', false);
$select.change();
}
});
$select.wrapper.selected.append($clone);
}
// Add click handler to mark row as selected
$row.click(function() {
option.element.prop('selected', 'selected');
$select.change();
});
// Add key handler to mark row as selected and make the control accessible
$row.keypress(function() {
if (event.keyCode === 32 || event.keyCode === 13) {
// Prevent the default action to stop scrolling when space is pressed
event.preventDefault();
option.element.prop('selected', 'selected');
$select.change();
}
});
// Apply search filtering
if (query && query != '' && option.label.toLowerCase().indexOf(query.toLowerCase()) === -1) {
return;
}
$select.wrapper.non_selected.append($row);
});
}
$.fn.multi = function(options) {
var settings = $.extend({
'enable_search': true,
'search_placeholder': 'Search...',
}, options);
return this.each(function() {
var $select = $(this);
// Check if already initalized
if ($select.data('multijs')) {
return;
}
// Make sure multiple is enabled
if (!$select.prop('multiple')) {
return;
}
// Hide select
$select.css('display', 'none');
$select.data('multijs', true);
// Start constructing selector
var $wrapper = $('<div class="multi-wrapper">');
// Add search bar
if (settings.enable_search) {
var $search = $('<input class="search-input" type="text" />').prop('placeholder', settings.search_placeholder);
$search.on('input change keyup', function() {
refresh_select($select);
})
$wrapper.append($search);
$wrapper.search = $search;
}
// Add columns for selected and non-selected
var $non_selected = $('<div class="non-selected-wrapper">');
var $selected = $('<div class="selected-wrapper">');
$wrapper.append($non_selected);
$wrapper.append($selected);
$wrapper.non_selected = $non_selected;
$wrapper.selected = $selected;
$select.wrapper = $wrapper;
// Add multi.js wrapper after select element
$select.after($wrapper);
// Initialize selector with values from select element
refresh_select($select);
// Refresh selector when select values change
$select.change(function() {
refresh_select($select);
});
});
}
})(jQuery);
$(document).ready(function() {
$('select').multi({
search_placeholder: 'Search',
});
});
/* Reset button */
function DeselectListBox() {
var ListBoxObject = document.getElementById("firstData")
for (var i = 0; i < ListBoxObject.length; i++) {
if (ListBoxObject.options[i].selected) {
ListBoxObject.options[i].selected = false
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can trigger the click of your reset button and clear the whole div in your document ready function. After this you can remove the class "selected" so its completely reset.
Like this
$(document).ready(function() {
$('select').multi({
search_placeholder: 'Search',
});
$('#tabReset').click(function() {
$('.selected-wrapper').empty();
$('a').removeClass('selected');
});
});
attach an event to reset button. empty the selected-wrapper and remove the selected class from non-selected-wrapper
$("button.alltabreset").click(function(){
$(".selected-wrapper").empty();
$(".item").removeClass("selected");
});
solution: https://jsfiddle.net/zuov3wmb/

On Checkbox click event, Unable to remove checked="checked' attribute

I have a Jquery Dialog box within my view, In this dialog box there is a UL LI list which is transformed to a treeview. I retain previous checkbox checked selection by adding the checked attribute in my HTML Text Writer helper. What I am trying to do is to remove the checked attribute once its un-checked. I am able to fire the event and get the value for instance true or false for check or uncheck but I am not able to scuccessfully remove the checked attribute if it was checked. The DOM still have the previous state of checked.
HTML Writer
InUl(() => locations.ForEach(location => InLi(() =>
{
var children = this.childrenRenderer(location);
bool childStatus = !(children != null && children.Count() > 0);
if (childStatus)
{
writer.AddAttribute("type", "checkbox");
writer.AddAttribute("value", urlRenderer(location));
writer.AddAttribute("id", htmlPrefix + urlRenderer(location));
writer.AddAttribute("onclick", "handleClick(this)");
if (keys != null)
{
if (keys.Contains(Convert.ToInt32(urlRenderer(location))))
{
writer.AddAttribute("checked", "checked");
}
}
writer.RenderBeginTag("input");
}
writer.Write(locationRenderer(location));
if (childStatus)
{
writer.RenderEndTag();
}
RenderLocations(children);
})));
JS Function
function handleClick(e) {
alert("Click, new value = " + e.checked);
var $this = $(this);
if (e.checked = false) {
$this.removeAttr('checked');
}
}
If I uncheck a checkbox, the following function still gives the old checkbox which is now unchecked:
$("#errorCodes input:checkbox:checked").each(function () {
var v = $(this).val();
a.push(v);
if (errorTextArea.length > 0) {
errorTextArea = errorTextArea + " | ";
}
errorTextArea = errorTextArea + v;
});
Try this:
function handleClick(e) {
alert("Click, new value = " + e.target.checked);
if (e.target.checked == false) {
e.target.removeAttr('checked');
}
}
You have a simple error in your code:
if (e.checked = false)
should read
if (e.checked == false)

Displaying a hidden text box when a particular option value selected

I am trying to make a hidden text-box visible when a particular option value is selected, It works when there are multiple options available obviously because it responds to onChange. How can I get it to work if that is the only option present, the first select box in my Example.
Js Fiddle - http://jsfiddle.net/8bm9R/
This is my Js function
function showOther(fieldObj, otherFieldID) {
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue == 'other') ? '' : 'hidden';
return;
}
I've updated the JsFiddle:
Basically JsFiddle is misused, the function should be set to be wrapped in the header instead of 'onLoad'.
jsfiddle.net/8bm9R/2/
function showOther(fieldObj, otherFieldID)
{
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue=='other') ? '' : 'hidden';
return;
}
Cheers
$("select").change(function() {
if($(this).val() == "expected_value") {
otherFieldObj.style.visibility = "visible"
}
else {
otherFieldObj.style.visibility = "hidden"
}
});

Why is this javascript not working - select box if

I have this code on my site. The idea is to hide a specific class when a specific select box value is selected.
This is my code
$(document).ready(function(){
var txt = 'Marketing';
$("div.ginput_container select#input_3_1 option").each(function(){
if($(this).val()==txt){
$('.mar').hide();
}
});
});
The result I'm getting is .mar class being hidden as soon as the page is loaded. I can't see the error, I have also tryied with
var num = 1
but I have the same issue.
$(document).ready(function() {
var txt = 'Marketing';
$("#input_3_1").change(function () {
if ( this.value == txt ) $('.mar').hide();
});
});
Here's the fiddle: http://jsfiddle.net/9Cyxh/
If you want to show $('.mar') when a different option is selected, use toggle instead:
$('.mar').toggle( this.value != txt );
Here's the fiddle: http://jsfiddle.net/9Cyxh/1/
If you want this to also run on page load (before an option is manually selected), trigger the change event:
$(document).ready(function() {
var txt = 'Marketing';
$("#input_3_1").change(function () {
$('.mar').toggle( this.value != txt );
}).change();
});​
Here's the fiddle: http://jsfiddle.net/9Cyxh/2/
You don't need the loop in the first place
Attach your select to the change() event handler and that should be it..
$(document).ready(function(){
$("select#input_3_1").on('change', function() {
var txt = 'Marketing';
if(this.value === txt){
$('.mar').hide();
};
}).change()
});
If you only want to hide ".mar" class when the value is changed and it equals "Marketing" try
$("#input_3_1").change( function() {
if( $(this).val().toUpperCase() === "MARKETING" ) {
$(".mar").hide();
}
});
Demo here
$("#input_3_1").change(function(){
if ($("#input_3_1").val()=='Marketing'){
$(".mar").hide();
}
});

How to check/uncheck checkboxes by clicking a hyperlink?

I have 11 checkboxes with individual ids inside a modal popup.I want to have a hyperlink called SelectAll,by clicking on which every checkbox got checked.I want this to be done by javascript/jquery.
Please show me how to call the function
You could attach to the click event of the anchor with an id selectall and then set the checked attribute of all checkboxes inside the modal:
$(function() {
$('a#selectall').click(function() {
$('#somecontainerdiv input:checkbox').attr('checked', 'checked');
return false;
});
});
You can do like this in jquery:
$(function(){
$('#link_id').click(function(){
$('input[type="checkbox"]').attr('checked', 'checked');
return false;
});
});
If you have more than one form, you can specify form id like this:
$(function(){
$('#link_id').click(function(){
$('#form_id input[type="checkbox"]').attr('checked', 'checked');
return false;
});
});
This should work, clicking on the element (typically an input, but if you want to use a link remember to also add 'return false;' to prevent the page reloading/moving) with the id of 'selectAllInputsButton' should apply the 'selected="selected"' attribute to all inputs (refine as necessary) with a class name of 'modalCheckboxes'.
This is un-tested, writing on my phone away from my desk, but I think it's functional, if not pretty.
$(document).ready(
function(){
$('#selectAllInputsButton').click(
function(){
$('input.modalCheckboxes').attr('selected','selected');
}
);
}
);
$(function(){
$('#link_id').click(function(e){
e.preventDefault(); // unbind default click event
$('#modalPopup').find(':checkbox').click(); // trigger click event on each checkbox
});
});
function CheckUncheck(obj) {
var pnlPrivacySettings = document.getElementById('pnlPrivacySettings');
var items = pnlPrivacySettings.getElementsByTagName('input');
var btnObj = document.getElementById('hdnCheckUncheck');
if (btnObj.value == '0') {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
if (!items[i].checked) {
items[i].checked = true;
}
}
}
btnObj.value = "1";
}
else {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
if (items[i].checked) {
items[i].checked = false;
}
}
}
btnObj.value = "0";
}
}

Categories