Remove() function doesnt work in firebase for web - javascript

This is the js file. What im trying to do is create an onclick delete function when clicked on a particular row in html page. So far i can get the child key(nesting) but somehow the delete function throws error i.e career-delete.html:1 Uncaught ReferenceError: MCu9V4ypS is not defined
at HTMLButtonElement.onclick (career-delete.html:1).
userImagesRef1.once("value", function(snapshot) {
var val1, val2, val3;
var ParentKey = snapshot.key;
console.log("PK"+ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
var childKey = snap.key;
console.log("CK" + childKey);
var Vacancy = snap.child("VacancyNumber").val();
console.log("VacancyNumber" + Vacancy);
// var NoticeNumber = snap.child("Service").val();
// var NameofWork = snap.child("Title").val();
snap.child('pictures').forEach(function(openPicturesSnap){
console.log("KEY LINKS: " + openPicturesSnap.key);
// var i = 0;
if(openPicturesSnap.key == 0){
val1 = openPicturesSnap.val();
// console.log("LINKS1111::::" + val1 );
}
if(openPicturesSnap.key == 1){
val2 = openPicturesSnap.val();
}
if(openPicturesSnap.key == 3){
val1 = openPicturesSnap.val();
}
})
var Service = String(snap.child("Service").val());
// console.log(Service)
var ts = snap.child("timestamp").val();
// console.log("TS:" + ts);
var Title = String(snap.child("Title").val());
// console.log(Title)
let Numberofposts = String(snap.child("NumberofPosts").val());
// console.log(Numberofposts);
var SNo = "";
var State = snap.child("Status").val();
var IssueDate = snap.child("IssueDate").val();
var ClosingDate = snap.child("ClosingDate").val();
var Remarks = String(snap.child("Remarks").val());
$("#tableBody").append("<tr><td>"+ SNo +"</td><td><a href = '" + val1+ "'>" +Vacancy+"</a></td>"+ "<td><a href = '" +val2 + "'>" +Service+"</a></td><td>" + Title + "</td><td>"+Numberofposts+"</td><td>" + IssueDate + "</td><td>"+ClosingDate + "</td> <td>" + State+"<td><a href = '" +val3 + "'>" +Remarks+"</a>"+ "</td><td>"+'<button type="button" onClick=Delete('+childKey+'); class="btn delete">X</button>'+"</td></tr>" );
})
})
function Delete(key){
var feedRef = firebase.database().ref("user-images").child(key);
feedRef.remove()
.then(function(){
console.log("Remove succeeded.")
alert("Added");
// console.log(key.val());
})
.catch(function(error){
console.log("Remove Failed!"+error.message)
});
}
});

You can delete nodes by using the following alternative:
feedRef.set(null);
https://firebase.google.com/docs/database/web/read-and-write#delete_data

You need to add some double quotes as follows:
<button type="button" onclick="Delete('" +childKey+ "');" class="btn delete">X</button>

Related

How to get this data using the loop?

How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>
use foreach loop to iterate over all object
read more from here

How do I remove just the current instance of the array, not all instances of the array?

How do I remove just the current instance of the array, not all instances of the array?
var persons = [];
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
Created new node instances.
for (var l in persons) {
var listNode = document.createElement("LI");
var btn = document.createElement("BUTTON");
btn.innerHTML = "Remove";
showList.appendChild(listNode);
showList.appendChild(btn);
Displays pushed instances correctly.
listNode.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>'
}
Tried a few variations of the following function but just empties the array, or at least wont return the amended array.
btn.onclick = function() {
var index = Array.indexOf(persons[l]);
persons.splice(index, 1);
return persons;
}
if (showAllButton.value=="Show Contacts") {
showAllButton.value = "Hide Contacts";
showList.style.display = "block";
}
else if (showAllButton.value = "Hide Contacts") {
showAllButton.value = "Show Contacts";
showList.style.display = "none";
}
}
probably bind l, remove the element at index l, then redraw the dom somehow.:
btn.onclick = function(l) { //take over the bound l
persons.splice(l, 1);
//some kind of redraw
showAllButton.click();
}.bind(null,l);//bind l
Something like this should work as expected (sorry, blind coding, have no time to test now)
var persons = [];
function removePerson(index) {
persons.splice(index, 1);
renderList();
}
function clearList() {
while (showList.firstChild) {
showList.removeChild(showList.firstChild);
}
}
function renderItem(person, index) {
var item = showList.appendChild(document.createElement("LI"));
var label = item.appendChild(document.createElement("SPAN"));
label.innerHTML = persons[i];
var btn = item.appendChild(document.createElement("BUTTON"));
btn.innerHRML = "Remove";
btn.onclick = removePerson.bind(null, index);
}
function renderList() {
clearList();
persons.forEach(renderItem);
}
Not a kind of best practices, but seems to be working.
Final Working Code, thank you!
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
for (var l in persons) {
var list = showList.appendChild(document.createElement("LI"));
list.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>';
var btn = showList.appendChild(document.createElement("BUTTON"));
btn.innerHTML = "Remove";
btn.onclick = function(l) {
persons.splice(l, 1);
showAllButton.click();
}.bind(null,l);
}

How to use Angular.js to populate multiple select fields using AJAX calls to different endpoints

I apologize up front for the possible lack of clarity for this question, but I'm new to Angular.js and my knowledge of it is still slightly hazy. I have done the Angular.js tutorial and googled for answers, but I haven't found any.
I have multiple select/option html elements, not inside a form element, and I'm populating them using AJAX. Each form field is populated by values from a different SharePoint list. I'm wondering if there is a way to implement this using Angular.js?
I would like to consider building this using Angular because I like some of it features such as data-binding, routing, and organizing code by components. But I can't quite grasp how I could implement it in this situation while coding using the DRY principle.
Currently, I have a single AJAX.js file and I have a Javascript file that contains an array of the different endpoints I need to connect to along with specific query parameters. When my page loads, I loop through the arrays and for each element, I call the GET method and pass it the end-point details.
The code then goes on to find the corresponding select element on the page and appends the option element returned by the ajax call.
I'm new to Angular, but from what I understand, I could create a custom component for each select element. I would place the component on the page and all the select and options that are associated with that component would appear there. The examples I've seen demonstrated, associate the ajax call with the code for the component. I'm thinking that I could use a service and have each component dependent on that service and the component would pass it's specific query details to the service's ajax call.
My current code - Program flow: main -> data retrieval -> object creation | main -> form build.
Called from index.html - creates the multiple query strings that are passed to ajax calls - ajax calls are once for each query string - the very last function in the file is a call to another function to build the form elements.
var snbApp = window.snbApp || {};
snbApp.main = (function () {
var main = {};
main.loadCount = 0;
main.init = function () {
function buildSelectOptions(){
//***
//Build select options from multiple SharePoint lists
//***
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
for(var i = 0; i < listsArray.length; i++){
var listItem = listsArray[i];
var qryStrng = listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
var listDetails = {
listName: listItem.list,
listObj: listItem,
url: "http://myEnv/_vti_bin/listdata.svc/" + listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
};
var clientContext = new SP.ClientContext.get_current();
clientContext.executeQueryAsync(snbApp.dataretriever.letsBuild(listDetails), _onQueryFailed);
}
//***
//Build select option from other API endpoint
//***
var listDetails = {
listName:"SNB_SecondaryActivityCodes",
url: "http://myEnv/requests/odata/v1/Sites?$filter=(IsMajor eq true or IsMinor eq true) and IsActive eq true and IsPending eq false and CodePc ne null and IsSpecialPurpose eq false&$orderby=CodePc"
};
snbApp.dataretriever.letsBuild(listDetails);
}
buildSelectOptions();
//***
//Add delay to populate fields to ensure all data retrieved from AJAX calls
//***
var myObj = setTimeout(delayFieldPopulate,5000);
function delayFieldPopulate(){
var optObj = snbApp.optionsobj.getAllOptions();
var osType = $("input[name=os_platform]:checked").val();
snbApp.formmanager.buildForm(osType, optObj);
}
};
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return main
})();
AJAX calls here - called from main/previous file:
var snbApp = window.snbApp || {};
snbApp.dataretriever = (function () {
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
function getListData(listItem) {
var eventType = event.type;
var baseURL = listItem.url;
$.ajax({
url: baseURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
})
.done(function(results){
snbApp.objectbuilderutility.buildObjectFields(results, listItem);
})
.fail(function(xhr, status, errorThrown){
//console.log("Error:" + errorThrown + ": " + myListName);
});
}
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return{
letsBuild:function(item) {
getListData(item);
}
};
})();
Builds a item name object - called from recursive AJAX calls / previous file
var snbApp = window.snbApp || {};
snbApp.objectbuilderutility = (function () {
function formatItemCode(itemCode, eventType){
if(eventType !== 'change'){ //for load event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(0,3);
}
}else{ //for change event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(3);
}
}
}
return{
buildObjectFields: function(returnedObj, listItem){ //results:returnedObj, prevItem:listItem
//***
//For SharePoint list data
//***
if (listItem.listName !== "SNB_SecondaryActivityCodes") {
var theList = listItem.listName;
var firstQueryParam = listItem.listObj.codeDigits;
var secondQueryParam = listItem.listObj.codeDescription;
var returnedItems = returnedObj.d.results;
var bigStringOptions = "";
//regex to search for SecondaryFunctionCodes in list names
var pattern = /SecondaryFunctionCodes/;
var isSecFunction = pattern.test(theList);
if(isSecFunction){
bigStringOptions = "<option value='0' selected>Not Applicable</option>";
}else{
bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
}
$.each(returnedItems, function (index, item) {
var first = "";
var second = "";
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key != "__metadata") {
if (key == firstQueryParam) {
first = item[key];
}
if (key == secondQueryParam) {
second = item[key];
}
}
}
}
bigStringOptions += "<option value=" + first + " data-code=" + first + ">" + second + "</option>";
});
var str = theList.toLowerCase();
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
//***
//For other API
//***
} else {
var theList = listItem.listName;
var bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
var returnedItems = returnedObj.value;
for(var i = 0; i < returnedItems.length; i++){
var item = returnedItems[i];
//***
//change event type means the user selected a field
//***
if(listItem.eventType === "change"){
var siteCodeChange = item.SiteCodePc;
if (typeof siteCodeChange === "string" & siteCodeChange != "null") {
siteCodeChange = siteCodeChange < 6 ? siteCodeChange : siteCodeChange.slice(3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeChange + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeChange + ") " + item.Name + "</option>";
snbApp.formmanager.buildSelectSiteLocations(bigStringOptions);
//***
//load event which means this happens when the page is loaded
//***
}else{
var siteCodeLoad = item.SiteCodePc;
if (typeof siteCodeLoad === "string" & siteCodeLoad != "null") {
var siteCodeLoad = siteCodeLoad.length < 4 ? siteCodeLoad : siteCodeLoad.slice(0, 3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeLoad + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeLoad + ") " + item.Name + "</option>";
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
}
}
}
}
};
})();
Form management - called from previous file, gets all select elements on page and appends items from the object in previous file to each select element.
var snbApp = window.snbApp || {};
//Direct interface to the form on the page
snbApp.formmanager = (function(){
var form = {};
form.content_holder = document.getElementById("content_holder");
form.sec_act_codes = document.getElementById("snb_secondary_activity_codes");
form.prim_func_codes = document.getElementById("snb_primary_function_codes");
form.sec_func_codes = document.getElementById("snb_secondary_function_codes");
form.sec_func_nums = document.getElementById("snb_secondary_function_numbers");
form.host_options = document.getElementById("snb_host_options");
form.site_locs_div = document.getElementById("site_locations_div");
form.site_locs = document.getElementById("snb_site_locations");
form.dc_or_off_prem_div = document.getElementById("dc_or_off_premise_div");
form.dc_off_prem_codes = document.getElementById("snb_dc_offpremise_codes");
var snb_secondary_activity_codes = "";
var snb_primary_function_codes = "";
var snb_secondary_function_codes = "";
var snb_secondary_function_numbers = "";
var snb_host_options = "";
var snb_site_locations = "";
var snb_dc_op = "";
//builds the server location hosting options selection
function buildLocationTypeSelector() {
var locationOptionsString = "<option value='0' disabled selected>Select Option</option>";
for (var i = 0; i < locationOptions.length; i++) {
var location = locationOptions[i];
locationOptionsString += "<option value=" + location.hostLocale + " data-code=" + location.code + ">" + location.hostLocale + "</option>";
}
$("#snb_host_options").append(locationOptionsString);
}
function buildSiteLocations(bigString){
if(bigString === undefined){
var siteLocs = document.getElementById("snb_site_locations");
var newOption = document.createElement("option");
newOption.setAttribute("value", 0);
newOption.setAttribute("disabled","disabled");
newOption.setAttribute("checked","checked");
var newText = document.createTextNode("Select Option");
newOption.appendChild(newText);
siteLocs.appendChild(newOption);
} else{
var siteLocs = document.getElementById("snb_site_locations");
siteLocs.innerHTML = bigString;
}
}
return {
form:form,
buildSelectSiteLocations: function(bigString){
buildSiteLocations(bigString);
},
buildForm: function (osType, optObj) {
buildLocationTypeSelector();
buildSecondaryFunctionNumberSelector();
buildSiteLocations();
if(osType === 'windows'){
$("#snb_secondary_activity_codes").append(optObj.windows.secondary_activity);
$("#snb_primary_function_codes").append(optObj.windows.primary_function);
$("#snb_secondary_function_codes").append(optObj.windows.secondary_function);
$("#snb_site_locations").append(optObj.windows.site_location);
$("#snb_dc_offpremise_codes").append(optObj.windows.dc_offpremise);
}else{
$("#snb_secondary_activity_codes").append(optObj.unix.secondary_activity);
$("#snb_primary_function_codes").append(optObj.unix.primary_function);
$("#snb_secondary_function_codes").append(optObj.unix.secondary_function);
$("#snb_site_locations").append(optObj.unix.site_location);
$("#snb_dc_offpremise_codes").append(optObj.unix.dc_offpremise);
}
}
};
})();
Thanks in advance.

iPhone jquery/ajax only works for some instances

I have multiple pages across a project I am working on that use AJAX to submit a form to django. All of these buttons work on seemingly everything (mobile and desktop, chrome, firefox, desktop safari) except for mobile safari. Using safari on an iPhone, some of the requests will work, but others won't and I can't seem to figure out why. I have tried to make them all in a similar structure to the one that works, but still, nothing so I figured I'd ask for some help. Thank you in advance!
Here is a working example:
Javascript:
$('#submit').on('click',function(){
dataDict = {csrfmiddlewaretoken:'{{ csrf_token }}'};
dataDict['deleted_exercises'] = deleted_exercises;
var errors = 0;
$('.error').hide();
dataDict['workout_id'] = '{{ workout.id }}';
var exist_exercise_list = [];
$('.existing').each(function(){
//add either new or existing exercise name to exercise list
var ex_name = $(this).find('.ex-name').data('name');
var edit_ex_name_input = $(this).find('.ex-name-input').val();
var ex_name_lower = ex_name.replace(/\s+/g, '-').toLowerCase();
exist_exercise_list.push(ex_name);
var edit_ex_name = ex_name_lower + '-name';
dataDict[edit_ex_name] = edit_ex_name_input;
//add exercise unit to data dict
var edit_ex_unit = $(this).find('.ex-unit').val();
var ex_unit_name = ex_name_lower + '-unit';
dataDict[ex_unit_name] = edit_ex_unit;
//add max event for exercise to data dict
var max_event = $(this).find('.max-event-select').val();
var max_event_name = ex_name_lower + '-max-event';
dataDict[max_event_name] = max_event;
//add color group to data dict
var color_group = $(this).find('.ex-color-select').val();
var color_group_name = ex_name_lower + '-color';
dataDict[color_group_name] = color_group;
//add exercise order to dataDict
var exercise_order = $(this).data('order');
var order_name = ex_name_lower + '-order';
dataDict[order_name] = exercise_order;
//add exercise notes
var notes = $(this).find('.ex-notes').val();
var notes_name = ex_name_lower + '-notes';
dataDict[notes_name] = notes;
//
var sets = $(this).find('.exist-set');
var num_sets = $(sets).length;
var num_sets_name = ex_name_lower + '-num-sets';
dataDict[num_sets_name] = num_sets;
$(sets).each(function(){
var set_num = $(this).find('.set-num').data('number');
//add target weight for this set to dataDict
var target_weight = $(this).find('.weight').val();
if (target_weight != '' && Math.round(target_weight) !== parseInt(target_weight)){
errors = errors + 1;
$(this).find('.weight').before("<span class='error' style='color: #FF4444'>Please enter a valid weight</span>");
}
var target_weight_name = ex_name_lower + '-set-' + set_num + '-weight';
dataDict[target_weight_name] = target_weight;
//add max percentage to dataDict
var max_percent = $(this).find('.percentage').val();
if (max_percent != '' && isNaN(max_percent)){
errors = errors + 1;
$(this).find('.percentage').before("<span class='error' style='color: #FF4444'>Please enter a valid percent</span>");
}
var max_percent_name = ex_name_lower + '-set-' + set_num + '-percent';
dataDict[max_percent_name] = max_percent;
//add reps to dataDict
var reps = $(this).find('.reps').val();
if (reps != '' && Math.round(reps) !== parseInt(reps)){
errors = errors + 1;
$(this).find('.reps').before("<span class='error' style='color: #FF4444'>Please enter a valid rep number</span>");
}
var reps_name = ex_name_lower + '-set-' + set_num + '-reps';
dataDict[reps_name] = reps;
})
var added_sets_list = [];
var added_sets = $(this).find('.new-set');
$(added_sets).each(function(){
var set_num = $(this).find('.set-num').data('number');
var target_weight = $(this).find('.target-weight-input').val();
if (target_weight != '' && Math.round(target_weight) !== parseInt(target_weight)){
errors = errors + 1;
$(this).find('.target-weight-input').before("<span class='error' style='color: #FF4444'>Please enter a valid weight</span>");
}
var max_percent = $(this).find('.max-percent').val();
if (max_percent != '' && isNaN(max_percent)){
errors = errors + 1;
$(this).find('.max-percent').before("<span class='error' style='color: #FF4444'>Please enter a valid percent</span>")
}
var reps = $(this).find('.reps').val();
if (reps == '' || Math.round(reps) !== parseInt(reps)){
errors = errors + 1;
$(this).find('.reps').before("<span class='error' style='color: #FF4444'>Please enter a valid rep number</span>");
}
var add_set = set_num + '_-&&-_' + target_weight + '_-&&-_' + max_percent + '_-&&-_' + reps;
added_sets_list.push(add_set);
})
var added_sets_name = ex_name_lower + '-added-sets';
dataDict[added_sets_name] = added_sets_list;
})
var new_exercises = [];
$('.new-ex').each(function(){
var new_ex_name = $(this).find('.new-ex-name').val();
if (new_ex_name == ''){
errors = errors + 1;
$(this).find('.new-ex-name').before("<span class='error' style='color: #FF4444'>Please enter an exercise name</span>")
}
new_exercises.push(new_ex_name);
var new_ex_name_lower = new_ex_name.replace(/\s+/g, '-').toLowerCase();
var new_ex_order = $(this).data('order');
var new_ex_order_name = new_ex_name_lower + '-order-new';
dataDict[new_ex_order_name] = new_ex_order;
var new_ex_unit = $(this).find('.new-ex-unit').val();
var new_ex_unit_name = new_ex_name_lower + '-unit-new';
dataDict[new_ex_unit_name] = new_ex_unit;
var new_ex_max_event = $(this).find('.new-ex-max-event').val();
var new_ex_max_event_name = new_ex_name_lower + '-max-event-new';
dataDict[new_ex_max_event_name] = new_ex_max_event;
var new_ex_color = $(this).find('.new-ex-color-select').val();
var new_ex_color_name = new_ex_name_lower + '-color-new';
dataDict[new_ex_color_name] = new_ex_color;
var new_ex_notes = $(this).find('.new-ex-notes').val();
var new_ex_notes_name = new_ex_name_lower + '-notes-new';
dataDict[new_ex_notes_name] = new_ex_notes;
var new_ex_sets = $(this).find('.set');
var num_set_new = $(new_ex_sets).length;
var num_set_new_name = new_ex_name_lower + '-num-sets-new';
dataDict[num_set_new_name] = num_set_new;
$(new_ex_sets).each(function(){
var set_num = $(this).find('.set-num').data('number');
var weight = $(this).find('.target-weight-input').val();
if (weight != '' && Math.round(weight) !== parseInt(weight)){
errors = errors + 1;
$(this).find('.target-weight-input').before("<span class='error' style='color: #FF4444'>Please enter a valid weight</span>");
}
var weight_name = new_ex_name_lower + '-set-' + set_num + '-weight-new';
dataDict[weight_name] = weight;
var percent = $(this).find('.max-percent').val();
if (percent != '' && isNaN(percent)){
errors = errors + 1;
$(this).find('.max-percent').before("<span class='error' style='color: #FF4444'>Please enter a valid percentage</span>");
}
var percent_name = new_ex_name_lower + '-set-' + set_num + '-percent-new';
dataDict[percent_name] = percent;
var reps = $(this).find('.reps').val();
if (reps == '' || Math.round(reps) !== parseInt(reps)){
errors = errors + 1;
$(this).find('.reps').before("<span class='error' style='color: #FF4444'>Please enter a valid rep number</span>");
}
var reps_name = new_ex_name_lower + '-set-' + set_num + '-reps-new';
dataDict[reps_name] = reps;
})
})
dataDict['removed_sets'] = removed_sets;
dataDict['deleted_exercises'] = deleted_exercises;
dataDict['existing_exercises'] = exist_exercise_list;
dataDict['new_exercises'] = new_exercises;
if (errors == 0){
$.ajax({
url: "/edit_athlete_workout/",
type: 'POST',
data: dataDict,
success : function() {
window.location.reload(true);
},
error : function(xhr,errmsg,err) {
$('#result').append("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
})
Button:
<button class='btn' id='submit' type='button'>Submit</button>
And one that doesn't work:
$('#complete-wo').on('click',function(){
event.preventDefault();
results = {csrfmiddlewaretoken:'{{ csrf_token }}'};
$('.errorDesc').remove();
var ex_ids = [];
var errors = 0;
results['exercises'] = ex_ids;
$('.ex-id').each(function(i, obj){
var exercise_id = $(obj).val()
ex_ids.push(exercise_id);
var reps_comp = $('input[name="reps-ex-'+ exercise_id + '"').val();
if (reps_comp == '' || Math.round(reps_comp) !== parseInt(reps_comp)){
errors = errors + 1;
$('input[name="reps-ex-'+ exercise_id + '"').before('<div class="errorDesc" style="color: #FF0000"> Enter a valid rep number</div>');
}
var load_comp = $('input[name="load-ex-'+ exercise_id + '"').val();
if (load_comp == '' || Math.round(load_comp) !== parseInt(load_comp)){
errors = errors + 1;
$('input[name="load-ex-'+ exercise_id + '"').before('<div class="errorDesc" style="color: #FF0000"> Enter a valid weight</div>');
}
results['reps-ex-' + exercise_id] = reps_comp;
results['load-ex-' + exercise_id] = load_comp;
//alert(exercise_id + '/' + results['reps-ex-' + exercise_id] + results['load-ex-' + exercise_id]);
})
if (errors == 0){
$.ajax({
url: "/submit_workout/",
type: 'POST',
data: results,
success : function() {
window.location.href = '/player_calendar/';
},
error : function(xhr,errmsg,err) {
$('#result').append("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
});
Button:
<button class='btn btn-primary btn-block' id='complete-wo' type='button'>Workout Complete</button>
I found a solution to this problem. For some reason, on mobile safari, there was a problem with selecting the inputs using:
var reps_comp = $('input[name="reps-ex-'+ exercise_id + '"').val();
load_comp = $('input[name="load-ex-'+ exercise_id + '"').val();
The page worked fine once I switched these to just be class-based selectors.

I need Javascript syntax and logic advice

I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...

Categories