I am trying to join two ajax calls into one. One fires on a checkbox change in the form, and the other fires when the jQuery slider "slides". I would like to combine the two.
I was thinking of using a .bind(), but I need to use more than one jQuery selector, and more than one event.
The two jQuery selectors would be:
$("input[type=checkbox]")
$( "#pay_range" ).slider
The two different events would be, respectively
.click()
.slide()
Obviously, the different event listeners have to go with the correct jQuery selectors.
the js for the checkboxes:
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// remove the original results
$('#original_results').css("display", "none");
// which filter section does it belong to
var filter_section = $(this).attr('name');
// should it be filtered out or left in
var remove = $(this).prop('checked');
// if needs to be filtered
if (!remove)
{
// add it to our filter list for the specified section
filters[filter_section].push(this.value);
}
else
{
// take it off the list for the specified section
var index = filters[filter_section].indexOf(this.value);
if (index > -1)
{
filters[filter_section].splice(index, 1);
}
}
$.ajax({
type: 'POST',
url: '/results/search_filter',
//url: url,
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#filter_updating').html("Filtering your search...");
},
success: function(response) {
//inject the results
$('#search_results').html(response);
},
data: { filters: filters, criteria: criteria }
}); // end ajax setup
});
the js for the slider:
$(function() {
$( "#pay_range" ).slider({
range: true,
min: pay_min,
max: pay_max,
values: [ pay_min, pay_max ],
slide: function( event, ui ) {
$( "#filter_by_pay" ).html( "Pay Range: ¥" + ui.values[ 0 ] + " - ¥" + ui.values[ 1 ] ).css("color", "black");
$.ajax({
type:'POST',
url: '/results/search_filter',
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#filter_updating').html("Filtering your search...");
},
success: function(response) {
//inject the results
$('#search_results').html(response);
},
data: { min: ui.values[0], max: ui.values[1] }
});
}
});
});
You can simplify down to one function:
function doAjax() {
var ranges = $('#pay_range').slider('values')
var data = {
min: ranges[0],
max: ranges[1],
filters: filters,
criteria: criteria
}
/* show loading*/
$.post('ajaxData.html',data,function(response){
$('#search_results').html(response);
})
}
Then for slider:
$("#pay_range").slider({
range: true,
min: pay_min,
max: pay_max,
values: [pay_min, pay_max],
stop: function(event, ui) {
doAjax();
}
});
Do same thing in checkbox handler after you adjust filters
Your code doesn't show where citeria comes from
DEMO
Related
jquery autocomplete for a textbox should not allow data other than the autocomplete list.,but the problem is i need to allow only data from the list autocomplete list but not any other data, even if the user enter any another data we i need to show a message that please select from the autocomplete list.
The link show below is also allowing any data other than the autocomplete suggestions:
$("#field").autocomplete({
source: countries_starting_with_A,
minLength: 1,
select: function(event, ui) {
// feed hidden id field
$("#field_id").val(ui.item.id);
// update number of returned rows
$('#results_count').html('');
},
open: function(event, ui) {
// update number of returned rows
var len = $('.ui-autocomplete > li').length;
$('#results_count').html('(#' + len + ')');
},
close: function(event, ui) {
// update number of returned rows
$('#results_count').html('');
},
// mustMatch implementation
change: function (event, ui) {
if (ui.item === null) {
$(this).val('');
$('#field_id').val('');
}
}
});
http://jsfiddle.net/handtrix/32Bck/
There are lots of ways to do this. Here is one suggestion:
Working Example: http://jsfiddle.net/Twisty/32Bck/560/
HTML
<div class="ui-widget" style="position: relative;">
<input type="text" placeholder="type something ..." id="suggest" />
</div>
CSS
body {
padding: 30px;
}
input.ui-state-alert {
border: 1px inset #F00;
}
JavaScript
var makeSelect = false;
$(document).ready(function() {
function requiredValid(target) {
target = $(target);
// Return Focus
target.focus();
// Add alert class
target.addClass("ui-state-alert");
$("<div>", {
class: "required-alert-text",
style: "color: #F00; font-size: 10px; display: inline-block; position: absolute;"
}).html("Must select from list.").insertAfter(target).position({
my: "bottom",
at: "top+5",
of: target
});
}
$("#suggest").autocomplete({
delay: 100,
source: function(request, response) {
// Suggest URL
var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=" + request.term;
// JSONP Request
$.ajax({
method: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
url: suggestURL
})
.success(function(data) {
response(data[1]);
});
},
select: function(e, ui) {
makeSelect = true;
},
close: function(e, ui) {
if (makeSelect) {
makeSelect = false;
$(".ui-state-alert").removeClass("ui-state-alert");
$(".required-alert-text").remove();
} else {
requiredValid(this);
}
}
});
$(".ui-state-alert").on("blur", function() {
$(this).focus();
})
});
This will not cover all cases. Basically, we want to know if the user made a selection from the list. I created makeSelect and assigned it as false. We assume upfront that the user has not done this.
When the user selects a list option, select callback is triggered and updates out variable. This also triggers close callback as it is now closing the list. If the user has made a selection, we move one and reset for the next time. If not, we apply some techniques to alert the user and keep focus until they make a selection.
I am using jquery ui Dialog box to create multiple notes in my Web Application. So there is a add-note button which clicks to open a note (dialog box at center).
User can open multiple notes (dialogs) together and fill content save, delete, etc on each.
Problem arises when multiple notes are opened and I start deleting some randomly. So on deletion the positioning of the opened dialog gets affected. The opened dialogs after deletion of any start moving upwards on the screen.
I have been trying to solve this from quite some time. Plz help.
My JS:
function createNote(note, noteContent, newNote){
var noteDiv = $('<div> <textarea class="note-textarea" style="width:100%;background-color:#D3D3D3;"></textarea> </div>');
noteDiv.clone(true).attr("id", noteId)
.dialog({
modal : false,
draggable : false,
resizable : false,
open: function(){
$("#"+ noteId).find('textarea').val(noteContent);
$("#"+ noteId).find('textarea').css({
'height': $("#" + noteId).parent().height()
});
}, create: function(){
// Create Title Textfield inside note top bar
$("<input type = 'text' placeholder='Title' class='note-title'></input>").appendTo($("#"+ noteId).prev(".ui-dialog-titlebar").find('span'));
$("#"+ noteId).prev(".ui-dialog-titlebar").find('input').val(noteTitle);
if(!jQuery.isEmptyObject(note)){
createLastModifiedSpan($("#"+ noteId), lastModified);
}
},
buttons : [ {
text : "Save",
disabled: true,
click : function() {
......AJAX CALL to SAVE
}],
beforeClose: function(event, ui) {
if(confirm('Are you sure you want to delete this note?')){
$.ajax({
type: 'POST',
url: "/common/deleteNote.action",
data:
{
'note.id.operatorId':$('#operatorId').val(),
'note.id.noteId':noteId
},
success: function(data, textStatus, jqXHR){
if(data.result == 'success'){
alert('Deleted Successfully');
numberOfNotesCreated--;
}else
alert('Error in Deleting. Contact Admin');
},
error: function(data){
alert("Error in DB!");
}
});
}else
return false;
},
resize: function(event, ui) {alert('dskjfsf')},
position:[10,100]
});
$("#"+ noteId).dialog('open');
$("#" + noteId).parent().draggable()
.resizable();/*.position({
my: "center",
at: "center",
of: window
});*/
//Fire event on Either textarea or note title
$("#"+ noteId).find('.note-textarea')
.add($("#"+ noteId).prev('.ui-dialog-titlebar').find('.note-title')).keydown(function(event) {
if($(this).val() != '') {
toggleSaveButton($( "#" + noteId ), "enable");
}
});
if(newNote){
elementCount++;
numberOfNotesCreated++;
}
prevNoteId = noteId;
}
EDIT: If I add notes in sequence say 1, 2, 3, 4 and start deleting from the recently added like 4, 3, 2.. the positiong does not give a problem, however when I start deleting randomly 2, 1.. then the other notes postioning gets disturbed.
Found this on the jquery form which solved my problem :
https://forum.jquery.com/topic/bug-when-closing-one-dialog-within-multiple-stacked-dialogs
Put this in close function of the dialog:
var widget = $(this).dialog("widget"), height = widget.height();
widget
.nextAll(".ui-dialog").not(widget.get(0))
.each(function() { var t = $(this); t.css("top", (parseInt(t.css("top")) + height) + "px"); });
I am trying to design a pagination system in jQuery. The bit I am stuck on is when I click on different page number links, I want it to move the "active" class to the newly clicked page.
In the example page "1" has the active class. When I click "2" I want the active class to move to "2" and be removed from "1".
http://jsfiddle.net/qKyNL/24/
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
$('#content').fadeTo(500, 1);
}
});
});
I'm quite new to jQuery and could do with some help. Can anyone please give me some guidance on how to do this?
You could check addClass method here and removeClass method here
Remove the current active li and add the active class to the one you clicked.
Add those two lines in your click event handler
$('#pagination li.active').removeClass("active");
$(this).parent().addClass("active");
I have this code
<script type="text/javascript">
$(function () {
$(".a").live("click", function () {
var $this = $(this),
ProductImageId = $this.data('ProductImageId');
$.ajax({
url: '/Home/AddToCart',
type: "post",
cache: false,
data: { ProductImageId: ProductImageId },
success: function (data) {
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
Every time someone click on this button I want a image to load for like 1 sec
so the user knows that something happened..
any kind of help is appreciated
Something like:
var $loader = $('<img src="loader.gif">').appendTo(document.body);
And then
success: function (data) {
setTimeout(function() {
$loader.remove();
data = eval(data);
$this.addClass('productSelected');
},1000);
}
It will show the image for 1sec + the ajax loading time. Although, as a visitor of your site I would probably prefer to skip the 1sec delay...
Add before send like this :
beforeSend: function(){
$("some element").append("<img src='url' id='one_sec_img' />");
SetTimeout(1000, function(){
$("#one_sec_img").hide();
})
}
But, I think your requirement is something normal :
Here, bcoz of the before send, as soon as you click button that triggers ajax, the image will be loaded, and on success, the image can be hidden . This is the usual process, in this case,setTimeout is not needed . But, if your requirement is something like, the image should appear only one sec, you can use set timeout. Otherwise, below code is enough.
beforeSend: function(){
$("some element").append("<img src='url' id='one_sec_img' />");
},
success: function(res){
$("#one_sec_img").hide();
}
<script type="text/javascript">
$(function () {
$(".a").live("click", function () {
var html=$(this).html();
$(this).html('loading');//<img src="" />
var $this = $(this),
ProductImageId = $this.data('ProductImageId');
$.ajax({
url: '/Home/AddToCart',
type: "post",
cache: false,
data: { ProductImageId: ProductImageId },
success: function (data) {
$(".a").html(html);
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
try this.
Use jQuery BlockUI Plugin to show the image, may be it solve your problem.
Try:
$(".a").click( function( ) {
$("#idOfImage").show().delay( 1000 ).hide();
// ajax call
});
else if you only want the image to disappear only after the ajax call
$(".a").click( function( ) {
$("#idOfImage").show();
$.ajax({
// parameters
}).done( function( ) {
$("#idOfImage").hide( );
});
});
The code i current have is this.
function update (){
latest_id = $('#image:first').data('position'); /* == 12 */
$.ajax({
type: "POST",
url: "../web/update/" + latest_id + "",
success: function(data) {
$('#my_like').after(data);
$('.newly-added').animate({"margin-left": "+=66px"}, "fast");
},
error: function(response) {
alert("failed");
},
});
}
setInterval(function() {
update();
}, 4000);
But because the element has been newly added it doesn't receive the new animate part. I done some research and found .live but that needs something to start it, e.g a click.
Fixed, there was a issue with jquery I was including.