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);
Related
I got an issue here. I found out that the global variable got changed every time it got into ajax.
$(document).on("keyup input", ".product-id", function () {
var id_prod = this.id.replace('prod_id_', '');
console.log('id_prod (outside ajax): ', id_prod);
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({
"display": "block"
});
if (inputVal.length) {
$.ajax({
type: 'POST',
data: { term: inputVal },
url: 'backend-search-inv.php',
success: function (data) {
resultDropdown.html(data);
$(document).on("click", "#result2 p", function () {
var inv_id = $(this).text();
//console.log('inv_id: ',inv_id);
$.ajax({
type: 'POST',
data: {
term: inv_id
},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ', id_prod);
},
error: function () {
console.log('Unable to access database.');
}
});
}); //end of result being clicked
}
});
}
else {
resultDropdown.empty();
}
});
I don't get it why the variable id_prod gets incremented everytime when it goes into ajax. Here is the screenshot of the console.log.
Referring to the screenshot, everytime I want to enter something to the id_prod = 2, the ajax always ended up updating the id_prod = 1, and then id_prod = 2 again automatically, and result in duplication of my data.
Can someone help me on this?
So basically I just declare the id_prod as a global variable and assigned 0 as it's default value. Then, for id_prod is basically assigned to new value once it's in the keyup input event.
Thanks to Mohamed Yousef for his answer in my own question's comment section!
//DECLARE id_prod as a global variable...
var id_prod = 0;
$(document).on("keyup input", ".product-id", function(){
id_prod = this.id.replace('prod_id_', '');
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({"display":"block"});
if(inputVal.length){
$.ajax({
type: 'POST',
data: {term:inputVal},
url: 'backend-search-inv.php',
success: function(data){
resultDropdown.html(data);
}
});
}
else{
resultDropdown.empty();
}
});
// WHEN RESULT BEING CLICKED...
$(document).on("click", "#result2 p", function(){
var inv_id = $(this).text();
$.ajax({
type: 'POST',
data: {term:inv_id},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ',id_prod);
$('#prod_id_'+id_prod).val(inv_info[0]);
$('#prod_qty_'+id_prod).val(1);
$('#prod_disct_'+id_prod).val(0);
$('#prod_type_'+id_prod).val(inv_info[1]);
$('#prod_colour_'+id_prod).val(inv_info[2]);
$('#prod_price_'+id_prod).val(inv_info[3]);
$('#result2').empty();
sumPrice();
},
error: function(){
console.log('Unable to access database.');
}
});});
I'm trying to get a value of several URL input and if value of URL isn't not valid, I just want to animate input element and stop everything.
Is there any way to do it?
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
});
You need to let outside of your each loop know the condition of the contents.
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var blnIsValid = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
// Input isn't valid so stop the code
blnIsValid = false;
return false; // Alternatively don't stop so that any other invalid inputs are marked
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
// Check to make sure input is valid before making ajax call
if (blnIsValid) {
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});
One method is you can use flag to check and execute the Ajax method
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var callAjax = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
callAjax = false;
return false;
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
if(callAjax)
{
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});
i have DIV element in body and i copy that element to enable adding more elements to database but when i execute script that looks like this :
$(document).ready(function(){
$(document.body).on('change','.jobType',function(){
var value = this.options[this.selectedIndex].value;
select = this;
$.ajax({
url: 'getpart',
dataType: "json",
type: 'post',
data: {
part_id : value,
},
success: function( data ) {
wrapper = select.closest('.wrapper');
console.log(v, select);
inputPrice = wrapper.querySelector('.jobPrice')
console.log(inputPrice, data.Part.price);
inputPrice.value = data.Part.price;
}
});
});
});
var wrapper is null because is added to DOM dynamically, is there a way to use document.querySelector() on newly added element ?
I have added jquery statements to you existing code. If you have jQuery you can use it.
Changes:
1) var select = $(this);
2) var value = select.val();
3) var wrapper = select.closest('.wrapper');
4) var inputPrice = wrapper.find('.jobPrice')
$(document).ready(function(){
$(document.body).on('change','.jobType',function(){
var select = $(this);
var value = select.val();
$.ajax({
url: 'getpart',
dataType: "json",
type: 'post',
data: {
part_id : value,
},
success: function( data ) {
var wrapper = select.closest('.wrapper');
console.log(select);
var inputPrice = wrapper.find('.jobPrice')
console.log(inputPrice, data.Part.price);
inputPrice.val(data.Part.price);
}
});
});
});
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 :)
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);
// ...
});