Here is a sample of my problem and below is the same code
HTML
<button id='preview_btn'>Add</button>
<table id="point_tbl">
</table>
JavaScript
var pointList = [];
function deletePoint(id) {
console.log(id); // should be string but turns out to be the tr element
for (var i = 0; i < pointList.length; i++) {
if (pointList[i].id == id) {
pointList.splice(i, 1);
document.getElementById(id).remove();
document.getElementById(id + "item").remove();
}
}
}
function getTemplate(obj) {
var id = obj.id + "item";
var aa = obj.id;
var row = "<tr id = '" + id + "'><td>" + obj.sn + "</td><td>" + obj.x + "</td><td>" + obj.y + "</td><td>" + obj.tx + "</td><td>" + obj.ty + "</td><td>" + obj.lbl + "</td><td><button class='del_point' onclick = 'deletePoint("+id+");'>Delete</button></td></tr>";
return row;
}
document.getElementById("preview_btn").onclick = function(event) {
var id = getUniqueId();
var obj = {sn: pointList.length, x: 10, y: 10, tx: "0.5", ty: "0.5", lbl: "", id: id};
$('#point_tbl').append(getTemplate(obj));
pointList.push(obj);
}
function getUniqueId() {
if (!getUniqueId.idList) {
getUniqueId.idList = [];
}
var id = "uniqueID" + Math.round(Math.random() * 1000 + 1);
if (getUniqueId.idList.indexOf(id) != -1) {
return getUniqueId();
} else {
getUniqueId.idList.push(id);
}
return id;
}
When the Add button is clicked a new row is added with a button.
On this newly added button the deletePoint function is bind using the getTemplate function. The deletePoint function accepts the id of the row (tr) created by getTemplate function.
I am logging the the passed parameter in the deletePoint function. I was expecting this to be the id(basically a string) of the row but it turns out to be the whole tr element.
Not able to rectify the problem, please help.
What happens is that the generated code in the event handler is
deletePoint(someId)
instead of being
deletePoint("someId")
As most browsers create a variable in global scope for all elements having an id (the name of the variable being the id), you pass the element, not the string (in some browsers you would pass undefined).
Immediate fix : Change
onclick = 'deletePoint("+id+");'
to
onclick = 'deletePoint(\""+id+"\");'
Better : don't inline JS code in HTML to avoid those problems. For example give an id and data-attribute to your cell and later bind as you do with other elements.
You can change your delete function to fix problem
function deletePoint(id) {
id.remove();
}
Related
$(document).ready(function(){
var $body = $('body');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = tweet></div>');
var $user = $('<div class = users></div>');
var $message = $('<div class = message></div>');
var $time = $('<div class = time></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
$user.text('#' + tweet.user + ': ').attr('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//see user history by clicking on name
//click event on name element
//hide all other users that do not have the same username attribute?
$('.tweets').on('click', '.users', () => {
var user = $(this).data('users');
console.log(user);
})
So I'm trying to pull data from a class when I click on it. This involves the last few lines of my code. The data stored in my .users should give me an output of {someName: 'stringOfName"} however when I click on it I get an empty object {}. What am I doing wrong? I'm adding data to my .users and I can clearly see it being displayed holding information so am I pulling the data from this object incorrectly?
$(this).data('users'); would get info from a data-attribute called "users" on the clicked element. But I don't see anywhere in you code where you attach any data-attributes to any of your elements. You've added a "username" attribute, but that's not the same as a data-attribute, and it also has a different name.
Secondly, you can't use an arrow function as your "click" callback function because this will have the wrong scope. (You can read more about this elsewhere online).
Here's a working demo:
$(document).ready(function() {
//some dummy data
var streams = {
"home": [{
"user": "a",
"message": "hello",
"created_at": "Friday"
}]
};
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweet"></div>');
var $user = $('<div class="users"></div>');
var $message = $('<div class="message"></div>');
var $time = $('<div class="time"></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
//create a data-attribute instead of an attribute
$user.text('#' + tweet.user + ': ').data('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//use a regular function insted of an arrow function
$('.tweets').on('click', '.users', function() {
var user = $(this).data('username'); //search for the correct data-attribute name
console.log(user);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tweets"></div>
When a new button is created it isn't being picked up by the rest of the code
var topics = ["dog", "cat", "pangolin", "snake", "bird", "emu", "cow", "hedgehog"]
$(document).ready(function () {
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
});
$("button").click(function() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function(response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
});
});
What I'm trying to do is when the user creates a new button, that button will then work like the premade buttons. The premade buttons are supposed to display a few gifs.
What is happening is that after I create the new button, clicking on that button won't even console log the id of that new button.
Your event listener $("#btnAddSubmit").click worked only with already created buttons. That is means your new buttons will be without this listener. If you want to add listeners to the new buttons, you must do something like:
// We are create event listener as a function for convenient use
var onButtonClick = function () {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
// Your code here...
}
}
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// We are remove all button's listeners and at once add new
$("button").off('click').on('click', onButtonClick);
});
// And this code will add your listener as it was originally
$("button").off('click').on('click', onButtonClick);
Be cearful if your buttons have another event listeners. If it exists, you connot use .off(). In that case is correct way will be add listener for a new specific button's id.
Based on your question and the js code provided, i guess this is because the newly added button doesn't get the event.
All events are attached to the dom on page load. The new buttons that are injected to the DOM doesn't get the events. jQuery already did the bindings to DOM elements before the new code was injected. To solve this you have to use '.on() method in jQuery
Something like this
$(document).on('click','your_button_class_here',function(){
dosomething();
});
You're using the ready callback, so all of this runs when the DOM is ready. However, you don't actually create the new button until this ready callback has already run! So when you try to add callbacks with $("button").click(function(){}), you are trying to add that callback to all the buttons on the DOM... but some of the buttons you want to add it to do not exist yet. They won't exists until that first button's click callback is executed! So the first button you make will have the callback attached, but the new ones will not.
Maybe try something like this? I expect something will be wrong with how the value of this works on your click callback, but I think it's a nudge in the right direction.
$(document).ready(function () {
$("#btnAddSubmit").click(function () {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// be wary of what the value of `this` refers to! it might refer to
// the `this` of the scope in which it was defined!
function gifCallback() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function (response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
};
// reference the new button by its ID and add your desired callback
$("#gif").click(gifCallback)
});
});
i have been tasked by my senior to print values of line items using higher order functions (.filter/.map/.reject/.reduce). I m confused how to write the higher order function instead of a for loop(for printing the line values in Invoice Printout). I need to print the line only when the qty is more than 3. I m an intern and i dont know how it will work, kindly help.
Link to The code snippet: https://drive.google.com/file/d/1uVQQb0dsg_bo53fT3vk9f0G8WwZomgQg/view?usp=sharing
I always used if condition for printing the row only when the quantity field has value more than 3. I even know how to .filter but i dont know how to call it and where to call it. Please help
I don't believe Array.from works in server side code. If it does then use that. What I have been using are the following functions. They don't conform to the higher order functions specified but they work with Netsuite syntax and go a long way towards simplifying sublist handling and encapsulating code:
//SS2.x
//I have this as a snippet that can be included in server side scripts
function iter(rec, listName, cb){
var lim = rec.getLineCount({sublistId:listName});
var i = 0;
var getV = function (fld){
return rec.getSublistValue({sublistId:listName, fieldId:fld, line:i});
};
for(; i< lim; i++){
cb(i, getV);
}
}
// to use it:
iter(ctx.newRecord, 'item', function(idx, getV){
if(parseInt(getV('quantity')) >3){
...
}
});
or for SS1 scripts I have the following which allows code to be shared between UserEvent and Scheduled scripts or Suitelets
function forRecordLines(rec, machName, op, doReverse) {
var i, pred, incr;
var getVal = rec ? function(fld) {
return rec.getLineItemValue(machName, fld, i);
} : function(fld) {
return nlapiGetLineItemValue(machName, fld, i);
};
var getText = rec ? function(fld) {
return rec.getLineItemText(machName, fld, i);
} : function(fld) {
return nlapiGetLineItemText(machName, fld, i);
};
var setVal = rec ? function(fld, val) {
rec.setLineItemValue(machName, fld, i, val);
} : function(fld, val) {
nlapiSetLineItemValue(machName, fld, i, val);
};
var machCount = rec ? rec.getLineItemCount(machName) : nlapiGetLineItemCount(machName);
if(!doReverse){
i = 1;
pred = function(){ return i<= machCount;};
incr = function(){ i++;};
}else{
i = machCount;
pred = function(){ return i>0;};
incr = function(){ i--;};
}
while(pred()){
var ret = op(i, getVal, getText, setVal);
incr();
if (typeof ret != 'undefined' && !ret) break;
}
}
// User Event Script:
forRecordLines(null, 'item', function(idx, getV, getT, setV){
if(parseInt(getV('quantity')) >3){
...
}
});
// in a Scheduled Script:
forRecordLines(nlapiLoadRecord('salesorder', id), 'item', function(idx, getV, getT, setV){
if(parseInt(getV('quantity')) >3){
...
}
});
Usually its a straight forward task, but since you are getting length and based on that you are iterating, you can use Array.from. Its signature is:
Array.from(ArrayLikeObject, mapFunction);
var tableData = Array.from({ length: countItem}, function(index) {
vendorBillRec.selectLineItem('item', index);
var item = vendorBillRec.getCurrentLineItemText('item', 'item');
var description = nlapiEscapeXML(vendorBillRec.getCurrentLineItemValue('item', 'description'));
var quantity = parseFloat(nullNumber(vendorBillRec.getCurrentLineItemValue('item', 'quantity')));
return { item, description, quantity}
});
var htmlData = tableData.filter(...).map(getRowMarkup).join('');
function getRowMarkup(data) {
const { itemName, descript, quantity } = data;
return '<tr>' +
'<td colspan="6">' +
'<p>' + itemName + ' ' + descript + '</p>'+
'</td>' +
'<td colspan="2" align="right">' + quantity + '</td>' +
'</tr>';
}
Or if you like to use more functional approach:
Create a function that reads and give you all data in Array format. You can use this data for any task.
Create a function that will accept an object of specified properties and returns a markup.
Pass the data to this markup after any filter condition.
Idea is to isolate both the task:
- Getting data that needs to be processed
- Presentation logic and style related code
var htmlString = Array.from({ length: countItem}, function(index) {
vendorBillRec.selectLineItem('item', index);
var item = vendorBillRec.getCurrentLineItemText('item', 'item');
var description = nlapiEscapeXML(vendorBillRec.getCurrentLineItemValue('item', 'description'));
var qty = parseFloat(nullNumber(vendorBillRec.getCurrentLineItemValue('item', 'quantity')));
return getRowMarkup(item, description, qty)
}).join('');
function getRowMarkup(itemName, descript, quantity) {
return '<tr>' +
'<td colspan="6">' +
'<p>' + itemName + ' ' + descript + '</p>'+
'</td>' +
'<td colspan="2" align="right">' + quantity + '</td>' +
'</tr>';
}
I am unsure why my getCereal variable id using the find("td:first").html() is not working. I have been able to create my table, however my click event will not work. I am stumped. Any input will be greatly appreciated.
<div id="cer"></div>
<script type="text/javascript">
// jQuery onClick event
// the click function MUST BE USED CANNOT BE ALTERED OR REMOVED
$(function () {
$("table tr").click(function (event) {
function getCereal(id) {
for (var cerId = 0; cerId < cereals.length; cerId++){
if(cereals[cerId].id == id){
alert(cereals[cerId].id +" " + cereals[cerId].name + " " +
cereals[cerId].like);
break;
}
}
}
var id = $(this).find("td:first").html();
getCereal(id)
// This creates an cereal constructor object
function cereal(id, name, like) {
this.id = id;
this.name = name;
this.like = like;
}
// This creates 5 new objects with cereal information.
const cereals = [
new cereal(1, 'Captain Crunch', 'Yes'),
new cereal(2, 'Frosted Wheats ', 'Yes'),
new cereal(3, 'Shredded Wheat', 'No'),
new cereal(4, 'Trix', 'No'),
new cereal(5, 'Count Chocula', 'No'),
];
var output = "<h1>Cereal Listing</h1><table><thead>"+"<tr>"+"<th>"+"Id"+"</th>"+"<th>"+"Cereal Name"+"</th>"+"<th>"+"Like?"+"</th>"+"</tr>"+"</thead>"
for (var x = 0; x < cereals.length; x++) {
output +='<tr>' + "<td>" + cereals[x].id + "</td>" +"<td>" + cereals[x].name + "</td>" + "<td>" + cereals[x].like +"</td>" + '</a>' + "</tr>";
}
output += "</table>";
document.getElementById('cer').innerHTML = output;
})
});
</script>
It's really unclear what the goal is here. Maybe this will help, consider the following code.
$(function() {
function cereal(id, name, like) {
this.id = id;
this.name = name;
this.like = like;
}
const cereals = [
new cereal(1, 'Captain Crunch', 'Yes'),
new cereal(2, 'Frosted Wheats ', 'Yes'),
new cereal(3, 'Shredded Wheat', 'No'),
new cereal(4, 'Trix', 'No'),
new cereal(5, 'Count Chocula', 'No'),
];
var output = "<h1>Cereal Listing</h1>";
output += "<table class='cereal-table'><thead>";
output += "<tr><th>Id</th><th>Cereal Name</th><th>Like?</th></tr>";
output += "</thead><tbody>";
$.each(cereals, function(k, c) {
var row = $("<tr>", {
"data-c-id": k
});
$("<td>").html(c.id).appendTo(row);
$("<td>").html(c.name).appendTo(row);
$("<td>").html(c.like).appendTo(row);
output += row.prop("outerHTML");
});
output += "</tbody></table>";
$("#cer").html(output);
$(".cereal-table").on("click", "tr", function(e) {
var cId = parseInt($(this).data("c-id"));
console.log("Row C-ID: " + cId);
var data = "";
data += "ID: " + cereals[cId].id;
data += ", Name: " + cereals[cId].name;
data += ", Like: " + cereals[cId].like
alert(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cer"></div>
Since jQuery is a JavaScript Framework, you can mix and match both, yet I try to remain in one or the other. This is all in jQuery.
The function creates an Object. You have 5 objects in an Array and we're going to iterate the Array using $.each(). This is a functioned designed for this. See:
jQuery.each()
Each Object has parameters we can call and insert into the Table Cell elements <td>. jQuery give us the ability to quickly create elements as jQuery Objects: $("<td>").
Since the goal appears to be to create an output string of HTML text, we can convert all the jQuery Objects we've create into HTML by asking for the outerHTML property.
The result of running the code is:
<h1>Cereal Listing</h1><table><thead><tr><th>Id</th><th>Cereal Name</th><th>Like?</th></tr></thead><tbody><tr><td>1</td><td>Captain Crunch</td><td>Yes</td></tr><tr><td>2</td><td>Frosted Wheats </td><td>Yes</td></tr><tr><td>3</td><td>Shredded Wheat</td><td>No</td></tr><tr><td>4</td><td>Trix</td><td>No</td></tr><tr><td>5</td><td>Count Chocula</td><td>No</td></tr></tbody></table>
Once the table is constructed and outputted, you can bind a click event to the Row with .on() or .click(). I advise the .on() since it more tolerate of dynamic content.
We bind the click event to each row and then collect the data from the row and create an alert.
Hope this helps.
can you please tell me how to get Id of row when pop up option click ?I generated the row dynamically when "add" button is press.on Row there is an icon ":" ,on click of icon it show pop up screen When I click "edit" or other option I want to show Id of row on which it it open .I am able to get event of edit .But not able to get id.
http://jsfiddle.net/4ajeB/5/
function createTestCase(testCaseName, iscreatedFromScript, jsonObject) {
var id;
if (typeof ($("#testCaseContainer li:last").attr('id')) == 'undefined') {
id = "tc_1";
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
var conunter = count;
} else {
id = $("#testCaseContainer li:last").attr('id');
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
var conunter = count;
id = id.substring(0, index) + "_" + parseInt(count + 1);
}
var html = '<div class="testcaselist_row">' + '<ul>' + '<li id="' + id + '" class="clickTestCaseRow">' + id + '<i class="icon1 test_h"></i></li>' + '</ul></div>';
$('#testCaseContainer').append(html).enhanceWithin();
}
$('.edit_h').click(function(){
alert("edit"+$(this).id)
})
I got the ID using global variable.Can it is possible to get ID without using variable ?
Just add the ID to the .edit_h as data, and access it in the click event.
...
$('.edit_h').data('originalId', id);
$('#testCaseContainer').append(html).enhanceWithin();
}
$('.edit_h').click(function(){
alert("edit ID:"+$(this).data('originalId'));
})
Updated fiddle: http://jsfiddle.net/4ajeB/6/