jQuery Mobile Page function - javascript

$(document).on("pageshow", "#mappage", function (event) {
$("#doldur").append("<li> <label onclick='getBina("
+ featuressokak[f].attributes.SOKAKID
+ ");'>"
+ featuressokak[f].attributes.SOKAKADI
+ "</label><div onclick='findsokak(" + f + ");' style='float:right;width='20%''><img src='img/map.png' style='float:right;'/></div></li>");
function getBina(sokakid) {}
});
I wrote part of my code. I need to call function getBina inside on mappage function. But I got this error : uncaught ReferenceError: getBina is not defined. So when I wrote function getBina outside mappage function, logicically I got error. I must run on inside. how is it possible ?
my button code :
var content = '<div class="adresbaslik">'+feature.attributes.ADI+'</div><p style="margin-top:-10px"></p><div class="fulladrespopup">'+mahalleadi+' MAHALLESİ '+sokfeature[0].attributes.SOKAKADI +' SOKAK NO:' + numfeature[0].attributes.KAPINO +' '+ilceadi+'</div>' ;
content = content + '<p style="margin-top:-10px"></p><div style="text-align: center ;"><a data-ajax="false" onclick="sendForm("'
+ilceadi+'","'
+mahalleadi+'","'
+sokfeature[0].attributes.SOKAKADI+'","'
+ numfeature[0].attributes.KAPINO+'","'
+ ilcegisID+'","'
+ mahallegisID+'","'
+ sokgetir[0].attributes.GIS_ID+'","'
+ numfeature[0].attributes.KAPINO+'","'
+ feature+'"'
+');" class="formgidin" >Bildirim</a></div>';

write the definition of the function then only it will remove the error "getBina is not defined".
You can write the function globally or you can write function locally.

Related

How do I Get Text from Dynamically created element in JavaScript

I am dynamically creating Div Text in JS and was wondering how I access the various text upon click.
Here is what I have tried so far;
My Dynamically created div
function Message(Side, message) {
var divChat = '<div class="direct-chat-msg ' + Side + '">' +
'<div id="myDiv" class="direct-chat-text">' + message + '</div>' +
'<div id="accountMenu">' +
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
'<li>Preferences</li>' +
'</ul>' +
'</div></div>';
$('#divChatWindow').append(divChat);
}
JS when the li is clicked on.
function getMessage(str) {
alert(str);
}
The error I am getting is:
Uncaught ReferenceError: *whaeverthemessageis* is not defined
at HTMLLIElement.onclick
What is the best solution to solve this problem?
Thanks =)
You have malformed html using single and double quotes. The message is being treated as a variable, not a string, hence the undefined error.
replace:
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
with this:
'<li onclick = "getMessage(\'' + message + '\')" id="replyDiv">Reply</li>' +
I'm not exactly sure what the problem is, but here is a working Playcode

Dynamic Javascript output in templated HTML

I am trying to build a Javascript class which takes some options and returns builds a form. I would like the submit function to be determined by the options passed to the class. All of the HTML is output as expected, but I don't think the javascript that is being output is being parsed. When the HTML renders I get a syntax error -
"Unexpected token function"
and when I try to submit the form I get a
Reference error - "{functionName} is not defined."
Here is the class so far:
var ClassOptionsForm = function(options) {
this.options = options
this.getSubmissionFunction = function() {
switch (this.options.type) {
case 'standard':
return this.standardSubmit;
break;
case 'extendable':
return this.extendableSubmit;
break;
}
}
this.successHandler = "function (data, form) {\
$(form).find('.result').text('Success!').css('color', 'green');\
}"
this.failureHandler = "function (data, form) { \
$(form).find('.result').text('Something went wrong.').css('color', 'red');\
}"
this.submitFunctionName = this.options.optionName + "Submit";
this.standardSubmit = "function " + this.options.optionName + "Submit(form) {\
google.script.run\
.withSuccessHandler(" + this.successHandler + ")\
.withFailureHandler(" + this.failureHandler + ")\
.withUserObject(form)\
.setUserOption('" + this.options.optionName + "', form)\
}"
this.extendableSubmit = "function(this) {\
// Extendable Form Submit
}"
this.buildForm = function() {
var value = this.options.value;
return '\
<script type="text/javascript">\
' + this.getSubmissionFunction() + '\
</script>\
<h3>' + this.options.formTitle + '</h3>\
<form id="' + this.options.optionName + '" onsubmit="' + this.submitFunctionName + '(this)">\
' + Object.keys(value).reduce(function(list, key) {
return list + '<input name="' + key + '" value="' + value[key] + '"/>';
}, '') + '\
<button type="submit">Save</button>\
</form>\
'
}
}
And here is how form render function is called in the HTML file:
<?!= GoogleAnalytics().optionsForm.buildForm(); ?>
And here is the final HTML output:
<script type="text/javascript">
function UAIDSubmit(form) {
google.script.run
.withSuccessHandler(function (data, form) {
$(form).find('.result').text('Success!').css('color', 'green');
})
.withFailureHandler(function (data, form) {
$(form).find('.result').text('Something went wrong.').css('color', 'red');
})
.withUserObject(form)
.setUserOption('UAID', form)
}
</script>
<h3>UAID</h3>
<form id="UAID" onsubmit="UAIDSubmit(this)">
<input name="id" value="********">
<button type="submit">Save</button>
</form>
I am pretty sure that this has something to do with the way that App Script sanitizes HTML, and I know there are a million ways I could accomplish submitting the form without dynamic JS. I am just trying to keep my code as dry as possible, and also I'm curious. Any workarounds that keep that don't involve doing away with templated JS?
When you try to submit the form it won't work because you can use a form object as parameter in a Google Script function but the form object must be the only parameter in that function. Read here[1]
[1] https://developers.google.com/apps-script/guides/html/reference/run

JQuery "Attribute Starts With" Selector Undefined

I have a modal dialog (Bootstrap) that has a list-group with custom list-group-items inside of it (populated by loop using append after adding data from my server).
Inside each list-group-item, I have a Checkbox that will be used to "select" the result. As I populate the items, I hook up the JQuery click event to the respective Checkbox:
// Add to search results
$('#search-results').append(
'<a id="centroid-list-item-' + featureAttrs['ObjectID'] + '" href="\\#"' + 'class="list-group-item" style="outline: 0">' +
'<table style="background: transparent">' +
'<tr>' +
'<td>' +
'<input id="centroid-checkbox-' + featureAttrs['ObjectID'] + '" type="checkbox" value=""> ' +
'</td>' +
'<td>' +
'<h4 class="list-group-item-heading">' +
featureAttrs['UNIQUEID'] +
'</h4>' +
'<p id="centroid-item-text-' + featureAttrs['ObjectID'] + '"' + 'class="list-group-item-text">' +
featureAttrs['NAME'] +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</a>'
);
// When the DOM is ready, add event
$(document).ready(function () {
$('#centroid-checkbox-' + featureAttrs['ObjectID']).click(function (event) {
var objectId = $(this).attr('id').replace(/^\D+/g, '');
console.log(objectId + " was clicked");
if ($(this).is(':checked')) {
// Enable the 'Set Target' button
$('#btn-set-target').removeAttr('disabled');
// Disable all other choices
$('[id^="centroid-checkbox-"]').each(function (event) {
console.log("Picked up values for checkboxes");
if ($(this).attr('id') != ('centroid-checkbox-' + objectId)) {
$(this).attr('disabled', true);
}
});
}
else {
$('#btn-set-target').attr('disabled', 'disabled');
// Enable all text boxes
$('[id^="centroid-checkbox-"]').each(function () {
if (this.attr('id') !== ('centroid-checkbox-' + objectId)) {
this.removeAttr('disabled');
}
});
}
});
});
The problem I am having is that when I call $('[id^="centroid-checkbox-"]') it is returning undefined. However, at the time is gets called, there are about 30 "centroid-checkbox-XXXXX" checkboxes. What am I doing wrong here?
The $ function never returns undefined.
But this in the callback you pass to each is an element, not a jQuery object.
Which means you must use this.id instead of this.attr('id') and $(this).removeAttr('disabled') instead of this.removeAttr('disabled') (and you probably want this.disabled=false or $(this).prop('disabled', false)).
objectId never gets defined because you need to quote enclose the regular expression you're using for replace():
var objectId = $(this).attr('id').replace(/^\D+/g, '');
should be:
var objectId = $(this).attr('id').replace('/^\D+/g', '');
DEMO: http://jsfiddle.net/4fUvn/8/

attempting to split string dynamically keep getting error?

I'm attempting to split a string I'm passing into
$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" + "<br />");
Seems to be passing me the error
SyntaxError: syntax error
splitName(
Not sure how that's wrong...Here is the splitname function if that helps
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("<br /> The second element is " + mySplitResult[1]);
console.log("<br /> The third element is " + mySplitResult[2]);
};
It's too hard to get it right when you put quotes in quotes in quotes and you try to escape it right. You got it wrong.
A solution is to make it in small parts :
var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">...");
But the best solution would be to follow best practice, that is not inline the javascript but use jQuery's binding function :
$("#groupUL").append("... <a id=myid ...");
$("#myid").click(function(){ splitName(response.data[i].from.name) });
I think the only problem with your code is with your readability issue. So I would suggest please improve it. Lets have a look at it. My code example # JSbin.
Here is the code :- (which i think is better)
var response = {
data : {
message: 'Cleaning code',
from: {
name: 'Clean Code works'
}
}
};
var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)
$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
.html(response.data.from.name)
.appendTo(li)
.click(function() {
splitName(response.data.from.name);
});
$('<br>').appendTo(li);
// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("The second element is " + mySplitResult[1]);
console.log("The third element is " + mySplitResult[2]);
}

selection error in jquery with dynamic elements

First of all thanks for reading. I have a problem with jQuery. I am trying to get some data with AJAX and put the result on page with dynamically created div. This works perfect. The problem occurs when I try to select the created div and do something with it
$('.myNewDiv').css('border', '2px solid #000080');
It gives me error in jQuery library
In Chrome debugger it is "Uncaught TypeError: Cannot read property 'slice' of undefined" on line 2234
And in Firebug under firefox "Array.prototype is undefined Line 3324"
I have no idea what is the problem so i'd be grateful for any information
The whole function code:
function AddNextDiv(number) {
var url2 = '<%= ResolveUrl("~/Translate/GetLineDetails") %>';
$.getJSON(url2, { textLineID: LinesIDs[number], TranslatedSubsID: '<%= Html.Encode(Model.OutputSubs.SubsID) %>' }, function (result) {
if (result == "Already in Database") return false;
var myObject1 = JSON.parse(result);
$("#MainField").append("<div class=\"TextLineDiv\">This is line number " + myObject1.LineNumber + " of 423<br/>" + myObject1.TextValue + "<br/><input id=\"TranslationBox" + myObject1.LineNumber + "\" class=\"translationTextBox\" type=\"text\" size=\"20\" /><br/><div id=\"CheckBoxDiv" + myObject1.LineNumber + "\"><input name=\"" + myObject1.LineNumber + "\" class=\"addCheckBox\" onchange=\"HideDiv(this)\" type=\"checkbox\" /><br/><div class=\"NumberDiv\" title=\"" + myObject1.LineNumber + "\" onmouseover=\"CallRefresh(this)\" > This line was translated <div id=\"Translated" + myObject1.LineNumber + "\">" + myObject1.TimesTranslated + "</div> times.</div><br/><br/></div></div>");
$("div#MainField div.TextLineDiv").css('border', '2px solid #000080');
return true;
});
}
`
You can't select things that aren't added to the document yet. If you can restructure your code so that the div can be caught into a variable it would be easy. Otherwise you need to do something like add it to a hidden element then select it. (yuk!)
I suggest using jQuery's DOM tools rather than building everything as a big string of html.

Categories

Resources