JQuery Method is not defined - javascript

I have the following JS/JQuery in the body of a my JQM (html) site, when I try to call sortMethod() I get 'ReferenceError: sortMethod is not defined' in FireBug console.
<script>
$(function(){
$("[name=radio-choice-h-3]").change(function() {
//alert('Selected: '+$('input[name=radio-choice-h-3]:checked').val());
sessionStorage.sortBy = $('input[name=radio-choice-h-3]:checked').val();
sortMethod();
});
});
$(function(){
sortMethod();
});
$(function sortMethod(){
if(sessionStorage.sortBy === "model" || sessionStorage.sortBy == null || sessionStorage.sortBy.trim())
{
theManufacturers('model');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2a", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "year")
{
theManufacturers('year');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2b", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "location")
{
theManufacturers('location');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2c", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === 'ttaf')
{
theManufacturers("ttaf");
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2d", page).prop("checked", true).checkboxradio("refresh");
});
}
});
$(function theManufacturers(inputSearch){
var qryString = 0;
//set up string for adding <li/>
var li = "";
var jqxhr = $.getJSON("url",
function(data){
$.each(data.items, function(i,item){
li+='<li><img src="' + item.Image.trim() + '" style="height:80px;/> <span style="font-size:0.75em;">' + item.Manufacturer.trim() + ' ' + item.Model.trim() + '(' + item.Price.trim() + ')</span><br/><span style="font-size:0.65em;">S/N: ' + item.Serial.trim() + ' | TTAF: ' + item.TTAF.trim() + ' | LOC: ' + item.Location.trim() + '</span><br/><span style="font-size:0.65em;">' + item.DealerName.trim() + '</span></li>';
});
$("#results-list").append(li);
$("#results-list").listview("refresh");
});
//jqxhr.done(function() {
// console.log( "second success" );
//});
});
What am I doing wrong?

<script>
//first you define your functions, they will not be executed "from alone"
//syntax:|function name() { .. code }
function sortMethod(){
if(sessionStorage.sortBy === "model" || sessionStorage.sortBy == null || sessionStorage.sortBy.trim())
{
theManufacturers('model');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2a", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "year")
{
theManufacturers('year');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2b", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === "location")
{
theManufacturers('location');
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2c", page).prop("checked", true).checkboxradio("refresh");
});
}
else if(sessionStorage.sortBy === 'ttaf')
{
theManufacturers("ttaf");
$(document).on("pagecontainerbeforeshow", function () {
var page = $.mobile.pageContainer.pagecontainer("getActivePage");
$("#radio-choice-h-2d", page).prop("checked", true).checkboxradio("refresh");
});
}
};
//same here, just a defined function
function theManufacturers(inputSearch){
var qryString = 0;
var li = "";
var jqxhr = $.getJSON("url",
function(data){
$.each(data.items, function(i,item){
li+='<li><img src="' + item.Image.trim() + '" style="height:80px;/> <span style="font-size:0.75em;">' + item.Manufacturer.trim() + ' ' + item.Model.trim() + '(' + item.Price.trim() + ')</span><br/><span style="font-size:0.65em;">S/N: ' + item.Serial.trim() + ' | TTAF: ' + item.TTAF.trim() + ' | LOC: ' + item.Location.trim() + '</span><br/><span style="font-size:0.65em;">' + item.DealerName.trim() + '</span></li>';
});
$("#results-list").append(li);
$("#results-list").listview("refresh");
});
});
//here is an example how i outsourced your changehandler to a function
function initializeChangeHandler(){
$("[name=radio-choice-h-3]").change(function() {
//alert('Selected: '+$('input[name=radio-choice-h-3]:checked').val());
sessionStorage.sortBy = $('input[name=radio-choice-h-3]:checked').val();
});
};
//heres the function that will be executed when the document model is complete loaded
//syntax:|$(function(){ .. code .. })
$(function(){ // as the code inside here is executed, you can now call your functions
initializeChangeHandler();// <<-- example for understanding
sortMethod(); // <<-- heres the call
});
</script>
keep up to this structure ( initialize the stuff you defined before)
then you can be sure your functions are defined ;9

Move sortMethod in outer of scope $(), I mean sortMethod not need $()
function sortMethod(){
....
}

Related

run function after element generated jquery

I have function written in one js file with deferred and promise. After that I am calling that function in another HTML file where I create menu this page will work as web part. So I want to run the function after that menu generate, how can I do that.
Ph.DAL = function() {
this.getRequest = function(listName, select, filter, orderby, top, _async) {
var dfd = $.Deferred()
var request = baseRequest
request.type = 'GET'
request.async = _async
request.url =
siteAbsoluteUrl +
"/_api/web/lists/getbytitle('" +
listName +
"')/items?" +
(this.isNullOrEmpty(select) ? '' : '$select=' + select) +
'&' +
(this.isNullOrEmpty(filter) ? '' : '$filter=' + filter) +
'&' +
(this.isNullOrEmpty(orderby) ? '' : '$orderby=' + orderby) +
'&' +
(this.isNullOrEmpty(top) ? '' : '$top=' + top)
request.headers = { ACCEPT: 'application/json;odata=verbose' }
dfd = $.ajax(request)
return dfd.promise()
}
Which I am calling from another html page to generate dynamic menu
$(document).ready(function() {
var utility = new Ph.DAL()
var menuHTML = ''
utility
.getRequest(
'Navigation',
'Id,Title,Icon,URL,Target,ParentId,OrderBy',
"Active eq 'Yes'",
'',
'',
true
)
.done(function(data) {
if (data && data.d && data.d.results && data.d.results.length > 0) {
createMenu(data.d.results, null)
}
$('#respMenu').html(menuHTML)
$('#respMenu').aceResponsiveMenu({
resizeWidth: '768', // Set the same in Media query
animationSpeed: 'fast', //slow, medium, fast
accoridonExpAll: false, //Expands all the accordion menu on click
})
})
function createMenu(jSON, parentId) {
var _menu
_menu = Enumerable.from(jSON)
.where(function(value) {
return value.ParentId == parentId
})
.orderBy(function(value) {
return value.OrderBy
})
.toArray()
if (_menu.length > 0) {
_menu.map(function(item, i) {
menuHTML +=
'<li class="' +
(item.URL.toLowerCase() == utility.pageName.toLowerCase() ? 'active' : '') +
'"><a href="' +
item.URL +
'">'
menuHTML +=
'<i class="' +
item.Icon +
'"></i><span class="title">' +
item.Title +
'</span></a>'
var subMenu = Enumerable.from(jSON)
.where(function(value) {
return value.ParentId == item.Id
})
.orderBy(function(value) {
return value.OrderBy
})
.toArray()
if (subMenu.length > 0) {
createSubMenu(jSON, subMenu)
}
menuHTML += '</li>'
})
}
}
function createSubMenu(mainData, data) {
menuHTML += '<ul>'
data.map(function(item, i) {
menuHTML += '<li>' + item.Title + ''
var subMenu = Enumerable.from(mainData)
.where(function(value) {
return value.ParentId == item.Id
})
.orderBy(function(value) {
return value.OrderBy
})
.toArray()
if (subMenu.length > 0) {
createSubMenu(mainData, subMenu)
}
})
menuHTML += '</li></ul>'
}
})
Now I am trying to loop li and want to add active class on particular class but menu generated and function call is earlier so it not working. How can I do that.
Run this function after menu creation
$.menuActive = function (menuItem) {
$('#respMenu li').each(function() {
if ($(this).text() == menuItem) {
$(this).addClass('active')
return false
}
})
}
You should try to use the MutationObserver API
var mutationObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// Do something here
});
});
mutationObserver.observe(myRefElement, {attributes: true})
//You can use custom events
//Do this after $('#respMenu').html(menuHTML)
$( "#respMenu" ).trigger( "list_ready" );
//In another file
$( "#respMenu" ).on( "list_ready", function () {
//Do ur stuff here
});

delete from database with javascript

I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.

jquery load function after show

I am trying to run a function after a given DIV shows.
$(document).ready(function () {
$("#next").click(function () {
$("#nextwindow").show()
});
});
$(document).ready(function () {
$("#pagetitle-up").click(function () {
$.post('maindatabase.php', {
page: <? php echo $_GET[p]; ?> , sort: 1
},
function (data) {
var printthisline = "";
var data = $.parseJSON(data);
for (var i in data.results) {
printthisline += " <a href='main.php?p=" + data.results[i].id + "'> " + data.results[i].pagetitle + "</a>" + " | " + " <br> ";
}
document.getElementById("nexttable").innerHTML = printthisline;
});
});
});
When trying to bind them together so that the function only runs once the initial DIV shows, it stops working. Any suggestions why?
$(document).ready(function () {
$("#next").click(function () {
$("#nextwindow").show()
});
});
$(document).ready(function () {
$("#nextwindow").on('show', function () {
$.post('maindatabase.php', {
page: <? php echo $_GET[p]; ?> , sort: 1
},
function (data) {
var printthisline = "";
var data = $.parseJSON(data);
for (var i in data.results) {
printthisline += " <a href='main.php?p=" + data.results[i].id + "'> " + data.results[i].pagetitle + "</a>" + " | " + " <br> ";
}
document.getElementById("nexttable").innerHTML = printthisline;
});
});
});
Thank you
You could trigger manually your custom show event:
DEMO jsFiddle
$(document).ready(function () {
$("#next").click(function () {
$("#nextwindow").show().trigger('show');
});
});
Or use callback:
DEMO jsFiddle
$("#nextwindow").show(0,myCallback);
function myCallback(){
$.post(...);
}
That's said, why not call POST request on #nextwindow click???

Placing a div only after clicked object

Buildgames returns rows:
<a>....</a>
<a>....</a>
When I click on each a the Buildcar_s function returns all the data inside an alert.
Instead of this alert I want to put all the results in a div under each a, so it would look like:
<a>.....clicked ...</a>
<div>....
...
</div>
<a>....not clicked...</a>
<a>....not clicked...</a>
<a>....not clicked...</a>
How can we put a div only under the a which was clicked?
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += 'mmmmmm<br/>';
});
place += '</div>';
return place;
}
Try this, relevant changes have been commented:
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
var $a = this;
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
// this inserts the HTML generated from the function,
// under the A element which was clicked on.
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += '<div style="float: right;"> ' + this.CITY + ' ' + '</div><BR />' + +'<br/><br/>';
});
place += '</div>';
return place; // returns the string created, as opposed to alerting it.
}

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Categories

Resources