post data from table row like json format - javascript

this is related to my last question(
NOTE: I already got some good answers there). I'm doing a program that will filter. I didn't include this question because i thought that it is easier for me to add text as long as i know how to get the data from the row. But to my dismay, I wasn't able to code a good program til now.
Im currently using this javascript code (thanks to Awea):
$('#out').click(function(){
$('table tr').each(function(){
var td = '';
$(this).find('option:selected').each(function(){
td = td + ' ' + $(this).text();
});
td = td + ' ' + $(this).find('input').val();
alert(td);
});
})
my question is: How to add text before the data from the row? like for example, this code alert
the first row like data1.1 data1.2 data1.3,
then the second row like data2.1 data2.2 data2.3,
I want my output to be displayed like this
[
{"name":"data1.1","comparison":"data1.2", "value":"data1.3"},
{"name":"data2.1","comparison":"data2.2", "value":"data2.3"},
{"name":"data3.1","comparison":"data3.2", "value":"data3.3"}
{.....and so on......}]
but before that happen, i want to check if all the FIRST cell in a row is not empty. if its empty, skip that row then proceed to next row.
is there somebody can help me, please...

Building on my answer to your previous question, see http://jsfiddle.net/evbUa/1/
Once you have your data in a javascript object (dataArray in my example), you can write the JSON yourself, per my example, but you will find it much easier to use a library such as JSON-js (see this also).
// object to hold your data
function dataRow(value1,value2,value3) {
this.name = value1;
this.comparison = value2;
this.value = value3;
}
$('#out').click(function(){
// create array to hold your data
var dataArray = new Array();
// iterate through rows of table
for(var i = 1; i <= $("table tr").length; i++){
// check if first field is used
if($("table tr:nth-child(" + i + ") select[class='field']").val().length > 0) {
// create object and push to array
dataArray.push(
new dataRow(
$("table tr:nth-child(" + i + ") select[class='field']").val(),
$("table tr:nth-child(" + i + ") select[class='comp']").val(),
$("table tr:nth-child(" + i + ") input").val())
);
}
}
// consider using a JSON library to do this for you
for(var i = 0; i < dataArray.length; i++){
var output = "";
output = output + '{"name":"data' + (i + 1) + '.' + dataArray[i].name + '",';
output = output + '"comparison":"data' + (i + 1) + '.' + dataArray[i].comparison + '",';
output = output + '"value":"data' + (i + 1) + '.' + dataArray[i].value + '"}';
alert(output);
}
})

There are two things you need to do here. First get the data into an array of objects, and secondly get the string representation.
I have not tested this, but it should give you a basic idea of what to do.
Edit Please take a look at this JS-Fiddle example I've made. http://jsfiddle.net/4Nr9m/52/
$(document).ready(function() {
var objects = new Array();
$('table tr').each(function(key, value) {
if($(this).find('td:first').not(':empty')) {
//loop over the cells
obj = {};
$(this).find('td').each(function(key, value) {
var label = $(this).parents('table').find('th')[key].innerHTML;
obj[label] = value.innerHTML;
});
objects.push(obj);
}
});
//get JSON.
var json = objects.toSource();
$('#result').append(json);
});

var a = [];
a[0] = "data1.1 data1.2 data1.3"
a[1] = "data1.6 data1.2 data1.3"
var jsonobj = {};
var c = []
for (var i = 0;i
alert(c); //it will give ["{"name":"data1.1","comp...1.2","value":"data1.3"}", "{"name":"data1.6","comp...1.2","value":"data1.3"}"]
u have to include library for function from JSON.stringify from
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
hope this helps

Related

not able to delete a table row created by jquery, the code is creating extra unnecessary columns

I have a function to append table rows whenever a user selects values from checkbox popup window. If the user selects same or different check box values , the old values should be deleted. My code is not deleting/replacing the old row and somehow it deletes the name of the old row and creates extra table data values.
https://imgur.com/JjQjTaW
In this case, the second circled table row should have replaced the first circled row.
function AppendSampleTable(specimenNumberTextBoxId, specimenArray, _combinatedIdForSampleTbl) {
// var specimenNumberTextBoxId = "MOLECULAR DIAGNOSTICSSpec1";
var sampleTable = document.getElementById('ctl00_ContentPlaceHolder1_tblSample');
// var sampleTable = document.getElementById('ctl00_ContentPlaceHolder1_sampleNum6');
var specimenType = document.getElementById(specimenNumberTextBoxId).getAttribute("specimentype");
var poolSpecimenCode = document.getElementById(specimenNumberTextBoxId).getAttribute("poolspecimen");
var specimenNumber = "test";
var tableRows = $(sampleTable).find('tr');
var rowIndex = tableRows.length;
var i = 0;
var newRow;
var specimenArrayLength = specimenArray.length - 1; // Because specimenArray contains empty string for first element.
// Erase tr that has same name as requested.
var $oldRow = $(sampleTable).find('tr[name="' + _combinatedIdForSampleTbl + '"]'); //WHY IS THIS NOT WORKING OR IS IT? SHOUDL IT REMOVE OLD ROWS?// 3/28/2019
alert("old row=" + $oldRow);
$oldRow.remove();
// Append tr that contains desired values.
for (i; i < specimenArrayLength; i++) {
// If none of specimen has choosen for a pool, array will contain 'undefined', so we need to ignore that not to be appended into table.
if (specimenArray[i + 1] != undefined) {
specimenNumber = specimenArray[i + 1];
newRow = "<tr name='" + _combinatedIdForSampleTbl + "'><td class='col-xs-2'><span id='ctl00_ContentPlaceHolder1_sampleName" + (rowIndex + i + 1) + "' specimenCode='" + poolSpecimenCode + "'>POOL - " + specimenType + "</span></td><td class='col-xs-2'><span id='ctl00_ContentPlaceHolder1_sampleNum" + (rowIndex + i + 1) + "'>" + specimenNumber + "</span></td></tr>";
$(sampleTable).append(newRow);
}
}
}
I expect my code to replace the old row and not have extra empty table data values.

JavaScript and jQuery Alert find("td:first").html() and Click

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.

Issues attempting to display data from JSON file

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

Outputting array elements one at a time

Currently I am pushing form data (a single text field) to an empty array so that every time I click 'submit' the data is pushed to the end of the array (and thus, the array gets larger)
What I am experiencing:
I would like to output each element in a table, but I would like to do it one element per row, but right now it outputs like this per row
First row: Data entered and submit pressed once -> enteredData
Second row: More data entered and submit pressed -> enteredData
enteredData1
If I enter another element it does
enteredData
enteredData1
enteredData2
And so forth and so on....
Here's the code block that I have looping:
userInputName.push(userString);
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
}
I feel like I'm missing some kind of conditional logic inside the for loop, but at this moment (too little sleep) I can't piece it together rationally :|
Any suggestions on what I'm missing?
This is what my full javascript code block looks like--I may reference this to my other thread asking a related question:
//Declare global variable
var userInputName = [];
function displayTableAndTotals() {
// Your code goes in here.
//var totalStrings = [];
var userString;
var arrayIndex;
var output;
var outputTotal;
var form;
form = document.getElementById("userFormId");
output = document.getElementById("userEntriesId");
outputTotal = document.getElementById("testId");
userString = form.string.value;
userInputName.push(userString);
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
}
form.string.select();
return false;
}
you could just add the pushed element
var table = document.querySelector('#myTable');
document.querySelector('[type="submit"]').addEventListener('click', function(e) {
table.innerHTML += "<tr><td>" + userInputName.reverse()[0] + "</td></tr>";
}, false);
Good grief, of course I solve my own problem AFTER I spent forever agonizing and then consulting.
Basically I needed to do this:
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
tableData = "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
totalCount = userInputName.length;
}
output.innerHTML += tableData;
outputTotal.innerHTML = "<h4>Total Number of Strings: " + totalCount + "</h4>";
form.string.select();
return false;
So that the tableData variable would contain a new iteration without constantly resubmitting the entire thing every time. That way I could output tableData outside the loop properly.
I appreciate the feedback I have received.
Thank you!

Get specific string using javascript

I will briefly explain my issue:
I have a numbers looks like this: 971505896321;971505848963;971505478231;971509856987;
My client should write the above numbers in a text field and I should take the 971505896321 and 971505848963 and 971505478231 and 971509856987 and add them into a list.
I success now to add the numbers to the list but I have difficulties how to get the numbers without ;.
function AddPhoneNo()
{
var recipientNumber = document.smsmobile.mobile_no;
var opt = "<option value='" + recipientNumber.value + "'>" + recipientNumber.value + "</option>"
if (recipientNumber.value != "")
{
if(verifyPhone(recipientNumber.value))
{
$('#selectedOptions').append(opt);
recipientNumber.value = "";
}
}
}
All the numbers should start with 971 and the length of each number is 12. For example: 971506987456.
Appreciate your help.
Thanks,
var recipientNumber = "971505896321;971505848963;971505478231;971509856987;";
var mobileArr = recipientNumber.split(";");
and then u can run a loop on the above array and add those to your options
You just need to replace ; if I m getting you corretly than code for you is
var recipientNumber = document.smsmobile.mobile_no.replace(';','');
EDIT
if you are entering all number one than you need to split out your string
var recipientNumber = "971505896321;971505848963;971505478231;971509856987;";
var arrayofNumbers= recipientNumber.split(";");
var i; for (i = 0; i < arrayofNumbers.length; ++i)
{
var opt = "<option value='" + arrayofNumbers[i]+ "'>" + arrayofNumbers[i]+ "</option>"
if (arrayofNumbers[i] != "")
{
if(verifyPhone(arrayofNumbers[i]))
{
$('#selectedOptions').append(opt);
}
}
}

Categories

Resources