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

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)

Related

Conditional jQuery validation based on custom attribute

I'd like to enable/disable buttons on key up change conditionally based on a custom data attribute that matches between an input and a button. I've solved it with just one input, but it seems that when I add another one in the mix, the buttons don't seem to enable.
Furthermore, I have a hunch that it's because of .each() but I can't put my finger on it.
Here's the CodePen I've tried and failed on
var validation = $('[data-validation]');
var validate;
validation.on("change keyup", function (e) {
let validated = true;
validation.each(function () {
let value = this.value;
validate = $(this).data('validation');
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
});
if (validated) {
$('[data-validator=' + validate + ']').prop("disabled", true);
} else {
$('[data-validator=' + validate + ']').prop("disabled", false);
}
});
The key here is to only run your validation code for the input that was changed. As opposed to what you have, which is to run for all inputs.
To get the input that actually changed, you can utilize the .target property of the event object passed to the event handler.
Alternatively, if you remove the validation.each() entirely, it also works. That is because jQuery sets the value of this to be the DOM element (not a jQuery-wrapped element) that actually triggered the event.
var validation = $("[data-validation]");
var validate;
validation.on("change keyup", function (e) {
let validated = true;
let value = this.value;
validate = $(this).data("validation");
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
if (validated) {
$("[data-validator=" + validate + "]").prop("disabled", true);
} else {
$("[data-validator=" + validate + "]").prop("disabled", false);
}
});

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/

If radio button is selected show alert

I want an alert to show when i click a radio button.
My radio buttons:
<div class="genericFormField">
New:#Html.RadioButtonFor(m => m.Form.InstallType, 1, Model.InstallationHeader.InstallType == 1 ? new { Checked = "checked" } : null )
Pool:#Html.RadioButtonFor(m => m.Form.InstallType, 2, Model.InstallationHeader.InstallType == 2 ? new { Checked = "checked" } : null)
Refurb:#Html.RadioButtonFor(m => m.Form.InstallType, 3, Model.InstallationHeader.InstallType == 3 ? new { Checked = "checked" } : null)
</div>
So if the radio button new is selected i want an alert to say "NEW" otherwise nothing.
Normally it is easy because you have id but in this occasion there is no ID?
As this is RadioButtonFor.
Thanks
New code
Full code:
$('input[name="Form.InstallType"]').on('change', function() {
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === '1') {
var validOptions = "#Url.Action("SerialProdNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val();
previousValue = "";
$('#abc').autocomplete({
autoFocus: true,
source: validOptions,
}).change(function(){
var source = validOptions;
var found = $('.ui-autocomplete li').text().search(source);
console.debug('found:' + found);
var val = $('input[name="Form.InstallType"]:checked').val();
if (found < 0 && val === '1') {
$(this).val('');
alert("Please choose from auto complete");
}
});
}
});
This works, however if the radio button is on page load it doesnt work, i have to click another radio button and then click "new" and then it will work..
any chance it works on if its checked already rather than when check.
#Html.RadioButtonFor creates a proper input with name and id attributes.
You can access the value this way:
$('input[name="Form.InstallType"]:checked').val();
Not sure about generated radios' name as it is an inner variable.
Render page and look at generated name. This is how it looks in my case.
Now, about your alert. You need to listen to change event.
$('input[name="Form.InstallType"]').on('change', function()
{
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === '1') alert('New');
});
Why '1'? Because you have set it in the ASP.NET code.
This is how it should look like.
<div class="genericFormField">
New: #Html.RadioButtonFor(m => m.Form.InstallType, 'new')
Pool: #Html.RadioButtonFor(m => m.Form.InstallType, 'pool')
Refurb: #Html.RadioButtonFor(m => m.Form.InstallType, 'refurb')
</div>
<script>
$(document).ready(function() {
AlertIfNewIsSelected(); // Check if it is selected on page load. According to the question in comments.
$('input[name="Form.InstallType"]').on('change', AlertIfNewIsSelected);
});
function AlertIfNewIsSelected()
{
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === 'new') alert('New');
}
</script>
Of course, it all can be reached without using jQuery.

Changing value separation from "," to "-" (JS/Jquery)

I received some Jquery code for an HTML checkbox. Essentially, when checked, the value of the checkbox is placed in an input box. When I uncheck the box, the value is cleared from the input. However, when you check multiple checkboxes, a "," separates the values. Is there a way to seperate the values by "-" instead of ","? I tried playing around with the code and it just breaks the code. I am fairly new to JS/Jquery so if it is a simple answer, I apologize. I can provide more information if needed. A working JSFiddle with "," is here: https://jsfiddle.net/m240Laka/25/
My code is located here:
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice");
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(",").filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join());
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join());
}
}
});
$none.on("change", function () {
var $this = $(this),
isThisChecked = $this.prop("checked");
if(isThisChecked){
$choice.prop({
disabled: true,
checked : false
});
$choiceDisplay.val("");
}else{
$choice.prop({disabled: false});
return false;
}
});
In the functions join() and split(), you need to pass in the delimiter you want, '-'. I suggest creating a local variable that you use, so it is easier to change this if needed.
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice"),
delimiter = '-';
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(delimiter).filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
}
});
Here is it in a jsfiddle.
In $.join() add the separator string parameter:
$choiceDisplay.val(choiceSelectionsArray.join("-"));
UPDATE:
add the same in $.split()
choiceSelectionsArray = $choiceDisplay.val().split("-")....

Checkbox div double the label?

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.

Categories