Dropdown list checkbox event not getting triggered on checkbox click - javascript

I am having a dropdown list on the header of data table. The list has multiple checkbox and I want to call an event when the checkbox is checked or unchecked.
During debug, breakpoint is not hitting the checkbox click event. Please let me know how to implement for checkbox click/change event in this scenario.

This is because #chk_select_abst is not rendered at the time of DOM ready when you are binding that event.
For binding events on dynamically added DOMs, you can bind or delegate the event somewhere on its parent DOM node which you are sure will be there on page load and will NEVER be removed/replaced dynamically. Behind the scenes, this make use of event bubbling or event propagation. Check out this link for more info about bubbling.
A safe bet is to use the parent node as body. But, you can and should use a lower parent node (in this case #ul_AbandonedStates) for performance gain.
Documentation for jQuery event delegation.
var json = {
abandonState: [{
Name: 'name 1',
Value: 'value 1'
}, {
Name: 'name 2',
Value: 'value 2'
}]
}
function addCheckBox() {
if (json) {
if (json.abandonState) {
var abandonedStates = json.abandonState;
var li = $('<li>');
var select = $("<label><input id='chk_select_abst' type='checkbox' class='abandonstatecheckclass' value='-1' name='Select All' /> Select All</label>");
var res = li.append(select);
$('#ul_AbandonedStates').append(res);
$.each(abandonedStates, function(index, item) {
var li = $('<li>');
var chk = $("<label><input id='chk_" + item.Value + "' type='checkbox' class='abandoncheckclass' value='" + item.Value + "' name='" + item.Name + "' />" + item.Name + "</label>");
var res = li.append(chk);
$('#ul_AbandonedStates').append(res);
});
var li = $('<li>');
var btn = $('<button id="ul_AbandonedStates_ok" class="btn btn- primary btn- xs" type="button" value="OK">OK</button>');
var res = li.append(btn);
$('#ul_AbandonedStates').append(res);
}
}
}
$(document).ready(function() {
//change here
$("#ul_AbandonedStates").on("click", "#chk_select_abst", function() {
$("#ul_AbandonedStates input:checkbox").prop('checked', $(this).prop('checked'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<th align="center" width="13%" style="position:relative;" index=6 name="abandonedState">
Abandon State
<div class="down-arrow-wrapper">
<ul class="checkbox-list" id="ul_AbandonedStates"></ul>
</div>
<th>
</table>
<button class="add" onclick="addCheckBox()">Add List</button>

Related

How to properly register a click event on a radio button?

I am dynamically creating HTML radio buttons where I am assigning the Id of the input tag to a variable. I want to append a click event handler to these radio buttons using the Id I have assigned. How do I properly use the Id I created to generate a click event? Right now, the event is not being triggered at all.
generateDynamicHTML(function (structure) {
let keys = Object.keys(structure);
keys.forEach(function(key){
let radioButton = $("<input type='radio' name='studentName' id=" + key + "/><label for=" + key + ">" + key + "</label>");
radioButton.appendTo('#studentToggle')
$("#" + key).click(function () {
console.log(key);
})
})
})
I am using the console.log to test if the method was being hit but I am getting empty results. I know the keys are correct because the radio buttons are being created.
Any help would be appreciated.
Thank you.
The problem is that the id added is key/ not key. You should leave a space between " and the closing of the input tag. Or use template literals.
See below
const structure = {
'first': 1,
'second': 2
}
let keys = Object.keys(structure);
keys.forEach(function(key) {
let radioButton = $("<input type='radio' name='studentName' id=" + key + " /><label for=" + key + ">" + key + "</label>");
// or template literals
// let radioButton = $(`<input type='radio' name='studentName' id=${key} /><label for=${key}>${key}</label>`);
radioButton.appendTo('#studentToggle')
$("#" + key).click(function() {
console.log(key);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="studentToggle">
</div>
If you use event delegation, you never have to add extra event handlers to options as long as their parent does not change:
const generateDynamicHTML = function( structure ) {
return Object
.keys( structure )
.map(function( key ) {
return '<input type="radio" name="studentName" id="' + key + '"/><label for="' + key + '">' + key + '</label>';
})
.join( '' );
};
const fields = $( '#student_fields' );
// Add the click handler before any radios
fields.on( 'click', 'input[type="radio"]', function( event ) {
console.log( event.target.id );
});
// Add the radios, the click stil works
fields.append( generateDynamicHTML({
"john": { "age": 21 },
"jane": { "age": 20 }
}));
// Add more radios
fields.append( generateDynamicHTML({
"dave": { "age": 21 },
"joe": { "age": 19 }
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="student_fields">
<legend>Students</legend>
</fieldset>

How to add a function to an appended element

I have an input-text. If you type something, the text appears below (see code snippet).
Now, I need to do the same with a previous step: clicking a button (preferably a checkbox) to append/remove all. Here is my failed idea: DEMO (it appends the input text, but when you type, text won't apear below like it does on my code snippet).
I feel like the function to add text below does not work because there is a problem with selecting the appended element. How do I do this?
Any more simple idea to do this would be great
var name1 = document.getElementById('name');
name1.addEventListener('input', function() {
var result = document.querySelector('.X');
console.log(this.value );
result.innerHTML = this.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>What is your name? </label><input type="text" id="name">
<p>Your name is: <span class="X"></span></p>
Put your first part of the snippet into appending logic while clicking the add button. As in your codes, the input box is appended to the document after its listener being attached.
if (!added) {
$content = $(NewContent).appendTo('.firstappend');
// attach listener after input box actually exists!
var name1 = document.getElementById('A');
name1.addEventListener('input', function() {
var result = document.querySelector('span.Y');
console.log(this.value );
result.innerHTML = this.value;
});
}
$(function() {
let NewContent = '<div class="added">' +
'<p>' +
'<label>What is your name? </label>' +
'<input type="text" id="A">' +
'</p>' +
'<p>Your name is: <span class="Y"></span></p>' +
'</div>';
$(".addremove").on('click', function() {
if ($(".added").length) {
$(".added").remove();
} else {
$(".firstappend").append(NewContent);
}
});
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toadd">
<button type="button" class="addremove">Do you have a name?</button>
</div>
<div class="firstappend"></div>
as from the DEMO you included,
appended elements to document cannot be invoked explicitly, since you're using jQuery, you can do this
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});

Remove one of the added lines on click

I want to only remove the line of the specific .delete that I press. How can I specify that in jQuery. Now it's removing all the p since I've chosen that as the value but I can't figure out how to make it specific for each line of append.
HTML
<div id="menu">
<h3>Shopping list</h3>
<div class="line">
<p class="title">Amount</p>
<p class="title">Product</p>
<p class="title">Price</p>
<div>
<input class='amountInput' type='number' name='quantity' min='0' max='1000' step='1'>
<input class='productInput' type="text" name="message" value="">
<input class='priceInput' type='number' name='quantity' min='0' max='1000000' step='0.01'>
<button class="food">Add</button>
</div>
<div class="messages">
</div>
</div>
</div>
<div class="totalPrice">
</div>
jQuery
$(document).ready(function() {
var totalPrice = 0;
$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = $frm.children(".priceInput").val();
var addAmount = $frm.children(".amountInput").val();
var div = $("<div>");
div.append("<p>" + addAmount + "</p>", "<p id='product'> " + toAdd + " </p>", "<p>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
$frm.parent().children(".messages").append(div);
totalPrice += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);
});
});
$(document).on('click', '.delete', function() {
$('p').remove()
});
If you want to remove the elements that are being added, you'll just need to use $(this) within your function to refer to the element that triggered the call :
// When an element with the delete class is clicked
$(document).on('click', '.delete', function() {
// Remove the closest <div> above the element that was clicked
$(this).closest('div').remove();
});
If you want to update pricing...
When you remove your elements, you may want up consider updating your pricing as well, which you can do by reading your last element and subtracting it :
$(document).on('click', '.delete', function() {
// Get the previous element which contains your price
var priceToSubtract = parseInt($(this).prev().text());
// Subtract the price
totalPrice -= priceToSubtract;
// Update your price
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest('div').remove();
});
This will require you to scope your totalPrice variable outside of your $(document).ready() block as seen below :
<script>
var totalPrice = 0;
$(document).ready(function() {
// Your code here
});
</script>
You should remove the parent div of the all the p, like:
// This is delegated event as the HTML element is added dynamically
$(document).on('click', '.delete', function() {
$(this).closest("div").remove(); // .closest will traverse upwards to find the matched element that is div
});
Note: You need to use event delegation as the HTML elements are added dynamically. Learn more about it here.

Get the Checked and Unchecked table data via jquery

I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});

Cannot put a button in SlickGrid cell

I am trying to put a button in the cells of one of the columns and do something when it's clicked.
For example I add these lines to the SlickGrid example 1 (http://mleibman.github.io/SlickGrid/examples/example1-simple.html)
First to the column array I add:
{id: "Report", name: "Report", field: "Report", width: 40, sortable: true, formatter:reportFormatter}
then I add:
function reportFormatter(row, cell, value, columnDef, dataContext) {
return "<input type='button' value='show' id='reportBtn'/>";
}
$('#reportBtn').click(function() {
alert("hello");
});
The buttons appear in the cells but the click event is not being called !
I must be doing something wrong but can't for the life of me figure it out
can anyone help ?
Thanks!
slick.formatters.js
...
"btnForm": buttonsFormatter // add Slick.Formatters
..
function buttonsFormatter(row, cell, value, columnDef, dataContext) {
return "<input type='button' value='"+value+"' id='btnForm' value2='"+row+"' value3='"+cell+"' onClick='fnBtnClick(this);'/>";
}
add your html Script
function fnBtnClick( objBtn ){
alert( "row::[" + objBtn.value2 + "]\n\ncell::[" + objBtn.value3 + "]" );
}
you should use the grid events not button event like below ,
will call the onclick event of the grid ,
check if the clicked field is your button one
do your action
grid.onClick.subscribe(function (e, args) {
//check if your button was clicked
if ($(e.target).hasClass("btn")) {
var item = dataView.getItem(args.row);
///do your action
}
});
Use the precompiled template slick grid example. Add the property eg. ImageTrial, and in the data structure fill the property with the dynamic input button.
<script type=" " id="testtemplate">
<div class="test">
<b><%=ImageTrial%></b>
<b><%=ImageTrial2%></b>
</div>
dataForCell["ImageTrial"] = "<button type=\"button\" onclick=\"alert('a " + 1 + "')\">s</button>";
dataForCell["ImageTrial2"] = "<button type=\"button\" onclick=\"alert('b " + 2 + "')\">b</button>";
Good Luck

Categories

Resources