Dynamic Checkboxes getting reset? - javascript

I have a fullcalendar displayed and a list of resources with checkboxes displayed next to their name. They checkboxes show up correctly and if i dont do anything with them they stay checked like they normally would. But, when i call fullcalendar with jquery and go to add or remove a resource, the checkboxes uncheck themselves after running the jquery/fullcalendar functions.
here is how i create the checkboxes:
$(document).ready(function() {
for(p in dsnrs){
$('#specialists').append(
'<input type="checkbox" name="designer" id="' + dsnrs[p].name +'" onChange="addOrRem(dsnrs['+p+'] )" />' +dsnrs[p].name+ '<br />');
}
});
And here are my functions for adding/removing the calendar resources
function addOrRem(spec){
//alert("Specialist: " + spec.name + ", Checked: " +document.getElementById(spec.name).checked);
if(document.getElementById(spec.name).checked==true){
remRes(spec.id);
addRes(spec);
}if(document.getElementById(spec.name).checked=false){
remRes(spec.id);
}
}
function addRes(spec) {
$('#calendar').fullCalendar( 'addEventResource', spec );
}
function remRes(id) {
$('#calendar').fullCalendar( 'removeEventResource', id);
}
Here is the relevant HTML
<div id='designersbox' style='float:left;margin-top:5px'>
<div id='specialists' onload='specList()'></div>
Add resource
Remove resource
</div>
<div id='calbox' style="width:1000px;height:900px;position:relative;float:left;margin-bottom:10px; padding:10px">
<div id='calendar' style="float:left;height:1000px;width:1000px;"></div>
</div>
I'm not really sure why the checkboxes are getting reset. If i comment out the calls to the add/remove functions and just do the alert, they work fine. Any help or clues would be much appreciated.

added a var, checked = document.getElementById(spec.name).checked;
Seemed to fix the problem. I'm not sure why it works, but replacing the if statements with checked==true/false instead of not using the variable fixed the issue.
new function:
function addOrRem(spec){
//$(":checkbox[value=designer]").attr("checked", true);
//alert("Specialist: " + spec.name + ", Checked: " +document.getElementById(spec.name).checked);
var checked = document.getElementById(spec.name).checked;
if(checked==true){
remRes(spec.id, '#calendard');
addRes(spec, '#calendard') ;
}if(checked==false){
remRes(spec.id, '#calendard');
}
}

Related

jQuery Datepicker doesn't overwrite value in dynamically created input, page refresh needed

EDIT1:
So I did managed to fix this problem. But I'm not sure how.
I've been using two identical forms with different IDs for different
reasons (Add and Edit forms). In those forms I had inputs with IDs.
But for both forms I've been using the same ID for the inputs in them.
So I change those IDs to classes (how it should be). I think this was
the reason for the bug.
The second thing I've changed was removing
the first form in a moment I would click on the second form (Edit
form/button) because It was making a trouble, trouble I didn't
addresed in here and I don't think It has anything to do with my
initial problem. Just writing everything I did in any case.
I'm having a problem with jQuery Datepicker and Timepicker. I'll try to describe my situation.
I have dynamically created html for my local storage values (imagine squares with it's own data in it.)
My problem... If I simply load these squares and I want to change something, by clicking on edit button, It will create a form with pre-written values in them, by clicking on one of these inputs, a calendar shows up. And then after clicking on some date, the pre-written value changes with value of a date I've clicked on. Same for Timepicker. But! There is a problem.
If I want to create new squares with new data ( by dynamically creating form with inputs, then the data is saved to local storage) and then (without refreshing the page) clicking on edit button, bringing same old form (as described above) and clicking on some of the inputs, calendar shows up, but after clicking on some date, the value of the input doesn't change. Same with Timepicker, doesn't overwrite the pre-witten value.
But if I refresh the page and want to edit something (without creating new squares/data), Datepicker change the value without problem.
Can you help me please? I'll try to answer any question if needed.
Here is a function that show everything saved in local storage.
function fetchBookmarks() {
var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
bookmarks.sort(function compare(a, b) {
var dateA = new Date(a.date);
var dateB = new Date(b.date);
return dateB - dateA;
});
var results = document.getElementById("results");
results.innerHTML = "";
for (var i = 0; i < bookmarks.length; i++) {
var date = bookmarks[i].date;
var distance = bookmarks[i].distance;
var time = bookmarks[i].time;
results.innerHTML += '<div class="bookmarks shadow p-3 m-2 bg-light rounded">' +
'<div class="row">' +
'<div class="col">' +
'<h3>Date: </h3>' +
'<h3>Distance: </h3>' +
'<h3>Time: </h3>' +
'</h3><input onclick="editBookmarks(\'' + time + '\')" class="btn btn-outline-primary mr-1 btn-lg" id="edit" type="button" value="Edit"><input onclick="deleteBookmarks(\'' + time + '\')" class="btn btn-outline-danger btn-lg" id="deleteBookmarks" type="button" value="Delete">' +
'</div>' +
'<div class="col">' +
'<h3 class="font-weight-bold">' + date + '</h3>' +
'<h3 class="font-weight-bold">' + distance + '</h3>' +
'<h3 class="font-weight-bold">' + time + '</h3>'
'</div>' +
'</div>' +
'</div>';
};
};
And here is function after clicking on edit button...
function editBookmarks(time) {
var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
for (var i = 0; i < bookmarks.length; i++) {
if (bookmarks[i].time == time) {
$(".bookmarks").hide();
results.innerHTML += '<form class="bookmarks shadow p-3 m-2 bg-light rounded" id="editForm">' +
'<h4>Date: </h4><input class="form-control form-control-lg" id="date" placeholder="Select" value="' + bookmarks[i].date + '" type=""><br>' +
'<h4>Distance: </h4><input class="form-control form-control-lg" id="distance" placeholder="In miles" value="' + bookmarks[i].distance + '" type="text"><br>' +
'<h4>Time: </h4><input class="form-control form-control-lg" id="time" placeholder="Select" value="' + bookmarks[i].time + '" type=""><br>' +
'<input class="btn btn-success btn-lg" type="submit" value="Submit">' +
'</form>';
/* $('#date').datepicker()
$('#time').timepicker({
timeFormat: "H:mm",
hourMin: 0,
hourMax: 4
}); */
bookmarks.splice(i, 1);
};
};
$("#editForm").on("submit", function (e) {
var date = $("#date").val();
var distance = $("#distance").val();
var time = $("#time").val();
if (!distance.length || !date.length || !time.length) {
alert("Something missing!")
} else {
var bookmark = {
date: date,
distance: distance,
time: time
};
bookmarks.push(bookmark);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
fetchBookmarks();
$("#editForm").hide();
};
e.preventDefault();
});
$("#search").hide();
};
And here is Datepicker with Timepicker
$('body').on('focus', "#date", function () {
$(this).datepicker();
});
$('body').on('focus', "#time", function () {
$(this).timepicker({
timeFormat: "H:mm",
hourMin: 0,
hourMax: 4
});
});
I know that this is quite much to ask and I'm having a problem with articulating. I'm just lost in this.
I'm thankful for any help.
Here's a link for GitHub file, I think It's better than posting the code here. My whole problem is at the bottom of the file, if you're interested.
https://github.com/ovy1448/MyRun/blob/master/js/main.js
Thanks again.
As per my understanding, since you are using onfocus event to attach datepicker/timepicker, all the event of datepicker/timepicker is not getting attached to the field. I faced similar problem 2-3 years back. What I did is that I added a function for the datepicker onSelect event which updates the field value. You can try this(as below) and let me know if it works
$('body').on('focus', "#date", function () {
$(this).datepicker({onSelect: function(dateStr){
$('body').('#date').val(dateStr);
}});
});
$('body').on('focus', "#time", function () {
$(this).timepicker({
timeFormat: "H:mm",
hourMin: 0,
hourMax: 4,
onSelect: function(timeStr){
$('body').('#time').val(timeStr);
}
});
});
So I did managed to fix this problem. But I'm not sure how. I've been using two identical forms with different IDs for different reasons (Add and Edit forms). In those forms I had inputs with IDs. But for both forms I've been using the same ID for the inputs in them. So I change those IDs to classes (how it should be). I think this was the reason for the bug.
The second thing I've changed was removing the first form in a moment I would click on the second form (Edit form/button) because It was making a trouble, trouble I didn't addresed in here and I don't think It has anything to do with my initial problem. Just writing everything I did in any case.

ESRI Javascript API: Looping to Build a Layer Selection Menu

For reference, please see this: https://developers.arcgis.com/javascript/jssamples/map_dynamiclayerlist.html
But, unlike the ESRI example, I am loading several different Services and each Service has multiple Layers. So I have modified the ESRI code per the following:
var visible = [];
function buildLayerList() {
arrayUtils.forEach(map.layerIds, function (id) {
var currLayer = map.getLayer(id);
var items = arrayUtils.map(currLayer.layerInfos, function (info, index) {
if (info.defaultVisibility) {
visible.push(info.id);
}
return "<input type='checkbox' class='list_item'" + (info.defaultVisibility ? "checked=checked" : "") + "' id='" + info.id + "'' /><label for='" + info.id + "'>" + info.name + "</label>";
});
});
//more code per ESRI
}
But, in my case, the items variable is not getting any values; it is returning as null or not defined. I presume that is because I have basically two loops, unlike ESRI's.
So how do I fix it? I would hate to hard-code the layer selection menu option but may have to if I cant figure this out.
Note: These are all Arcgis Dynamic Layers.
Thanks!
Never mind: All I needed was a Esri Javascript API's 'TOC Widget'; I downloaded that and implemented in my code. Much easier than trying to re-invent the wheel.
Thanks--especially to #Pointy.

jquery on click event doesn't work when using ajax

I am doing an ajax to pull information from a spreadsheet on my google drive, and then using the following code to display them in HTML:
I have this HTML:
<section class="p-booking" id="booking">
<div class="container">
<div class="row">
<div class="event-box">
<!-- caixas puxados do drive -->
</div>
</div>
</section>
And this JS:
$.getJSON(url, function (data) {
var caixasEvento = [];
caixasEvento.push('<div class="col-md-3">');
caixasEvento.push('<div data-id="' + something + '" class="box">');
caixasEvento.push('<h1 class="day">' + something + '</h1>');
caixasEvento.push('<h1 class="local">' + something + '</h1>');
caixasEvento.push('<img class="local-img" src="' + image + '">');
caixasEvento.push('</div>');
caixasEvento.push('</div>');
$('.event-box').append(caixasEvento.join(''));
});
And then I need an alert every time someone clicks the box:
$('.box').on('click', function() {
alert('test')
});
I'm using a script link tag in the bottom of my html document.
the box is normally appearing with all the drive information.
It does not work. I believe that is a problem related to the ajax, because if I create a div with the 'box' class, the alert works.
I'm guessing this is happening because the box element doesn't exist on the page when you try to setup the listener. Try this:
$('.event-box').on('click', '.box', function() {
// do stuff here
});
Try this:
$('.box').each(function()
{
$(this).click(clickHandler);
});
function clickhandler()
{
alert('test')
}

Javascript - Dynamically added tabs not seen as tabs in Kendo panelbar

Ok, first off I read in an encrypted file as my DataSource, which is then converted to an XML String.
The data displays properly in my grids, except that the panels which are dynamically added to the panelbar does not seem to act as such as seen in this fiddle.
They are added to:
<ul id='panelbar'>
<li id='patDet' class='k-state-active'>
<span class='k-link k-state-selected'><input type='checkbox' id='cPatientDetails' /><label for='cPatientDetails'><a href='#' id='cbSelect'></a>Patient Detail</label></span>
<div id='patTab'></div>
</li>
</ul>
like so:
$("<li id = '"+ liID +"' class='k-item k-state-default' role='menuitem' aria-expanded='false' aria-hidden='true'><span class='k-link k-header'><input type='checkbox' id='c" + x + "' class='cbSelect' /><label for='c" + x + "'><a href='#' id='cbSelect''></a>" + liTitle + "</label></span></li>").appendTo("#panelbar");
$("<div id = 'gridGenerate" + x + "' width='400px;' aria-hidden='true'></div>").appendTo("#" + liID);
The reason for the span and link is so that styling can be used on my checkbox which can be found in this fiddle.
At first I used a hard coded DataSource, which worked perfectly, but when I switched over to fetching the data using a request, where all the data displays as it should, except for the panelbar.
This is what it looks like:
when only the first tab should be open. I created the panelbar like so:
$("#panelbar").kendoPanelBar(
{
expandMode: "single"
});
EDIT
I've made it now that the panelbar and grids are only created once the data is retreived and converted, but the issue remains.
Any idea why this is happening?
When KendoUI adds a tab, it does much more than just adding HTML tags. That's why you have methods for adding tabs on demand.
Instead of adding the HTML by hand try using:
var panelbar = $("#panelbar").data("kendoPanelBar");
panelbar.append([
{
text: "<label for='c" + x + "'>" +
"<a href='#' id='cbSelect''></a>" +
"" + liTitle + "" +
"</label>",
encoded: false,
content: "<div>text</div>"
}
]);
Click here to see it in JSFiddle.
Answer:
It seems like when I ask a question, it helps me to find the answer. Just found it.
I created the panelbar before adding the extra panels, so I just moved the:
$("#panelbar").kendoPanelBar(
{
expandMode: "single"
});
to the end of my method. The all the content is added, then I create the panelbar.

Html.CheckBox onclick event is getting escaped

I'm trying to generate a series of check boxes that will update a span to keep track of the number of check boxes that have been checked (shows something like "4 of 12 checked"). I've created the JavaScript function updateSelected that handles that, but it requires the ID of the span and the class of the check boxes to count, so I tried this code to generate each check box:
#Html.CheckBox(string.Format("contentprofilestate[{0}].selected", i),
new { onclick = "updateSelected('" + selectedSpanId + "', '" + checkboxClass + "')" })
This produces the following HTML:
<input id="contentprofilestate_6__selected" name="contentprofilestate[6].selected"
onclick="updateSelected('StMarySpan', 'StMaryCheck')"
type="checkbox" value="true" />
How can I get the onclick event handler to render without escaping the apostrophes? Alternatively, is there a better way to accomplish this task (if so, feel free to use jQuery in your suggestion)?
Note re: Lester
I created a new project and created this view and it still escaped the apostrophes:
#{
ViewBag.Title = "index";
}
<h2>index</h2>
#Html.CheckBox(string.Format("contentprofilestate[{0}].selected", 0), new { onclick = "updateSelected('" + "test" + "', '" + "test2" + "')" })
Alternate Solution
I was not able to figure out how to keep the apostrophes from being escaped, so I wrote some jQuery logic to do what I need without any inline JavaScript:
jQuery(document).ready(function () {
jQuery(':checkbox').click(function () {
var clientHeader = jQuery(this).closest('.client-header');
var clientCheckedSpan = clientHeader.find('.client-checked');
var inputChecked = clientHeader.find('input:checked');
clientCheckedSpan.text(inputChecked.length);
});
});
It's very odd that the apostrophes are being encoded. I didn't think they would be and after doing a quick test they aren't. There's probably something else going on in that view. If you place just that 1 line in an empty view I'm betting you won't get the same problem.
As for any other alternatives, you can easily get the number of selected checkboxes using jQuery:
var numChecked = $("input:checked[id^=contentprofilestate]").size();

Categories