I have an ajax for retrieving names from the database, when the names are more than one, i split them then clone the first class so that i can have the other name(second) in the cloned class. It seems not to work, What am i missing?
$.ajax({
type: "POST",
url: base_url + "c_transfer/viewTransfer/" + transfer_id,
dataType: "json",
success: function (data) {
var all_transferors = data[0]['Transferor_Name'];
var sole_transferors = all_transferors.split(',');
for (transferor_counter = 0; transferor_counter < sole_transferors.length; transferor_counter++) {
if (transferor_counter > 0) {
$('.clone').relCopy({});
$("#transferor_name").val(sole_transferors[transferor_counter]);
} else {
$("#transferor_name").val(sole_transferors[transferor_counter]);
console.log(sole_transferors[transferor_counter]);
}
// console.log(sole_transferors[transferor_counter]);
}
Are you trying to do this?
$("#transferor_name").val(sole_transferors[transferor_counter].val());
You need to use .val() at the end?
Related
I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/
So i have a couple of item that iterate through from database using Jquery and for each of them I output a button to select that specific item and when I click on that row's button I want to POST the details to the controller in MVC.
$.each(data, function (i, val) {
var item = $('<div></div>');
item.append('<h2><a>' +val.Name+ '</a></h2>');
item.append('<a id="button">SELECT</a>');
tab.append(item);
});
And I have this function for the button:
$('#myId').on('click', 'a#button', function () {
alert('Name'+val.Name+'');
var item = { Name: val.Name };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{item:" + JSON.stringify(item) + "}",
url: "/Person/GetData"
});
});
If I add the function inside the loop it will iterate as many times as there are items in there. So how can I deal with this in order to send post the name after I press SELECT button?
Use DOM traversal method to get the desired element to extract text to be passed to $.ajax()
As Identifiers in HTML must be unique use CSS class selector to target them
$.each(data, function (i, val) {
var item = $('<div></div>');
item.append('<h2><a>' + val.Name + '</a></h2>');
item.append('<a class="button">SELECT</a>');
tab.append(item);
});
In the event handler, use .prev() to target the sibling <H2> element
$('#myId').on('click', 'a.button', function () {
var item = {
Name: $(this).prev('h2').find('a').text()
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
item: item
},
url: '#Url.Action("GetData", "Person")' //Note: this will not work in separate JS file
});
});
Move the click to the bottom of the page outside any loop,
change the id to a class item.append('<a class="button">SELECT</a>'); for your click event to select the proper value
$('#myId').on('click', 'a.button', function () {
var val = $(this).prev('h2 a').text();//get the val.Name value
var item = { Name: val};//create a object
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: item,//jquery will take care of the encoding
url: "/Person/GetData"
});
});
I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});
I'm practicing JQuery and I wanted to create some images from JSON data.
I'm using element.attr(attr,value) and it's working nicely with the src attribute but no matter what I can't add any other attributes to my img tag and I don't know why. You can see that I'm trying to add one id but it doesn't work.
Here is my JS code :
$.ajax({
url: "http://ddragon.leagueoflegends.com/cdn/7.5.1/data/en_US/champion.json",
type: 'GET',
dataType: 'json',
data: {},
success: function(response){
var i = 1;
$.each(response.data, function (champion, infos) {
$.each(infos, function (infoKey, infoValue) {
var image = $("<img class='champion-icon'>");
if(infoKey == "id"){
image.attr('id', infoValue);
}
if(infoKey == "image"){
image.attr('src', "http://ddragon.leagueoflegends.com/cdn/7.5.1/img/champion/" + infoValue['full']);
image.appendTo("#champions");
if(i == 14){
$("<br>").appendTo("#champions");
i = 0;
}
i++;
}
});
})
}
});
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.