I have this js code :
$(".contenteditable").keyup(function(){
var data = $(this).text();
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
$.post
(
"/users/"+userId,
{
data,domId,userId,'_method':'patch'
},
function(data)
{
console.log(data);
}
)
});
Its working ok. However, now I want to make it as function and use it for any page I tried like this:
function keyUpUpdate()
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
The userId is not working inside this function.
How can I get the closest tr and then the first input type hidden value from the active element inside function.
this has no context inside your function you should send the current object to the keyUpUpdate() as parameter then get userId based on this object :
$(".contenteditable").keyup(function(){
keyUpUpdate($(this));
//Other code
})
function keyUpUpdate(_this)
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(_this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
Or if you've just this function to execute on keyup you could call it directly then the this object will be passed dynamically :
$(".contenteditable").keyup(keyUpUpdate);
function keyUpUpdate()
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
Hope this helps.
Related
So, I have a page where I can add foods to an order list and currently I am making the "remove from the list" function as well, but I am facing a problem.
When I call setAttribute() on the right removeButton, I also want to remove the item from my array so that it won't send the removed food's name to the database.
My problem is the following: In the call of setAttribute(), something is wrong with my array, because removeName doesn't get it as a parameter.
var lastid = 0;
var foods_added = [];
var locked = true;
function add_food() {
var food_name = document.getElementById('food_name').value;
$.ajax({
url: "ask-info.php",
type: "post",
data: { food_name : JSON.stringify(food_name) },
success: function(res) {
console.log(res);
if (res == "van") {
var entry = document.createElement('h4');
entry.appendChild(document.createTextNode(food_name));
entry.setAttribute('id','item'+lastid);
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("Töröl"));
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');
entry.appendChild(removeButton);
lastid+=1;
list.appendChild(entry);
foods_added.push(food_name);
document.getElementById('food_name').value = "";
document.getElementById('press').disabled = true;
} else {
document.getElementById('press').disabled = true;
}
}
})
}
function removeName(itemid, foods_added){
var item = document.getElementById(itemid);
for (var i = 0; i<foods_added.length; i++) {
if (foods_added[i].id == itemid) {
foods_added.splice(foods_added[i].id, 1);
}
}
list.removeChild(item);
}
It looks like your problem is probably in this line:
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');
I'd recommend trying this instead:
removeButton.addEventListener('click', () => {
removeName(`item${lastid}`, foods_added);
});
Or if you don't have the ability to use es6:
removeButton.addEventListener('click', function() {
removeName('item' + lastid, foods_added);
});
Going into more detail about why your code isn't working, I imagine it's because the string you're passing in as the second parameter to setAttribute is evaled in a context outside of your calling function. foods_added doesn't exist in that context so it is undefined.
I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm trying to read p_info array returned from the function getproductInfo containing a ajax call but I'm getting undefined value. I'm using a callback function to achieve this but still doesn't work. Where am I wrong?
$(document).ready(function() {
function successCallback(data)
{
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
console.log(product_info); // Correct: shows my product_info array
return product_info;
}
function getProductInfo(prodId, successCallback) {
$.ajax({
type: "POST",
url: "getProductInfo.php",
data: "id=" + prodId,
dataType: "json",
success: function(data) {
var p_info = successCallback(data);
console.log(p_info); // Correct: shows my product_info array
return p_info;
},
error: function()
{
alert("Error getProductInfo()...");
}
});
return p_info; // Wrong: shows "undefined" value
}
var p_info = getProductInfo(12, successCallback);
console.log(p_info); // Wrong: shows an empty value
});
The code should speak for itself. But basically, you cant return an upper-level function inside a function. You must set a variable to be used to return after the ajax is submitted.
//This makes the p_info global scope. So entire DOM (all functions) can use it.
var p_info = '';
//same as you did before
function successCallback(data) {
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
return product_info;
}
//This takes prodID and returns the data.
function getProductInfo(prodId) {
//sets up the link with the data allready in it.
var link = 'getProductInfo.php?id=' + prodId;
//creates a temp variable above the scope of the ajax
var temp = '';
//uses shorthand ajax call
$.post(link, function (data) {
//sets the temp variable to the data
temp = successCallback(data);
});
//returns the data outside the scope of the .post
return temp;
}
//calls on initiates.
var p_info = getProductInfo(12);
console.log(p_info);
I am getting an error in my .ajax() function when attempting to pass in the checkboxes
Here is the code:
if(typeof($post) !== 'undefined'){
var $fname = $($post).attr('name').toString();
var data = {$fname : []};
alert($post);
alert($fname);
$($post + ":checked").each(function() {
data[$fname].push($(this).val());
});
}else{
var data = null;
}
The error I am getting in firebug is: data[$fname].push($(this).val()); is undefined
$post is just a class name passed into the function.. in this case it's .del-checked
The alerts sucessfully alert me the class name, and the checkbox name... in this case it's del[]
How can I get this to work in order to pass it to the data option of $.ajax?
Because you can not use a variable as a key when creating a new object
var data = {$fname : []};
is the same thing as doing
var data = {"$fname" : []};
You need to create the object and add the key with brackets
var data = {};
data[$fname] = [];
You can't use variables as keys unless you use bracket notation
if (typeof($post) !== 'undefined'){
var $fname = $($post).attr('name');
var data = {};
data[$fname] = [];
$($post).filter(":checked").each(function() {
data[$fname].push( this.value );
});
}else{
var data = null;
}
What about:
var data = $($fname).serialize();
I have 2 basic form used to convert data (type 1 <-> type 2).
I want to do my .post request using only 1 form.
I'm having issue with the [data] parameter for jquery.post
Here's my code :
$('form').submit(function(){
var a = $(this).parent().find("input").attr('name');
var b = $(this).parent().find("input").val();
var url = $(this).attr('action')
$.post(url, { a:b },function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});
return false;
});
The problem lies within {a:b}.
b is interpreted as my var b, but a isn't, making my post parameters something like [a:1] instead of [param:1].
Is there a way to have a dynamic a?
Try this:
var data = {};
data[a] = b;
$.post(url, data, function(data) {
So like this:
$('form').on('submit', function (e) {
e.preventDefault();
var data = {};
var el = $(this);
var input = el.parent().find('input');
var a = input.attr('name');
var b = input.val();
var url = el.attr('action');
data[a] = b;
$.post(url, data, function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});
Yes, use something else for the data post:
$.post(url, a+"="+b,function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});