var settings = {};
$(".js-gen-settings").each(function(){
var date;
if (($(this).attr("type") === "checkbox") || ($(this).attr("type") === "radio")){//if its a checkbox
eval("settings."+this.name+" = "+$(this).is(":checked"));
}else{
date = $(this).val();
if (date == ""){
eval("settings." + this.name + " = null");
}else{
eval("settings." + this.name + " = '" + date + "'");
}
}
});
a JSON.stringify version of settings will be sent to the server using ajax.
If you want to modify a property of an object dynamically, you just put the name in [brackets].
settings[this.name] = null
settings[this.name] = date;
settings[this.name] = $(this).is(":checked");
change:
eval("settings." + this.name + " = null")
to
settings[this.name] = null;
I'm sure you can figure out the rest :)
Here, I've re-factored your code:
$( '.js-gen-settings' ).each(function () {
if ( $( this ).is( ':checkbox, :radio' ) ) {
settings[ this.name ] = this.checked;
} else {
settings[ this.name ] = this.value ? this.value : null;
}
});
Related
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.
Im working in a chat system very simple. But i have a problem. I can only get the other user messages if i close and re open the chat conversation div, then the message appears.
How can I solve this? The problem should be in this piece of code. As I am not very comfortable with ajax I ask for your help.
JS:
$(document).ready(function(){
var snd = new Audio("images/new_msg.wav");
var open=Array();
$("#jd-chat .jd-online_user").click(function(){
var user_name = $.trim($(this).text());
var id = $.trim($(this).attr("id"));
if($.inArray(id,open) !== -1 )
return
open.push(id);
$("#jd-chat").prepend('<div class="jd-user">\
<div class="jd-header" id="' + id + '">' + user_name + '<span class="close-this"> X </span></div>\
<div class="jd-body"></div>\
<div class="jd-footer"><input id="textareabox" placeholder="escrever..."></div>\
</div>');
$.ajax({
url:'chat.class.php',
type:'POST',
data:'get_all_msg=true&user=' + id ,
success:function(data){
$("#jd-chat").find(".jd-user:first .jd-body").append("<span style='display:block' class='me'> " + data + "</span>");
}
});
});
$("#jd-chat").delegate(".close-this","click",function(){
removeItem = $(this).parents(".jd-header").attr("id");
$(this).parents(".jd-user").remove();
open = $.grep(open, function(value) {
return value != removeItem;
});
});
$("#jd-chat").delegate(".jd-header","click",function(){
var box=$(this).parents(".jd-user,.jd-online");
$(box).find(".jd-body,.jd-footer").slideToggle();
});
$("#search_chat").keyup(function(){
var val = $.trim($(this).val());
$(".jd-online .jd-body").find("span").each(function(){
if ($(this).text().search(new RegExp(val, "i")) < 0 )
{
$(this).fadeOut();
}
else
{
$(this).show();
}
});
});
$("#jd-chat").delegate(".jd-user input","keyup",function(e){
if(e.keyCode == 13 )
{
var $cont = $('.jd-body');
var box=$(this).parents(".jd-user");
var msg=$(box).find("input").val();
var to = $.trim($(box).find(".jd-header").attr("id"));
$.ajax({
url:'chat.class.php',
type:'POST',
data:'send=true&to=' + to + '&msg=' + msg,
success:function(data){
$('#textareabox').val('');
$(box).find(".jd-body").append("<span style='display:block' class='me'> " + msg + "</span>");
$cont[0].scrollTop = $cont[0].scrollHeight;
$cont.append('<span>' + $(this).val() + '</span>');
$cont[0].scrollTop = $cont[0].scrollHeight;
$(this).val('');
}
});
}
});
function message_cycle()
{
$.ajax({
url:'chat.class.php',
type:'POST',
data:'unread=true',
dataType:'JSON',
success:function(data){
$.each(data , function( index, obj ) {
var user = index;
var box = $("#jd-chat").find("div#2").parents(".jd-user");
$(".jd-online").find(".light").hide();
$.each(obj, function( key, value ) {
if($.inArray(user,open) !== -1 )
$(box).find(".jd-body").append("<span style='display:block' class='other'> " + value + "</span>");
else
snd.play();
$(".jd-online").find("span#" + user + " .light").show();
});
});
}
});
}
setInterval(message_cycle,1000);
});
How messages are displayed when you first open the chat conv div ?
I'm assuming message_cycle() is supposed to display new messages in your div every second, i suppose your problem is here...
I'm not really confortable with this :
var box = $("#jd-chat").find("div#2").parents(".jd-user");
A div can't have an id starting with a number, you need <div id="chat2"> instead of <div id="2">.
After your line add a console.log('Box found : '+box.length) ; just to make sure your box is correctly found in message_cycle.
I am writing an extension for a text-editor (Brackets) that can generate HTML and append libraries automatically in the HTML.
I have an Object called 'choice'.
This modal requests the users input:
choice grabs the user's input by defining methods on choice
partial JS here:
var choice = new Object();
choice.language = function () {
//Buid HTML top 'head'
var htmlTop = "<!DOCTYPE html>" + "<html>" + "<head lang='";
//Grab Selected Language Type
var languageChoice = document.getElementById("languages").value;
//Determine what Selected Language type is and complete HTML 'head'
if (languageChoice === "english") {
languageChoice = "en";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "german") {
languageChoice = "de";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "spanish") {
languageChoice = "es";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "french") {
languageChoice = "fr";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "italian") {
languageChoice = "it";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "chinese") {
languageChoice = "zh-cn";
return htmlTop + languageChoice + "'>";
}
}; //end choice.language
choice.charset = function () {
//Build meta and the rest of the 'head tag'
var htmlCharset_Beginning = "<meta charset='";
var htmlCharset_End = "'>" + "<title> -Insert Title- </title>" + "<!-- Insert CSS links below -->" + "</head>" + "<body>";
var charsetChoice = document.getElementById("charset").value;
if (charsetChoice === "utf8") {
charsetChoice = "UTF-8";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
} else {
charsetChoice = "UTF-16";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
}
}; // end choice.charset
choice.doctype = function () {
var doctypeChoice = document.getElementById("doctype").value;
return doctypeChoice;
}; // end doctype
choice.libraries = function () {
var checkedBoxes = getCheckedBoxes("lib_checkboxes");
checkedBoxes.forEach(function(item){
var scripts =+ $(item).data('script');
});//End forEach
var bottomHTML = scripts + "</body>" + "</html>";
return bottomHTML;
}; //End choice.libraries
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
//Get checkedBoxes function
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
} // End action();
//JEFF STOP CODING HERE
// Register the commands and insert in the File menu
CommandManager.register(Strings.MENU_COMMAND, 'templates', action);
var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
menu.addMenuDivider();
menu.addMenuItem('templates');
}); //end define;
QUESTION:
Can I save multiple methods (each method returns a string) as a variable?
Example here:
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
My code is loading with no errors, but its not executing at all so I am trying to debug and figure out what is going wrong...
Before you realize the function 'chosenTemplate', you should check whether the document stream of the page has already downloaded. If it not, you may not be able to get the value of the widget (empty).
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.
I have a function for updating multiple selects based on values of another select.
How can I edit this function to use it without prototype just with jquery ?
function replace(val) {
if (val != 0) {
$$('select.replace).each(function(e) {
var aa = e.value.split("_");
if (aa[0] = val) {
e.value = val + "_" + aa[1] + "_" + aa[2];
jQuery("select.replace").trigger("chosen:updated");
}
});
} else {
alert('Please select a valid value');
return false;
}
}
It's simple:
jQuery( 'select.replace' ).each(function() {
var aa = $( this ).val().split("_");
if (aa[0] = val) {
$( this ).val( val + "_" + aa[1] + "_" + aa[2] );
//...
Red more about jQuery val() method.
Try using .change() when the select value is changed.
$( ".target" ).change(function() {
// code here
});