Ajax form submit twice when include jcarousel script - javascript

I'm using Ajax to submit my form, but when i click button Add to cart the form will submit twice but if i remove jcarousel , the form will submit like normal.
<form id="formrandom1473" name="formrandom1473" method="post" action="ajax_process.php?case=add_product_ajax&pid=1473">
<input type="hidden" value="1473" name="products_id">
<input type="hidden" value="1" name="qty">
<div class="add_to_cart_div">
<input type="image" border="0" id="add-to-cart-1473" title=" Add to Cart " alt="Add to Cart" src="includes/languages/english/images/buttons/button_in_cart.gif">
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#add-to-cart-1473").click(function () {
var formrandom1473 = $("#formrandom1473");
formrandom1473.submit(function () {
$.ajax({
type: formrandom1473.attr("method"),
url: formrandom1473.attr("action"),
data: formrandom1473.serialize(),
success: function (data) {
$("#output").html(data);
$(".message_div").addClass("message_success").slideDown().delay(6000).slideUp(); // Div success
$(".cart_counter").load("ajax_process.php?case=cart_counter"); // Load new quantity / by quantity
$(".shopping_cart_box").load("ajax_process.php?case=shopping_cart_box"); // Load new shopping cart box / by product
$(".cart_dropdown").load("ajax_process.php?case=cart_dropdown"); // Load new shopping cart box / by product
}
});
$("formrandom1473").unbind();
return false;
});
/* Effect */
var productX = $("#cart-image-1473").offset().left;
var productY = $("#cart-image-1473").offset().top;
var basketX = $("#boxcart-content").offset().left;
var basketY = $("#boxcart-content").offset().top;
var gotoX = basketX - productX;
var gotoY = basketY - productY;
var newImageWidth = $("#cart-image-1473").width() / 3;
var newImageHeight = $("#cart-image-1473").height() / 3;
$("#wrapper").html("");
$("#wrapper").css({"position":"absolute","top": productY,"left": productX});
$("#cart-image-1473").clone()
.prependTo("#wrapper")
.css({"position" : "absolute", "border" : "1px dashed black"})
.animate({opacity: 0.6})
.animate({opacity: 0.0, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200,
function() {
});
/* Effect */
}); //click
}); //ready
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.mycarousel').jcarousel();
});
</script>
i tried to use $("formrandom1473").unbind(); but the problem still same.

Did you mean to use $("#formrandom1473").unbind(); with the # instead?
Or, since you already stored the jQuery object earlier:
formrandom1473.unbind();
If unbind doesn't work for you, try this instead, but move it BEFORE the $.ajax:
formrandom1473.submit(function() { return false; });
Also, check your JS console for any errors.

After refer this comment .. the form finally can submit like normal after i'm using e.stopImmediatePropagation();
formrandom1473.submit(function (e) {
$.ajax({
type: formrandom1473.attr("method"),
url: formrandom1473.attr("action"),
data: formrandom1473.serialize(),
success: function (data) {
$("#output").html(data);
$(".message_div").addClass("message_success").slideDown().delay(6000).slideUp(); // Div success
$(".cart_counter").load("ajax_process.php?case=cart_counter"); // Load new quantity / by quantity
$(".shopping_cart_box").load("ajax_process.php?case=shopping_cart_box"); // Load new shopping cart box / by product
$(".cart_dropdown").load("ajax_process.php?case=cart_dropdown"); // Load new shopping cart box / by product
}
});
e.stopImmediatePropagation();
return false;

Related

Displaying a loading gif every time when a date picker date is changed

I have a laravel application which shows some stats to my users.
On my front end blade, I'm displaying few widgets where each widget contain's a specific stat.
Following widget is to show number of total orders.
<div class="row mt-3" id="shopify_row1">
<div class="col-md-2" id="shopify_widget1">
<div class="jumbotron bg-dark text-white">
<img class="img-fluid pull-left" src="https://cdn0.iconfinder.com/data/icons/social-media-2092/100/social-35-512.png" width="32" height="32">
<h6 class="text-secondary mt-2 px-4">Shopify</h6>
<hr class="border border-white">
<h5 class="text-white">Total Orders</h5>
<span class="tot_o" id="tot_o">{{ $tot_o }}</span>
</div>
</div>
</div>
Like this widget, I have 5 more widgets to display 5 different stats.
In every widget initially I'm displaying stats for the current date, eg: if the total number of orders for the day is 0, it shows 0...
Then, I have added a a date picker as I can get the data only for a particular day.
<td>
<input id="date" class="date form-control" type="date">
</td>
And following is my jQuery...
<script>
$(document).on('change', '#date', function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'GET',
url : '/shopify_data',
data : {selected_date : $('#date').val()},
success:function(data){
$('#tot_o').empty();
$('#tot_sum').empty();
$('#avg_ov').empty();
$('#cus').empty();
$('#item_sum').empty();
$('#orders').empty();
var total_orders = data.tot_o;
var total_sales = data.sum;
var currency = data.crr;
var avg_ov = data.avg_ov;
var cus = data.cus;
var item_sum = data.item_sum;
var orders = data.orders;
$('#tot_o').append(total_orders);
$('#tot_sum').append(total_sales);
$('#avg_ov').append(avg_ov);
$('#cus').append(cus);
$('#item_sum').append(item_sum);
$('#orders').append(orders);
//console.log(total_orders);
},
timeout:10000
});
});
</script>
This entire code works perfectly, but now I need to add a loading gif till the updated results get displayed on the date change.
What changes should I do to above jQuery in order to add the loading gif...
There are multiple ways how you can create the loading gif. One would be to create an element in your blade template that is hidden or shown by using a class.
HTML:
<div class="loader hidden"></div>
CSS:
.hidden {
display: none;
}
jQuery:
const loader = document.querySelector('.loader');
$(document).on('change', '#date', function (e) {
loader.classList.remove('hidden');
// your other code..
}
And inside your success function you add the hidden class which should hide the loading element again.
success: function(data){
loader.classList.add('hidden');
// your existing code..
},
However, I would instead add a complete block, which ensures that on failure as on success the loading element is hidden.
$.ajax({
// your existing code..
complete: () => {
loader.classList.add('hidden');
}
}
You can place loading gif in any place of DOM with style="display: none".
Next, in your script before ajax you can show gif and after success or fail result hide it again:
<script>
let gif = $('.loading-gif'); // Your loading gif
$(document).on('change', '#date', function (e) {
gif.show(); // Show loading gif
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'GET',
url : '/shopify_data',
data : {selected_date : $('#date').val()},
success:function(data){
gif.hide(); // Hide gif
$('#tot_o').empty();
$('#tot_sum').empty();
$('#avg_ov').empty();
$('#cus').empty();
$('#item_sum').empty();
$('#orders').empty();
var total_orders = data.tot_o;
var total_sales = data.sum;
var currency = data.crr;
var avg_ov = data.avg_ov;
var cus = data.cus;
var item_sum = data.item_sum;
var orders = data.orders;
$('#tot_o').append(total_orders);
$('#tot_sum').append(total_sales);
$('#avg_ov').append(avg_ov);
$('#cus').append(cus);
$('#item_sum').append(item_sum);
$('#orders').append(orders);
//console.log(total_orders);
},
timeout:10000
});
});
</script>

Is there a way to call a django function without refreshing the page

I'm trying to create a function that generates a random value in django so that it can be recorded, and then is passed into a javascript file where it spins a wheel to show the animation, and then after the animation is over puts 10 coins into the profiles account. The problem is when I use a view function, the return type is a page redirect, so the animation gets cut off. Is there a type of django function that can parse in values without a redirect, similar to a C++ void function?
Here's the code I have so far
views.py
#login_required
def Red(request):
profile = get_object_or_404(Profile, user=request.user)
profile.coins += 10
profile.save(update_fields=['coins'])
random = random.randrange(11)
return render(request, "bets/bets.html", {'random' : random})
Profile model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
coins = models.DecimalField(max_digits=9, decimal_places=2, default=0.00)
def __str__(self):
# #ts-ignore
return f'{self.user.username} Profile'
and the html with the javascript in it
<div class="Container">
<div class="inputContainer" blank="False">
{% csrf_token %}
<span class="coinContainer2"><i class="fas fa-coins"></i></span>
<input name="amount" class="amountInput" type="number" min="0.01" placeholder="Enter Amount">
<div class="sideContainer" id="buttonNav">
<span class="redButton"><button type="button" class="btn btn-danger" id="buttonRed" name = "redButton"> Red </button></span>
</div>
</div>
</div>
</div>
<script>
var itemSelected = 0;
var stoping = false;
jQuery(function ($) {
var $owl = $('.owl-carousel');
// Initialize Owl
$('.owl-carousel').owlCarousel({
center: true,
loop: true,
margin: 10,
nav: false,
mouseDrag: false,
touchDrag: false,
pullDrag: false,
dots: false,
responsive: {
0: {
items: 3
},
600: {
items: 3
},
1000: {
items: 7
}
}
});
// Click in button Jump
$('#buttonNav').click(function (e) {
e.preventDefault();
stoping = false;
// Random between 1 and 10
//var itemSelected = Math.floor((Math.random() * 11));
itemSelected = "{{ winner }}";
var $jump = $(this);
//$jump.html('Jumping ...');
$jump.attr('disabled', 'disabled');
// Trigger autoplay owl
$owl.trigger('play.owl.autoplay', [100]);
// Slow speed by step
setTimeout(slowSpeed, 2000, $owl, 200);
setTimeout(slowSpeed, 4000, $owl, 250);
setTimeout(slowSpeed, 5000, $owl, 300);
setTimeout(stopAutoplay, 6000);
return false;
});
// Event changed Owl
$owl.on('changed.owl.carousel', function (e) {
if (stoping) {
// Examine only if roulette stop
var index = e.item.index;
var element = $(e.target).find(".owl-item").eq(index).find('.element-roulette');
var item = element.data('item');
if (item == itemSelected) {
// If element equals to random, stop roulette
$owl.trigger('stop.owl.autoplay');
//$('#buttonNav').html('Jump');
$('#buttonNav').removeAttr('disabled');
}
}
});
// Showcase
slowSpeed($owl, 1400);
});
/**
* Reduce speed roulette
* #param {type} $owl
* #param {type} speed
* #returns {undefined}
*/
function slowSpeed($owl, speed) {
$owl.trigger('play.owl.autoplay', [speed]);
}
/**
* Stop autoplay roulette
* #returns {undefined}
*/
function stopAutoplay() {
stoping = true;
}
</script>
Thanks!
I believe it's only possible is though JavaScript or jquery.
https://api.jquery.com/jQuery.get/
URL to your function.
Idk know how different flask is from django but I use this tutorial to figure this out myself a week ago.
https://flask.palletsprojects.com/en/1.1.x/patterns/jquery/

Stop .blur() function from triggering on select statement but remain on span

I am trying to create an inline edit function to trigger differently on different elements.
I have tried to use other plugins but haven't been able to get them to do exactly what I want so have decided to try to create a plugin of my own, while learning jquery along the way.
The issue I am currently having is that I have a .blur event that is triggering on a span element correctly and this is what I want but when the element is a select element I don't want the blur event to trigger. As the code is below the blur event triggers and it is not the desired result. Can anybody advise how I can only trigger the blur() event on span elements and nothing else
$('.inlineEdit-jmc').inlineEditJmc({
fieldsArray: {
table-column1: 'field-table-column1',
table-column2: 'field-table-column2'
}
});
(function ( $ ) {
$.fn.inlineEditJmc = function(options) {
//Set Default Settings
console.log(options);
var settings = $.extend({
'pk': null,
'table': null,
'field': null,
'url': null,
'type': null,
'fieldsArray': null
},options)
if(settings.fieldsArray == null){}else{
var fields = new Array();
}
function load_settings(this_selected){
settings['pk'] = this_selected.attr("data-pk"); // pk of table to be updated
settings['table'] = this_selected.attr("data-table"); // table name of table to be updated
settings['field'] = this_selected.attr("data-field"); // name of the field in the table being updated
settings['url'] = this_selected.attr("data-url"); // url for the ajax call to be sent to.
settings['type'] = this_selected.attr("data-type"); // type of input being used. Input or Select
settings['value'] = this_selected.text(); //
settings['class'] = this_selected.attr("class"); // The Class
console.log(settings['table'] +' '+ settings['value']+ ' '+ settings['class']);
// if there are optionional inserts passed lets grab them
console.log('passed options:');
if(settings.fieldsArray == null){}else{
//var fields = [];
$.each(settings.fieldsArray,function(k,v){
//console.log('settings['+k+'] '+this_selected.attr(v));
$obj={};
$obj[k] = this_selected.attr(v);
fields.push($obj);
});
}
}
$(this).on('mouseover', function(event) {
$(this).addClass("ui-state-hover");
}).on('mouseout', function(event) {
$(this).removeClass("ui-state-hover");;
});
if($(this).is('select')){
$(this).on('change', function(){
alert('changed');
alert($(this).val());
//console.log($(this));
//load_settings($(this));
var nt = $(this).text();
var jsonstring = JSON.stringify(fields);
// AJAX
});
}
if($(this).is('span')){
$(this).on("blur", function () {
alert('span');
load_settings($(this));
var nt = settings['value']
console.log('comment: '+settings['value']);
// we are going to update the db here.
console.log('Insert');
console.log(fields);
var jsonstring = JSON.stringify(fields);
console.log(jsonstring);
$.ajax({
type: 'POST',
url: settings['url'],
data: {
fieldsArray: fields,
pk: settings['pk'],
table: settings['table'],
field: settings['field'],
value: settings['value']
},
cache: false,
success: function(data,status){
console.log(data);
}
});
});
}
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class=''>
<select class='inlineEdit-jmc' ><option value='0' data-pk='3' data-url='/path/to/js/ajax/ajax.php' data-table='mysqltablename' data-field='ignore'>NO</option>
<option value='1' data-pk='3' data-url='/path/to/js/ajax/ajax.php' data-table='mysqltablename' data-field='ignore' selected>YES</option>
</select></td>
<td class=''><span class='inlineEdit-jmc' id='input' data-pk='3' data-url='/path/to/js/ajax/ajax.php' data-table='mysqltablename' data-field='comment' contenteditable='true'>Text that can be edited</td>
Try this code section in place of yours that begins if($(this).is('span')){
$(this).on("blur", function ()
$("span").on("blur", function () {
// your function content here
});
$("span select").on("blur", function () {
e.stopPropagation();
});
The two alternative selectors act like a case statement in jQuery

Implementing a Modal Factory?

I'be been using modals as a means to communicate to users in my apps for some time now via several different front end frameworks. The logic is usually the same, defining the modal's html then rendering it via some click event.
As my applications grow, so do the number of modals I use for a user prompt or confirmation - these modals can have anything from text inputs to forms to dropdowns and so on.
My current method is to write out each separate modal in a single html file and simply call them by their IDs but I feel this is inefficient as there is plenty of duplicate boilerplate code, so I'm wondering the best way would be to create modals dynamically while keeping the code as light andclean as possible?
I've been thinking of something like a "modal factory" where you pass the content of the modal along with the height, width, styling, etc. would this be a good approach?
Thanks for any input!
Well what I do for Forms/HTML Content loaded from the server - is create a div with an ID - PartialViewDialog at the end of my page -(I load Partial Views inside a Dialog)
This one is Bootstrap 3.* based - (HTML structure based on Frontend framework
So the HTML is like this:
<body>
<!-- Other page content -->
<div class="modal fade" id="PartialViewDialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" data-modal="title"></h4>
</div>
<div class="modal-body" data-modal="content">
</div>
<div class="modal-footer" data-modal="footer">
</div>
</div>
</div>
</div>
</body>
Then in JS, I create a dialog Manager:
var MyApp = MyApp || {};
MyApp.UIHelper = MyApp.UIHelper || {};
MyApp.UIHelper.DialogManager = (function () {
"use strict";
var self = {};
self.divId = null;
self.dialog = null;
self.dialogBody = null;
self.dialogTitle = null;
self.dialogFooter = null;
self.actionUrl = "";
self.modalObject = null;
self.options = {};
function Initilize(divId, options) {
self.options = $.extend({ buttons: [] }, options);
self.divId = divId;
self.dialog = $(self.divId);
self.dialogBody = self.dialog.find('*[data-modal="content"]');
self.dialogTitle = self.dialog.find('*[data-modal="title"]');
self.dialogFooter = self.dialog.find('*[data-modal="footer"]');
self.BootgridObject = null;
};
function OpenPartialViewDialog(url, title, preprocessingFunction, postProcessingFunction) {
// Create the buttons
var options = self.GetPartialViewButtons(url, preprocessingFunction, postProcessingFunction);
// Initialise the PartialViewDialog with Buttons
Initilize('#PartialViewDialog', options);
// Set the URL for Ajax content load and Form Post
self.actionUrl = url;
// Set Dialog Title
self.dialogTitle.html(title);
// Open the PartialViewDialog
self.OpenModel();
};
// This Method creates the buttons for the Form dialog
// e.g Save, Cancel, Ok buttons
self.GetPartialViewButtons = function (url, preprocessingFunction, postProcessingFunction) {
// I only need Save and Cancel buttons always so I create them here
var buttons = {
buttons: {
// I create a save button which Posts back the Form in the Dialog
Save: {
Text: "Save",
css: "btn btn-success",
click: function () {
// Call a function before sending the Ajax request to submit form
if (preprocessingFunction) { preprocessingFunction(); }
$.ajax({
type: "POST",
url: url,
// This Dialog has a Form - which is Post back to server
data: self.dialogBody.find("form").serialize(),
success: function (response) {
// TODO: Check if response is success -
// Apply your own logic here
if (response.hasOwnProperty("IsSuccess")) {
if (response.IsSuccess) {
self.dialogBody.html("");
self.dialog.modal("hide");
// TODO: Show Success Message
// You can call another function if you want
if (postProcessingFunction) {
postProcessingFunction();
}
} else {
// If failure show Error Message
}
}
},
error: function (response) {
// If failure show Error Message
}
});
}
},
Cancel: {
Text: "Cancel",
css: "btn btn-danger",
click: function () {
self.dialogBody.html("");
self.dialogFooter.html("");
self.dialogTitle.html("");
self.dialog.modal("hide");
}
}
}
};
return buttons;
};
// dynamic creating the button objects
self.CreateButtonsHtml = function () {
var htmlButtons = [];
$.each(self.options.buttons, function (name, props) {
var tempBtn = $("<button/>", {
text: props.Text,
id: "btn_" + props.Text,
"class": props.css + "",
click: props.click
}).attr({ "style": "margin-right: 5px;" });
htmlButtons.push(tempBtn);
});
return htmlButtons;
};
// This method will load the content/form from server and assign the modal body - it will assign the buttons to the Modal Footer and Open the Dialog for user
self.OpenModel = function () {
$.ajax({
url: self.actionUrl,
type: "GET",
success: function (response) {
// Handle response from server -
// I send JSON object if there is Error in loading the content - otherwise the result is HTML
if (response.hasOwnProperty("HasErrors")) {
// Means some error has occured loading the content - you will have to apply your own logic
} else {
//Server return HTML - assign to the modal body HTML
self.dialogBody.html(response);
self.modalObject = self.dialog.modal();
// show modal
self.modalObject.show();
}
}
});
// Create the buttons in the Dialog footer
var buttons = self.CreateButtonsHtml();
self.dialogFooter.html('');
for (var i = 0; i < buttons.length; i++) {
self.dialogFooter.append(buttons[i]);
}
};
return {
OpenPartialViewDialog: OpenPartialViewDialog,
};
})();
Then whenever I need to open a dialog from the server I can call it like this:
MyApp.UIHelper.DialogManager
.OpenPartialViewDialog('/Content/Load', "My Title",
function(){alert('pre-process')},
function(){alert('post-process')}
);
Note: The PreProcess + PostProcess are called when the Save button is clicked
Here is a working/demo example which shows what the above JS does - Hope it helps
In the demo I load Dummy HTML from a div id="dummycontent"
Fiddle: https://jsfiddle.net/1L0eLazf/
Button Fiddle: https://jsfiddle.net/1L0eLazf/1/

div sort not working when div generated dynamically

I'm trying to sort a list of divs with the properties shown by particular attributes (gender, level, name etc) using the following script:
html:
<div id="sortThis" class="col-xs-12 alert-container">
<div id="1" class="container-element sortable box box-blue" data-gender="1" data-level="4" data-name="AAA"> <h3>AAA</h3><div class="panel-body">AAA is resp</div>
</div>
<div id="2" class="container-element sortable box box-pink" data-gender="2" data-level="3" data-name="DDD"><h3>DDD</h3><div class="panel-body">DDD is a s</div>
</div>
<div id="3" class="container-element sortable box box-blue" data-gender="1" data-level="2" data-name="FFF"><h3>FFF</h3><div class="panel-body">FFF has mad</div>
</div>
<div id="4" class="container-element sortable box box-pink" data-gender="2" data-level="4" data-name="CCC"><h3>CCC</h3><div class="panel-body">CCC has ma</div>
</div>
<div id="5" class="container-element sortable box box-pink" data-gender="2" data-level="2" data-name=EEE><h3>EEE</h3><div class="panel-body">EEE is a f</div>
</div>
<div id="6" class="container-element sortable box box-blue" data-gender="1" data-level="3" data-name="BBB"><h3>BBB</h3><div class="panel-body">BBB is an ou</div>
</div>
</div>
<button id="sLevel" class="LbtnSort">Sort by Level</button><br/>
<button id="sGender" class="GbtnSort">Sort by Gender</button><br/>
js:
var LdivList = $(".box");
LdivList.sort(function(a, b){
return $(a).data("level")-$(b).data("level")
});
var GdivList = $(".box");
GdivList.sort(function(a, b){
return $(a).data("gender")-$(b).data("gender")
});
/* sort on button click */
$("button.LbtnSort").click(function() {
$("#sortThis").html(LdivList);
});
/* sort on button click */
$("button.GbtnSort").click(function() {
$("#sortThis").html(GdivList);
});
when the .sortable divs are static, the sort works fine, as this jfiddle shows, however if the contents of the #sortable div (i.e. .sortable divs) are dynamically generated (in this case as the result of a form submit), when the sort button is pressed, the entire contents of the #sortable div disappears, and I can't seem to get it to work.
Any help or suggestions would be appreciated.
edit: The code for dynamic generation of the list is as follows - effectively it's an AXAX form submit that pulls data from a sorted list of items and outputs them.
$('#formStep2').submit(function(event) {
// get the form data
var studentArray = [];
$(".listbox li").each(function() {
studentArray.push({
'name': ($(this).text()),
'gender': ($(this).closest('ol').attr('id')).substr(0, 1),
'level': ($(this).closest('ol').attr('id')).substr(2, 3),
'topic': ($('input[name=topic]').val())
})
});
var studentString = JSON.stringify(studentArray);
console.log(studentString);
var formData = {
'students': studentString,
};
// process the form
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'process_step2.php', // the url where we want to POST
data: formData, // our data object
dataType: 'json', // what type of data do we expect back from the server
encode: true
})
// using the done promise callback
.done(function(data) {
if (!data.success) {
// error handling to go here.....
} else {
$('.alert-container').empty();
var obj = JSON.parse(data.message);
//sort the array alphabetically by name (default status)
var test = obj.sort(function(a,b){
var lccomp = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
return lccomp ? lccomp : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});
console.log(test);
var i=0;
test.forEach(function(st) {
console.log(st['name']);
var gen = (st['gender'] == 1) ? "blue" : (st['gender'] == 2) ? "pink" : NULL;
$('.alert-container').append('<div id="' + (i+1) + '" class="container-element sortable box box-' + gen + '" data-gender="' + st['gender'] + '" data-level="' + st['level'] + '" data-name="' + st['name'] + '"><h3>' + st['name'] + '</h3><div class="panel-body"><div class="col-xs-9"><i class="fa fa-quote-left fa-3x fa-pull-left fa-' + gen + '" aria-hidden=:true"></i>' + st['comment'] + '</div></div></div>');
i++;
});
// jump to the next tab
var $active = $('.wizard .nav-tabs li.active');
$active.next().removeClass('disabled');
nextTab($active);
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
You are defining LdivList and GdivList inline with your code so they are defined on DOM ready. You have to wrap the definition of those inside a function and call it on click:
$(document).ready(function(){
$("button.LbtnSort").click(function() {
$("#sortThis").html(GenerateLdivList);
});
/* sort on button click */
$("button.GbtnSort").click(function() {
$("#sortThis").html(GenerateGdivList());
});
});
function GenerateLdivList(){
var LdivList = $(".box");
LdivList.sort(function(a, b){
return $(a).data("level")-$(b).data("level")
});
}
function GenerateGdivList(){
var GdivList = $(".box");
GdivList.sort(function(a, b){
return $(a).data("gender")-$(b).data("gender")
});
}
As #theduke said, the lists are probably empty at the time you sort them. Here's a simple change that will read and sort the lists when you click the buttons instead. (Not tested.)
var LdivList = function () {
return $(".box").sort(function(a, b){
return $(a).data("level")-$(b).data("level")
});
};
var GdivList = function () {
return $(".box").sort(function(a, b){
return $(a).data("gender")-$(b).data("gender")
});
};
/* sort on button click */
$("button.LbtnSort").click(function() {
$("#sortThis").html(LdivList());
});
/* sort on button click */
$("button.GbtnSort").click(function() {
$("#sortThis").html(GdivList());
});

Categories