Unexpected token } can not find the mistake - javascript

i tried everything but i don't know where the mistake should be its show me a unespekted token } in a line where i not even have this sign.
<script type="text/javascript">
function postToStatus(action,type,user,ta){
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ><br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+
'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_'+sid+
'"><a href="#" onclick="return false" >onmousedown="deleteStatus("'+sid+
'\',\'status_'+sid+
'\');" title="DELETE THIS STATUS AND ITS REPLIES">delete status</a> ></span><br />'+data+
'</div></div>"'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
}

You need to put a semi-colon after the last } just before the ajax.send() call.
This website is your best friend if you write JavaScript: http://closure-compiler.appspot.com/home
function postToStatus(action, type, user, ta) {
var data = _(ta).value;
if (data == "") {
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if (datArray[0] == "post_ok") {
var sid = datArray[1];
data = data.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, " ><br />").replace(/\r/g, "<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_' + sid + 'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_' + sid + '">delete status ></span><br />' + data + '</div></div>"' + currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
};
ajax.send("action=" + action + "&type=" + type + "&user=" + user + "&data=" + data);
}
;

Related

Adding a parameter to URL with checkbox (jQuery)

I'm adding ?show={COUNTRY CODE} to URL as a parameter. I managed to add it with the code below but can't remove it when you unselect the checkbox.
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results) {
return results[1];
} else {
return 0;
}
}
$('#uc').click(function() {
var country = $(this).val();
var site_url = $('body').data('site-url');
var url = $('body').data('url');
window.location.href = site_url + url + '?show=' + country;
});
if ($.urlParam('show') == $('#uc').val()) {
$('#uc').attr('checked', true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="uc" id="uc" value="UK"> <label for="uc">Only UK</label>
Use the condition to check the checkbox is clicked or not.
if ($(this).is(':checked')) {
console.log(site_url + url + '?show=' + country)
} else {
console.log(site_url + url)
}
Use change() not click() then check with .is(':checked')
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results) {
return results[1];
} else {
return 0;
}
}
$('#uc').change(function() {
var country = $(this).val();
var site_url = $('body').data('site-url');
var url = $('body').data('url');
var site_url = 'google.com' // temp remove later
var url = '/sd/' // temp remove later
if ($(this).is(':checked')) {
console.log(site_url + url + '?show=' + country)
//window.location.href = site_url + url + '?show=' + country; // uncomment later
} else {
console.log(site_url)
//window.location.href = site_url; // uncomment later
}
});
if ($.urlParam('show') == $('#uc').val()) {
$('#uc').attr('checked', true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="uc" id="uc" value="UK"> <label for="uc">Only UK</label>

asp:textbox Uncaught TypeError: Cannot read property 'value' of undefined [duplicate]

This question already has answers here:
Test if something is not undefined in JavaScript
(11 answers)
Closed 6 years ago.
I get this error so my update button doesnt work and I havent updated my database progress because of this error.I want to be visible of textbox and I try to do in .cs side
This javascript codes using checkboxs and textboxs send to cs side with json
function UpdateDetails1() {
var bEnabled = GetCheckBoxVal($("#<%=CB_Enabled_Edit.ClientID%>"));
var bDisplayDetails = GetCheckBoxVal($("#<%=CB_DisplayDetails_Edit.ClientID%>"));
var b3rdParty = GetCheckBoxVal($("#<%=CB_b3rdParty_Edit.ClientID%>"));
var bDisplayOpenNow = GetCheckBoxVal($("#<%=CB_DisplayOpenNow_Edit.ClientID%>"));
var bReservation = GetCheckBoxVal($("#<%=CB_Reservation_Edit.ClientID%>"));
var bPromotion = GetCheckBoxVal($("#<%=CB_Promotion_Edit.ClientID%>"));
var bOnlyPromotion = GetCheckBoxVal($("#<%=CB_OnlyPromotion_Edit.ClientID%>"));
var bAllowFollow = GetCheckBoxVal($("#<%=CB_AllowFollow_Edit.ClientID%>"));
var bAlacarte = GetCheckBoxVal($("#<%=CB_Alacarte_Edit.ClientID%>"));
var bDisplayOpenEat = GetCheckBoxVal($("#<%=CB_DisplayOpenEat_Edit.ClientID%>"));
var Coord_Lat = $("#<%=TB_Coord_Lat_Edit.ClientID%>")[0].value;
var Coord_Long = $("#<%=TB_Coord_Long_Edit.ClientID%>")[0].value;
var Price = $("#<%=TB_Price_Edit.ClientID%>")[0].value;
alert(Price);
var Phone_Number = $('#<%=TB_Phone_Number_Edit.ClientID%>')[0].value;
if (bReservation == true)
$("#display_res_schedule").css("display", "block");
else
$("#display_res_schedule").css("display", "none");
var jsonData = '{ bEnabled: "' + bEnabled + '",' +
'bDisplayDetails: "' + bDisplayDetails + '",' +
'b3rdParty: "' + b3rdParty + '",' +
'Price: "' + Price + '",' +
'bDisplayOpenNow: "' + bDisplayOpenNow + '",' +
'bReservation: "' + bReservation + '",' +
'bPromotion: "' + bPromotion + '",' +
'Phone_Number: "' + Phone_Number + '",' +
'bOnlyPromotion: "' + bOnlyPromotion + '",' +
'bAllowFollow: "' + bAllowFollow + '",' +
'bAlacarte: "' + bAlacarte + '",' +
'bDisplayOpenEat: "' + bDisplayOpenEat + '",' +
'Coord_Lat: "' + Coord_Lat + '",' +
'Coord_Long: "' + Coord_Long + '" }';
alert(jsonData);
// var jsonData = '{ bEnabled: "' + bEnabled + '",' +
// 'bDisplayOpenNow: "' + bDisplayOpenNow + '",' +
// 'bReservation: "' + bReservation + '",' +
// 'Coord_Lat: "' + Coord_Lat + '",' +
// 'Coord_Long: "' + Coord_Long + '" }';
$.ajax({
type: "POST",
url: "Edit.aspx/UpdateDetails1",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: GetDetails1,
failure: function (response) {
alert(response.d);
}
});
}
I need to do visible false checkboxes and textboxes that I don't use.But TB_Phone_Number_Edit.Visible gets Uncaught TypeError: Cannot read property 'value' of undefined error
protected void Page_Load(object sender, EventArgs e)
{
LoadType = Request.QueryString["t"].ToString();
if (LoadType == "Agency")
{
CB_DisplayOpenNow.Visible = false;
CB_DisplayOpenNow_Edit.Visible = false;
CB_Alacarte.Visible = false;
CB_Alacarte_Edit.Visible = false;
CB_DisplayOpenEat.Visible = false;
CB_DisplayOpenEat_Edit.Visible = false;
CB_Reservation.Visible = false;
CB_Reservation_Edit.Visible = false;
CB_Promotion.Visible = false;
CB_Promotion_Edit.Visible = false;
CB_OnlyPromotion.Visible = false;
CB_OnlyPromotion_Edit.Visible = false;
TB_Price_Edit.Visible = false;
DDL_Currency.Visible = false;
DDL_Camera.Visible = false;
CB_AllowFollow.Visible = false;
CB_AllowFollow_Edit.Visible = false;
WhatDoNow.Visible = false;
Alacarte.Visible = false;
WhatEatNow.Visible = false;
Promotion.Visible = false;
Reservation.Visible = false;
OnlyPromotion.Visible = false;
Price.Visible = false;
Camera.Visible = false;
AllowFollow.Visible = false;
Label23.Visible = false;
Label24.Visible = false;
Label25.Visible = false;
Label26.Visible = false;
Label27.Visible = false;
Label29.Visible = false;
Label30.Visible = false;
Label33.Visible = false;
Label34.Visible = false;
TB_Price_Edit.Visible = false;
}
else if(LoadType == "Tour"){
CB_b3rdParty.Visible = false;
CB_b3rdParty_Edit.Visible = false;
CB_Alacarte.Visible = false;
CB_Alacarte_Edit.Visible = false;
DDL_Camera.Visible = false;
CB_AllowFollow.Visible = false;
CB_AllowFollow_Edit.Visible = false;
CB_DisplayOpenEat.Visible = false;
CB_DisplayOpenEat_Edit.Visible = false;
b3rdParty.Visible = false;
Alacarte.Visible = false;
WhatEatNow.Visible = false;
Camera.Visible = false;
AllowFollow.Visible = false;
Label18.Visible = false;
Label24.Visible = false;
Label25.Visible = false;
Label33.Visible = false;
Label34.Visible = false;
Phone_Number.Visible = false;
TB_Phone_Number_Edit.Visible = false;
Label8.Enabled = false;
}
Assuming the problem is not in GetCheckBoxVal any of the following statements is causing your issue:
var Coord_Lat = $("#<%=TB_Coord_Lat_Edit.ClientID%>")[0].value;
var Coord_Long = $("#<%=TB_Coord_Long_Edit.ClientID%>")[0].value;
var Price = $("#<%=TB_Price_Edit.ClientID%>")[0].value;
var Phone_Number = $('#<%=TB_Phone_Number_Edit.ClientID%>')[0].value;
Why? Because if the css selector given to jQuery returns no matches, the array will have zero elements, aka, its length will be 0. That does mean that even on element[0] there is nothing, its value is undefined. Trying to get a property or invoke a method on an undefined value gives you the exception you see.
As the suggested duplicate suggest you should guard against this situation. One possible way is to introduce a utility function:
// this gets the value property of an object and if object is undefined
// returns a default
function getValueOrDefault(someObject, reasonableDefault) {
return someObject === undefined ? reasonableDefault : someObject.value;
}
// your original function
function UpdateDetails1() {
// rest of your code
}
With that function in place your code becomes:
var Coord_Lat = getValueOrDefault($("#<%=TB_Coord_Lat_Edit.ClientID%>")[0], '0.0');
var Coord_Long = getValueOrDefault($("#<%=TB_Coord_Long_Edit.ClientID%>")[0], '0.0');
var Price = getValueOrDefault($("#<%=TB_Price_Edit.ClientID%>")[0],0);
var Phone_Number = getValueOrDefault($('#<%=TB_Phone_Number_Edit.ClientID%>')[0],'+1 010');
That should resolve the Uncaught type error. It is up to you to come up with reasonable defaults.
Setting a textbox to Visible = false makes it not render in your html. So when you try to get the value in your javascript, it effectively does not exist, making it undefined.
To fix this, either replace the textbox by a hidden field or change the opacity so that the textbox is there but transparent.

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.

Getting JSON Object then adding parts to HTML

I have been trying to get a script to work for my Github site and I am processing a JSON file to get an array to HTML in a ordered list.
My code I have been using is:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(mods, function(i) {
var tempUrl = "";
var tempApproved = "";
if (data.mods[i].Repo[0] == 0) {
tempUrl = data.mods[i].Repo[1];
} else if (data.mods[i].Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + data.mods[i].Repo[1] + "/";
} else {
tempUrl = data.mods[i].Repo[1];
}
if (data.mods[i].Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + data.mods[i].Title + "</a> - by " + data.mods[i].Author + "<ul><li>\t- <input type='checkbox' " + tempApproved + "/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
So what have I been doing wrong because nothing is working...
This should work:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(data.mods, function(i, m) {
var tempUrl = "";
var tempApproved = "";
if (m.Repo[0] == 0) {
tempUrl = m.Repo[1];
} else if (m.Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + m.Repo[1] + "/";
} else {
tempUrl = m.Repo[1];
}
if (m.Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + m.Title + "</a> - by " + m.Author + "<ul style='list-style-type:none'><li>\t - <input type='checkbox' " + tempApproved + " disabled/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
Instead of $.each(mods, function(i) { it should be $.each(data.mods, function(i, m) {. and the mods[i]. should be m..
Also there was a formatting error in the JSON file but now it is fixed. It was causing the errors to not display.

Closure object becomes undefined in inner function

It's been a while since I've toyed with my JS, so I might be missing something completely obvious. I have the following:
MyApp.IaeCheckboxCallback = function ($trigger) {
var $checkbox = $trigger.find('input[type="checkbox"]');
$checkbox.on('click', function () {
doIAECallbackNT($trigger.attr('id'), $trigger.data('data-recordid'), $trigger.data('data-recordtype'),
$trigger.data('data-valuejs'), $trigger.data('data-statuselement'), $trigger.data('data-callback'))
});
};
Once inside $checkbox.on, $trigger becomes undefined. How do I prevent this?
Adding more relevant code
I'm tying into this other developer's JS that is in another script file.
function doIAECallbackNT
(
iaeId,
recordId,
recordType,
fieldName,
value,
statusElementId
)
{
doIAECallbackNT(iaeId, recordId, recordType, fieldName, value, statusElementId, function(success) { });
}
function doIAECallbackNT
(
iaeId,
recordId,
recordType,
fieldName,
value,
statusElementId,
callback
)
{
var req = newXMLHttpRequestNT ();
var statusElement = document.getElementById(statusElementId);
setStatusNT(statusElement, "Updating...");
var msg =
"<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:Body>" +
"<HandleRequest xmlns='https://somesite.com/WebService/'>" +
"<iaeId>" + iaeId + "</iaeId>" +
"<recordId>" + recordId + "</recordId>" +
"<recordType>" + recordType + "</recordType>" +
"<fieldName>" + fieldName + "</fieldName>" +
"<value>" + escape(value) + "</value>" +
"</HandleRequest>" +
"</soap:Body>" +
"</soap:Envelope>";
//alert(msg);
req.onreadystatechange = function() {
if (req.readyState == 4) {
var success = false;
try { success = (req.responseXML.documentElement.getElementsByTagName("Success")[0].text.toLowerCase() == "true"); }
catch (e) { success = false; }
var msg2 = "";
//var msg3 = "";
try { msg2 = req.responseXML.documentElement.getElementsByTagName("Message")[0].text; }
catch (e) { msg2 = req.responseText; }
//msg3 = msg2;
if (!success) {
//Error: The string was not recognized as a valid DateTime. There is a unknown word starting at index 2.
if ( msg2.indexOf("valid DateTime") != -1 )
msg2 = "Failed: You entered an invalid date. Please re-enter the date.";
if (msg2.indexOf("StartDate_Must_Be_Before_EndDate") != -1)
msg2 = "Failed: The Start date must be prior to the End date. Try changing the start date first.";
//alert(msg2);
AddFailedNote(msg2);
if (statusElement.tagName.toLowerCase() != 'a')
msg2 = "<span class='error bold'>" + msg2 + "</span>";
}
else if (statusElement.tagName.toLowerCase() != 'a') {
AddSuccessNote(msg2);
msg2 = "<span class='success bold'>" + msg2 + "</span>";
}
setStatusNT(statusElement, msg2);
if (callback != null) { callback(success); }
}
};
req.open("POST", "../Services/IAEService.asmx", true);
req.setRequestHeader("Content-type", "text/xml; charset=utf-8");
req.setRequestHeader("Content-length", msg.length.toString());
req.setRequestHeader("SOAPAction", "https://www.somesite.com/WebService/HandleRequest");
req.send(msg);
}
and here's the ugly .NET rendering of a checkbox:
<span class="IaeCheckboxCallback" title="Ent?" data-recordid="11012" data-recordtype="Person" data-fieldname="HasEnterprise" data-statuselement="MainContent_MainContent_hrmol3_sp_ctl00" data-callback="function() { }" data-valuejs="MainContent_MainContent_hrmol3_dp_ctl00_0.checked" style="font-size:1em;"><input id="MainContent_MainContent_hrmol3_dp_ctl00_0" type="checkbox" name="ctl00$ctl00$MainContent$MainContent$hrmol3$dp$0$tc_HasEnterprise$ctl00" /></span>
The other person's code fails at: f (statusElement.tagName.toLowerCase() != 'a')
All the parameters that I've passed in show as undefined in the browser developer tool.

Categories