This is my jQuery code to add html generated by a post in a div. The slidedown() function doesn't seem to be working right. Here is my script:
$(".expand").click(function(){
var button = $(this);
var id = $(this).attr("eid");
var url = "/get-complete/" + id + '/';
$.ajax({
type: "GET",
url: url,
success: function( data ) {
var obj = $.parseJSON(data);
var lang = '';
$.each(obj, function() {
lang += this['html'] + "<br/>";
});
button.siblings('.comment-expand').slideDown('slow', function(){
button.siblings('.comment-expand').html(lang);
});
button.attr('class', 'collapse');
button.html('Collapse');
},
});
return false;
});
Here is the html:
<a class="expand" href="/#" eid="{{ event.id }}">Expand</a>
<div class="comment-expand"></div>
This is the sample data returned by the GET request:
[{"html": "\n <div class=\"comment-count-bar\">\n</div>\n "}]
This is the code to collapse the post, but this isn't working either:
$("body").delegate(".collapse", "click", function(){
var button = $(this);
button.siblings('.comment-expand').slideUp('slow');
button.attr('class', 'expand');
button.html('Expand');
return false;
});
Try this:
$.ajax({
type: "GET",
url: url,
// setting the dataType to json, jQuery itself parses the response
dataType: 'json',
success: function(data) {
// Hiding the element and setting it's innerHTML
// before calling slideDown()
button.siblings('.comment-expand').hide().html(function() {
// Mapping the response and concatenating `html` properties
// If the response has only one array use:
// return data[0].html + '<br>'; instead
return $.map(data, function(v) {
return v.html + '<br>';
}).join('');
}).slideDown();
button.addClass('collapse')
.removeClass('expand')
.html('Collapse');
},
});
Edit: Since you are adding the class dynamically you should delegate the event:
$(document).on('click', '.collapse', function() {
// var button = $(this);
// ...
});
Related
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
<input type="text" id="autocomplete">
<ul></ul>
<script>
var value;
var wikiapi;
$('#autocomplete').on('keypress',function(e){
if(e.which==13){
value=$(this).val();
wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
$.ajax({
url:wikiapi,
crossDomain:true,
dataType:"jsonp",
xhrFields: {
withCredentials: true
},
success: function(data){
var links=data.query.pages[171166].iwlinks;
var title=data.query.pages[171166].title;
$.each(links,function(i,val){
$('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
});
console.log(data.query.pages[171166].iwlinks[0].url);
}
});
}
});
</script>
Hi, I am trying to retrieve the value from input tag. But It seems the method I've tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please.
I've also tried "..$('#autocomplete').on('click',function(){
........} also but not working.
I did a quick check inside the success function as to what data was storing. After just a couple of examples I noticed the key (the six digits) were different for each example. Therefore, var links=data.query.pages[171166].iwlinks; and var title=data.query.pages[171166].title; will only work for test. In order to get the keys of data.query.pages you need a for loop. I've also added $('ul').empty() to empty out whatever was in the list. Here's the code needed to get it to work:
var value;
var wikiapi;
$('#autocomplete').on('keypress', function(e) {
if (e.which == 13) {
value = $(this).val();
wikiapi = "https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles=" + value + "&format=json";
$.ajax({
url: wikiapi,
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
success: function(data) {
$('ul').empty();
for (var key in data.query.pages) {
if (data.query.pages.hasOwnProperty(key)) {
var links = data.query.pages[key].iwlinks;
var title = data.query.pages[key].title;
}
}
$.each(links, function(i, val) {
$('ul').append('<li><a href=' + val.url + '>' + title + '</a></li>');
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete">
<ul>
</ul>
When I paste your code to jsfiddle with this success function success: function(data){ console.log(data) } the ajax call works fine.
So you have an Problem to handle your result from the API.
I have rewritten your code to make it more readable:
$(document).on('keypress', '#autocomplete', function (e) {
if (e.which === 13) {
var options = {
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
prop: "iwlinks",
iwprop: "url",
titles: $(this).val(),
format: "json"
},
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
};
$.ajax( options ).done(function (data) {
var html ='';
$.each(data.query.pages, function(pageKey, pageValue) {
$.each(pageValue.iwlinks, function(linkKey, linkValue) {
html += '<li>' + pageValue.title + '</li>';
});
});
$('ul').html(html);
}).fail(function (err) {
console.log(err);
alert('Ooops');
});
}
});
I have extracted the ajax options and added the GET parameter from the URL to them. I also iterate over result pages and the link object to generate the listitems.
Here can you read about the jQuery ajax method and the options: https://api.jquery.com/jQuery.ajax/
I have been using this jQuery before I use $.ajax(); and it was working good:
$(document).ready(function(){
var urlSerilize = 'some link';
var appList = $("#applications > li > a");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//var appList = $(".body-list > ul > li");
//var appCheck = $('input[type=checkbox][data-level="subchild"]');
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
installbtn.on('click', function () {
event.preventDefault();
jQuery.each( form, function( i, val ) {
console.log(val);
var request = $.ajax({
url: urlSerilize,
type: 'GET',
data: $('#'+val).serialize(),
success: function( response ) {
console.log( response );
$('#applications').html();
$('#apps_box').html();
}
});
request.done(function(msg){
console.log('Ajax done: ' + 'Yeah it works!!!');
});
request.fail(function(jqXHR, textStatus){
console.log('failed to install this application: ' + textStatus);
});
});
});
});
but after I used this ajax code the .click() jQuery event don't work anymore:
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
})
request.fail(function() {
console.log("error");
})
request.always(function() {
console.log("complete");
});
//end loading apps
var showmore = $('.showapps');
showmore.click(function(){
var parent = $(this).parent('.tv_apps');
var displayC = parent.children('.body-list').css('display');
console.log(displayC);
if (displayC=='none') {
parent.children('.body-list').show('400');
$(this).children().find('img').rotate({animateTo: 180});
}else{
parent.children('.body-list').hide('400');
$(this).children().find('img').rotate({animateTo: 0});
};
});
});
at first place I though it was because of the ajax loads and don't stop, then i was wrong.
I have tried the window.load=function(); DOM function to load the script after Ajax finish loading and also was wrong.
So please if there any idea to fix this problem,
Thanks.
This is the event I want it to be fixed:
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
showmore.click(function(){
should be
$('.showapps').on('click', function(){
OR
$(document).on('click','.showapps', function(){
For dynamically added contents, you need to bind events to it.
For more info: http://learn.jquery.com/events/event-delegation/
Thanks everyone, at last I have found the solution.
It was a question of the DOM, when I use the ready method of jquery it loads an empty ul (without content), so then what I figured out in the first time was correct, all I did is to remove the ready and use a simple function that includes all the .click() events, then call it in request.done();.
This is the solution:
function loadInstaller(){
var urlSerilize = 'some link';
var appList = $("#applications > li");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//...etc
};
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
loadInstaller();
})
//...etc
});
I hope this answer will help someone else :)
I am appending html by taking code from data-prototype attribute from one div.
The problem is this that I am appending with two select boxes on which I want to run later jquery, as I want to update second one after choosing option from first one, it is just not executing jQuery code. Everything is alright on select boxes which are inserted when page is loading, but for those from append it doesn't work.
My jQuery Code:
var $optionDefinitions = $('.option-definitions');
var collectionHolder = $('div#epos_productsbundle_variant_options');
var $addOptionsLink = $('Add an option');
var $newLinkLi = $('<li></li>').append($addOptionsLink);
$(function() {
collectionHolder.append($newLinkLi);
collectionHolder.data('index', collectionHolder.find(':input').length);
$addOptionsLink.on('click', function(e) {
e.preventDefault();
addOptionsForm(collectionHolder, $newLinkLi);
});
function addOptionsForm(collectionHolder, $newLinkLi) {
var prototype = collectionHolder.data('prototype');
var index = collectionHolder.data('index');
var newForm = prototype.replace(/__name__/g, index);
var $newFormLi = $('<li id="subform_'+index+'"></li>').append(newForm);
$newLinkLi.before($newFormLi);
collectionHolder.data('index', index + 1);
}
$optionDefinitions.change(function(event){
var $optionid = $(this).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
});
I found the problem. After append I should use on.
So instead of
$optionDefinitions.change(function(event){
var $optionid = $(this).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
I got know
$(body).on('change', $optionDefinitions, function(event){
var $optionid = $(event.target).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
You can try this hack. setTimeout(after, 1);
93 var self = this;
94 var after = function() {
95 self. _container = $("#container");
96 self._slidebox = $("#slidebox");
97 self._slidebox_icon = $("#slidebox_icon");
98 }
99
100 setTimeout(after,1);
For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});