removeClass Not working on dynamically Created CheckBox on GoogleMap - javascript

I showed 5 markers on google map with infowindow. Each contents has checkbox.
I am adding div contents to Compare list when user click on each.There is Remove button to remove them back.I want to UnCheck it on remove.Complete code is here JSFIDDLE
I have two issues now
On Each check i want to keep their ids in hidden fields,I tried this code which is not working
var value = [];
var count = 0;
$('#map-canvas input:checked').each(function() {
value+=$(this).attr('value')+',';
count++;
});
$('#cmpIds').val(value);
On Remove button click I want to uncheck each checkbox and hide it.I have this function which is not working for each popup onclick="removeAdd(this);"

There are two main issues with your code. Firstly, you are constructing an array incorrectly. In order to construct an array based on the checkbox value, you do not construct it literally (i.e. by inserting , between values). Instead, you use .push(), i.e.:
var value = [],
count = 0;
$('#map-canvas input:checked').each(function() {
value.push($(this).attr('value'));
count++;
});
$('#cmpIds').val(value);
Secondly, you should also avoid using inline JS for the delete function. Use .on() if you want to bind event handlers to dynamically added elements. Therefore, for the injected markup, simply remove the inline JS reference:
<a class="text-success">Remove</a>
Also, I have used $(this).closest('.media') to find the .parent().parent(), as it is more verbose. You can cache this selector so jQuery wouldn't have to comb through the DOM repeatedly within the same click event:
$(document).on('click', '.text-success', function() {
var $parent = $(this).closest('.media');
// Remove listing
$parent.remove();
// Uncheck associated textbox
var parentID = $parent.attr('id'),
checkboxID = parentID.split('_');
$('#'+checkboxID).prop('checked', false);
});
Working fiddle here: http://jsfiddle.net/teddyrised/z0Lkbmyh/4/
Additional notes: your value array and count variable are reset every time a change event is registered on your checkbox. I suspect, although I cannot confirm, that this is not the desired behavior — I believe you want to keep track of checked properties on the go. Therefore, you should declare both of them outside the .change() handler:
var value = [],
count = 0;
$(document).on('change', '.wrapmap-gist input:checkbox', function() {
$('#map-canvas input:checked').each(function() {
value.push($(this).attr('value'));
count++;
});
$('#cmpIds').val(value);
// Rest of your code here
});

$(document).on('click', '#button-id', function() {
// your code here
});

Related

Updating a value on click once when multiple element exists

I have a fiddle here http://jsfiddle.net/wMUTg/56/ that I'm trying to update a value by one when a button is clicked, only once. Similar to the 'like' functionality on facebook. I've got that working, however if I have multiple elements that are similar only one is updating. I know I have to use the $this functionality but I'm struggling to find where to put it. Also, does anyone know if this can be achieved without an input field? Ideally I'd like it to be in a span tag but I needed the input to get the value first.
$(".red #update").one("click", function() {
var val;
val = $('#counter').val();
val++;
$('#counter').prop('value',val );
});
#CertainPerformance, is right. You should use class instead of same multiple IDs in one DOM.
However here is your solution:
Used $(this).prev('#counter') as selector to refer relevant element.
$(".red #update").one("click", function() {
var val;
val = $(this).prev('#counter').val();
val++;
$(this).prev('#counter').prop('value',val );
});

How do I make the checkbox work on newly created task?

I am writing a todo app using vanilla JavaScript to learn the language without using a library.
In the app, you can add a task, complete task or un-complete task, edit and delete task. I have sample tasks that show the functionality in HTML.
I have a function that adds a task to incomplete tasks section—each task item is wrapped in an li tag and has a checkbox, edit and delete buttons. The addTask function works perfectly.
The problem I am having is in the selectbox part. The app is designed in a way that when checkbox of a task is selected, it indicates a task is completed and thus the item is shown in the completed tasks section. The function works for the items available on the page but not the ones added using the add functionality. How do I make the new task work? Thanks. Here is my HTML Code:
<h3>Todo</h3>
<ul id="incomplete-tasks">
<li><input type="checkbox"><label>Pay Bills</label><button>Edit</button><button>Delete</button></li>
</ul>
<h3>Completed</h3>
<ul id="completed-tasks">
<li><input type="checkbox" checked></input><label>See Doctor</label><button>Edit</button><button>Delete</button></li>
And here is my JS code:
var incompleteTasksHolder = document.getElementById("incomplete-tasks");
var completedTasksHolder = document.getElementById("competed-tasks");
var incompleteTextboxes = incompleteTasksHolder.querySelectorAll("input[type=checkbox]");
for (var i = 0; i < incompleteTextboxes.length; i++) {
incompleteTextboxes[i].onfocus = function() {
var item = this.parentNode;
this.setAttribute("checked", "checked");
completedTasksHolder.appendChild(item);
}
}
You are probably using some event listeners to mark the task as completed when the checkbox changes value.
I think that you just forgot the bind this listener to the new item that you created via Javascript.
When creating your new element bind your listener to it:
taskCB.addEventListener('change', toggleCompleted);
Where taskCB is the checkbox element and toggleCompleted is the name of the function that is fired when a task checkbox is checked or unchecked.
This probably happens because the incompleteTextboxes variable only gets assigned a collection of DOM nodes once. Each time you add a new task, that ends up inside incompleteTasksHolder you should also re-assign an updated collection by re-running the assignment: incompleteTextboxes = incompleteTasksHolder.querySelectorAll("input[type=checkbox]");.
That could look something like this:
var incompleteTasksHolder = document.getElementById("incomplete-tasks"),
completedTasksHolder = document.getElementById("competed-tasks");
// Initialize variable, but create a function for the assignment:
var incompleteTextboxes;
// This function searches the DOM for all checkboxes inside incompleteTasksHolder, and assigns the collection of found elements to incompleteTextboxes:
function refreshIncompleteTasksCollection() {
incompleteTextboxes = incompleteTasksHolder.querySelectorAll("input[type=checkbox]");
}
// You can now re-assign all currently existing checkboxes by calling this function:
refreshIncompleteTasksCollection();
Now, each time there are new elements inside incompletetextboxes, you can run that function to add those to your collection. Note, you'll probably want to re-run your for-loop as well, for binding the focus event handler to your new elements.
A whole different (and in my opinion cleaner) approach would be to use event delegation for your onfocus handlers. Since incompletetextboxes only contains checkboxes inside #incomplete-tasks (by the way you set up your variables), you could use that element to delegate the event handling to. This can be done with addEventListener. You can read more about that here: https://davidwalsh.name/event-delegate.
The main reason I bring this up is because this would solve the problem of missing event handlers for your new elements. What event delegation basically means is, instead of saying:
listen at each incompleteTextbox for a focus event (which means that, when you add new elements you have to say that again for each new element)
you now say:
listen at incompleteTasksHolder for a focus event, and then determine whether that event was fired by a incompleteTextbox. That is possible because your checkboxes live INSIDE #incomplete-tasks. That could look something like this:
incompleteTasksHolder.addEventListener("focus", function(eventObject) {
if (eventObject.target && eventObject.target.matches("input[type=checkbox]")) {
// eventObject.target is the checkbox you want to work with
var checkbox = eventObject.target;
// YOUR CODE:
var item = checkbox.parentNode;
checkbox.setAttribute("checked", "checked");
completedTasksHolder.appendChild(item);
}
});
That means only one listener, that will always work, even for incompleteTextboxes that are inserted after that listener was set.

Assign java scripts to cloned HTML element

I have a html div and I clone it using Jquery. That div contains labels and text fields. ids of all of them generated and assigned dynamically. I have no problem with that.
A java script is assigned to a text field of original div. The cloned text fields does not have the javascript assigned to it.
the script I need to assign:
<script>
$(function() {
$("#datepick_onBooking,#datepick_Pay1,#datepick_Pay2,#datepick_totPay,#datepick_deedFees").datepicker();
});
</script>
the script I use to make clones:
<script>
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#addAnotherPayment').click(function() {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length+2;
cloned.insertBefore("#totPayForm");
// append count to the ids
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('input[type="text"]').attr('id', 'datepick_Pay'+ noOfDivs);
cloned.find('input[type="number"]').attr('id', 'amount_Pay'+ noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i++ + ':');
});
});
</script>
datepick_Pay1, datepick_Pay2, datepick_totPay, datepick_deedFees are static elements and they have been assigned to the script. I create text fields using cloning as datepick_Pay3,datepick_Pay4, and so on.
I cannot figure out how to dynamically assign the script to that newly created elements.How can I do that?
A Boolean indicating whether event handlers and data should be copied along with the elements.
change this line.
var cloned = $('.PayDiv0').first().clone(true);
when you clone something especially elements which having events
use parameter as
clone(true)
But this will be harmfull based on how event is attached on the actual element when copying the events to the cloned element may affect the actual.
You need to clone with events. http://api.jquery.com/clone/
var cloned = $('.PayDiv0').first().clone(true);
Then your script needs to be changed to work for dynamic elements. Here as soon as input elements gets focus, asssign the datepicker based on wild card id selector, if it doesn't already have one.
$(function() {
$('body').on('focus',"input[id^=datepick_]", function(){
if(!$(this).hasClass('.hasdatepicker'))
{
$(this).datepicker();
}
});
});

Jquery, getting 'this' selector from a conditional

I have several elements on my page with the 'checkbox' class. When clicked, a corresponding checkbox input is checked. However, I need to have JQuery check if the checkbox element is active when the page first loads, and check the checkbox input accordingly at that time.
Since there are multiple 'checkbox' classes on my page, I used the 'this' selector previously and it worked fine, however I do not know how to make it do this with my conditional on page load without the .click action that I used before. Here's what I'm trying to make work:
if($('.checkbox').hasClass('active')) {
$('[name="'+$(this).attr('rel')+'"]').prop('checked', true);
}
Obviously the 'this' selector doesn't know what I'm referring to. Is there a better way of doing this? Since it's checking through a bunch of elements and not just one I'm stumped. Thanks!
You can only use this within the context of a jQuery function, so in this scope it's not going to refer to any .checkbox.
You can use .each instead:
$('.checkbox.active').each(function() {
// In this context, this refers to the DOM element represented by .checkbox.active
$('[name="'+this.rel+'"]').prop('checked', true);
});
The each function may suit your needs:
$('.checkbox').each(function() {
var $this = $(this);
if ($this.hasClass('active')) {
$('[name="'+$this.attr('rel')+'"]').prop('checked', true);
}
});
If the checkboxes must be unchecked when the active class is absent, then:
$('.checkbox').each(function() {
var $this = $(this);
$('[name="'+$this.attr('rel')+'"]').prop('checked', $this.hasClass('active'));
});

Highlight just one single row in Jquery

I have a table with lots of rows. The table is there so people can grab data quickly via copy/paste. Trouble is you can easily lose track of where you last grabbed the text from (ie. which row). So I want a function where when you double click on a row (to highlight some text to copy) it then simply highlights the row and stays highlighted until you double click again.
I'm pretty keen to use Jquery.
Here's what I've got so far:
$("tr").dblclick ( function() {
var foo = (this);
$(foo).css("background-color","#333");
$(foo).css("color","white");
});
$("tr").mouseleave ( function() {
var foo = (this);
$(foo).css("background-color","#333");
$(foo).css("color","white");
});
The double click works. But the mouse leave highlights every row. Can I assign one variable to that row I've double clicked, then apply the .mouseleavefunction only to to that? Or is there another function that's better for what I want.
Thanks.
$("tr").dblclick ( function() {
// Unselect the previous selected row Logic
$(this).siblings().removeClass("Clicked");//Assuming the <tr> are at same level.
//$(this).parent().children("tr").not(this).removeClass(".Clicked");
$(this).toggleClass("Clicked");
});
and change the $("tr").mouseleave ( function() {}); to $("document").on( "mouseleave","tr.Clicked",function() {});
Also, its good to have the css like-
.Clicked{
background-color : #333;
color : white;
}
You can add one flag to identify which one is double clicked. And if the flag is true than only apply mouseleave function.
You must also apply delegation method if you assigning event in such case. like all tr or all li.
Plus I didn't got the meaning of mouseleave event here as you are doing same as dblclick event.
var allTr=$('#tableId').find('tr');
$('#tableId').on('.dblclick','tr',function() {
var foo = $(this);
//to remove css and attribute from privous selected tr
allTr.css({"background-color","#333","color","white"}).removeData('clicked')
//if you want to remove css when you double click again on same tr than use this if condition other wise dont use.
if(!foo.data('clicked')){
foo .css({"background-color","#333","color","white"}).data('clicked',true);
}
}).on('mouseleave','tr',function() {
var foo = $(this);
if(foo.data('clicked')){
foo .css({"background-color","#333","color","white"});
}
});
best if u can use JQuery UI Highlight
$("#myTbl tr:first-child").effect("highlight", {}, 3000);
Check Highlight

Categories