get jsonArray from table - javascript

I have a table and need to build json array. I need value from 1 and 4 column of table.
HTML
<table class="table table-striped" id="development_mapping">
<thead>
<tr>
<th>Visual Feature</th>
<th>Step</th>
<th>Output</th>
<th>Data Feature</th>
</tr>
</thead>
<tbody>
<tr><td>color</td>
<td><select id="sss"><option data-id="528092be144b4fbf65893404" selected="selected">first-step</option><option data-id="52809373144b4fbf6589340c">kmeans</option></select></td>
<td><select id="ooo"><option data-id="output" selected="selected">output</option></select></td>
<td><input id="value1" class="feature-execution"value="id"></td></tr></tbody>
</table>
Here is my solution, a function to made an json array from table
JAVASCRIPT
var jsonArray = {};
$('#development_mapping').find('tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
I have done, but not understand, why I get " " from value of 4 column. I mean, why variable in variable is always getting " "
This is my DEMO

Your selector: $('#development_mapping').find('tr') is selecting all <tr> tags in the table. Even the one in the <thead>! The <thead> doesn't have <td> tags, so that's where the " " is coming from.
Try this:
$('#development_mapping').find('tbody tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});

You are using .text() but there is no actual text in your 3rd td tag.
try this maybe?
variable : $(this).find('td:eq(3) input').val()

There are 2 problems with your code.
Remove the surrounding <tr> in your table head definition.
Use this to access input value
variable: $(this).find('td:eq(3) > input').first().val()
$.find() will return a collection and you'll need to get the first object of the collection for further use. Plus, you'll need to search for input inside the cell, not the cell itself.
Here is the working fiddle: http://jsfiddle.net/toshkaexe/7q3KP/

Related

How to automatically call a JavaScript that modify a value before show this value?

I am very new in JavaScript and I have the following problem to solve.
I have a table that contains this td cell:
<td class= "dateToConvert" width = "8.33%">
<%=salDettaglio.getDataCreazione() != null ? salDettaglio.getDataCreazione() : "" %>
</td>
This retrieve a String from an object and show it into the cell
The problem is the retrieved string represent a date having the following horrible form: 20131204 and I have to convert it into the following form: 2013-12-04.
So I am thinking to create a JavaScript that do this work when the value is retrieved.
My problem is: how can I do to automatically call the JavaScript before to show the value into the td cell? (So I show the modified output in the desidered form)
EDIT 1:
So I have create thid JavaScript function into my page:
function convertData() {
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.innerText = td.innerText.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
}
But it don't work because it never enter in this function (I see it using FireBug JavaScript debugger). Why? What am I missing? Maybe have I to call it explicitly in some way in my td cell?
Of course it is better to fix backend method to make it return proper format. But since you have no control over it try to use something like this:
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
Check the demo below.
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
<table>
<tr>
<td class= "dateToConvert" width = "8.33%">
20131204
</td>
<td class= "dateToConvert" width = "8.33%">
20140408
</td>
</tr>
</table>

Why I can't get the input value

I have this table in my HTML:
<table class="dataTable" id="repaymentShedule">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
</tr>
</thead>
<tbody data-bind="foreach: creditDetails">
<tr>
<td class="paymentDate" data-bind="text: dateOfPayment"></td>
<td class="startBalance" data-bind="text: beginingBalance"></td>
<td class="monthlyInt" data-bind="text: monthlyInterest"></td>
<td class="principal"><input data-bind="value: princpalPayment"></input></td>
<td class="monthlyInst" data-bind="text: monthlyInstallment"></td>
<td class="remainingBalance" data-bind="text: endingBalance"></td>
<td class="paid"><input type="checkbox" data-bind="checked: isPaid, disable: isPaid, click: testFunc, value: true"></td> <!-- value: true moje da ne e nujno -->
<td class="currentDate" data-bind="text: currentDate"></td>
</tr>
</tbody>
</table>
The values are comming from knockout js bindings.
and I'm trying to get all the values of the principal class with the function below:
updateValues = function(){
$("tbody").find("tr").each(function() {
var principal = $(this).find('td.principal').val();
console.log(principal);
});
};
Bu the console returns: (an empty string)
EDIT:
The above function works without any problems on the paymentDate class only by changing the .val() to .text()
I'm pretty sure that I'm not getting the value the right way, or that the binding is not allowing me to get the current value, but I'm really not able to spot the issue
You need to do this:
var principal = $(this).find('td.principal :input').val();
to get the value of the input element inside the table cell with class principal.
Also, as per the .val() API Documentation :-
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the .val() method returns an array
containing each selected option; if no option is selected, it returns
null.
Hence, you are getting empty string in console while using your code.
The above function works without any problems on the paymentDate class
only by changing the .val() to .text()
This also explains why you got the correct value after changing the .val() to .text() for the paymentDate table cell, as it does not have any input element inside it.
<td class="principal"><input data-bind="value: princpalPayment"></input></td>
You don't need a closing </input> tag, as input elements are self-closing.
And you just need to target better.
var principal = $(this).find('td.principal input').val();
If you're using KnockoutJS you probably don't need to use jQuery at all. Get the correct value from your ViewModel, something like this:
updateValues = function() {
var details = MyMainViewModel.creditDetails();
for (var i = 0; i < details.length; i++) {
var principal = details[i].princpalPayment();
console.log(principal);
}
};
No dependency on your view, and thus unit testable. In addition, if you put this function in the correct bit of scope (e.g. the observable bound to the data table) you'll have access to all the relevant other observables when you want to use the result.
your not looking for the input value your looking at the td value which clearly doesnt exist
here is a jsfiddle with the fixed jquery
http://jsfiddle.net/krxva/
updateValues = function(){
$("tbody").find("tr").each(function() {
var principal = $(this).find('td.principal').find('input').val();
console.log(principal);
});
};
var principal = $(this).find('td.principal').val();
console.log(principal);
Above willn't work because td has an input element also.
Since you want value of input element inside that td, so use like this :
var principal = $(this).find('td.principal input').val();
// Or use this
var principal = $(this).find('td.principal > input').val();
console.log(principal);
Refer this for understanding

Is it possible to get the value of a <td> element using onclick?

I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I'm trying to grab the table value and pass it to my JS file where a future AJAX command will pass it to a different file (that I won't have any issues with). My first attempt to alert out the value stated that the value was undefined. My second attempt showed the type of element it was inside (at the time it was a span). Now it's not showing anything. Suggestions?
PHP code:
<table class="departments">
<tr>
<th scope="col" style="width: 175px;">Email Name</th>
';
$get_depts = mysql_query("SELECT dept_name FROM depts where bus_id = '{$_SESSION['bus_id']}'");
while(($department = mysql_fetch_assoc($get_depts)))
{
echo '
<th scope="col" style="width: 175px;">'.$department['dept_name'].'</th>
';
}
echo '
</tr>
';
$get_emails = mysql_query("SELECT id, email_name from emails where bus_id = '{$_SESSION['bus_id']}' ORDER BY email_name ASC");
while(($email = mysql_fetch_assoc($get_emails)))
{
echo '
<tr>
<td id="test" onclick="moveValue()">'.$email['email_name'].'</td>
';
Current JS code:
function moveValue()
{
var x = document.getElementById(test);
var y = x.innerHTML;
alert(y);
}
Javascript:
var y = document.getElementById("test").innerText;
jQuery:
$("#test").text();
To get the HTML:
var html = document.getElementById("test" ).innerHTML;
jQuery:
$("#test").html();
You id attribute would be the same for every td inside the loop. So JS would not know which element you want.
You could try passing this into the onclick method
HTML
<td onclick="moveValue(this);">
JS
function moveValue( elem )
{
alert(elem.innerHtml);
}
I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.
I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.
You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-
var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
cells[i].addEventListener('click', clickHandler);
}
function clickHandler()
{
alert(this.textContent);
}
Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.
You can see it working in this fiddle
Lots of information here https://developer.mozilla.org/en-US/docs/Web/API
With javascript:
To get raw text without any elements or:
somevar=document.getElementById ( "test" ).innerText;
To get full html code of tag. Contents will be stored in 'somevar' variable.
somevar=document.getElementById ( "test" ).innerHTML;
You can do it either by
function moveValue()
{
var x = document.getElementById('test');
var y = x.innerHTML;
alert(y);
}
or by:
function moveValue(element) {
var y = element.innerHTML;
alert(y);
}
//with the following html code:
<td onclick="moveValue(this)">'.$email['email_name'].'</td>
its work.
function clickValue(elem) {
var x = document.getElementById(elem).innerHTML;
alert(x);
}
<table>
<th>Coba</th>
<tr>
<td id="1" onclick="clickValue('1')">value</td>
</tr>
<tr>
<td id="2" onclick="clickValue('2')">value yg ke 2</td>
</tr>
</table>
Change id="*anyvalue*" and clickValue('*anyvalue*')

JQuery: Find (the index of) a row with a specific data attribute value

I am trying to append a string, myoutput, right after a specific row in a table similar to this one:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>
So let's say I want to append my output string after the tr with data-my_other_id='2'
(note that in my code, my_other_id = 2 already )
I am trying to accomplish it doing this:
var want = $("tr").find("[data-my_other_id='" + my_other_id + "']").index();
after finding the index, I want to append my output strhing to this row...
$(want).insertAfter(...?);
Also... I noticed whenever I do
alert( want = $("tr").find("[data-my_other_id='" + my_other_id + "']").length)
I get 0 ...
Help please and let me know if my question is not clear enough so I can explain better.
I'm assuming you want to update the content rather than append, but it doesn't really change anything. I don't think you want to use find() that way. Try something like:
var $row = $('tr[data-my_other_id="' + id + '"]');
// should be the index of the tr in the <table>
// this may not be a good idea though - what if you add a header row later?
var index = row.index() + 1; // if you want 1-based indices
$row.find("td").text("I am row #" + index);
This is because find will no search siblings, only children. Try attaching your search to table.
html:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>​
js:
var my_other_id = 2;
alert( $("table").find("[data-my_other_id='" + my_other_id + "']").length);​
demo: http://jsfiddle.net/gDb3A/
You don't need to use the find method since the data attribute is on the tr itself. Also your use of index is not going to work. Try the following instead.
$("tr[data-my_other_id='" + my_other_id + "']").insertAfter(...?);
find looks for descendents. A TR can not be a descendent of itself.
Try using filter()
$("tr").filter("[data-my_other_id='" + my_other_id + "']").index();
Find in the specific table so it will be faster, you can use this method.
Js:
$('any-button').click(function(){
var id = 23;
var $row = $('.your-class tbody tr[data-id="' + id + '"]');
$row.remove();
});
Html
<table class="table table-striped your-class">
<thead>
<tr>...<tr/>
</thead>
<tbody>
<tr data-id="23">Some text</tr>
<tr data-id="43">Some text</tr>
<tr data-id="43">Some text</tr>
</tbody>
</table>

Setting TD value from previous TD

I have a table that is filled in with values dependant on a previous page
those avlues are filled in with struts apparently
but I'm not very good with all that stuff so is there a simple was I can do something like this, either with HTML only or maybe a small javascript I can put in tha page?
<Table>
<TR>
<TH>ID</TH>
<TD><s:property value="groupID" /><TD> <--Number generated by the page with struts
</TR>
<TR>
<TH>ID Value</TH>
<TD>foobar</TD> <-- the text I want to add in dependant on the number from the previous TD
</TH>
</Table>
so, is there a simple way to go about doing this? HTML, CSS, JavaScript solution maybe?
Given that exact HTML, a simple script like this will do it. But if you don't know JavaScript, you should really learn it so that you understand what you're doing.
<body>
<Table>
<TR>
<TH>ID</TH>
<TD><s:property value="groupID" /><TD>
</TR>
<TR>
<TH>ID Value</TH>
<TD>foobar</TD>
</TR>
</Table>
<!-- The script is here so it won't run until the TABLE has loaded -->
<script type="text/javascript">
// This is a map of the struts values to your values
var valueMap = {
"1": "foo",
"2": "bar",
"3": "baz"
};
// Browser compatibility. Older IE uses 'innerText' instead of 'textContent'
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
// Get all the TD elements on the page
var tds = document.getElementsByTagName('td');
// Get the text content of the first TD (index 0)
var text = tds[0][textContent];
// Get the value from the map using the text we fetched above
var value = valueMap[text];
// Set the text content of the second TD (index 1) to the mapped value
tds[1][textContent] = value;
</script>
</body>
Assuming you want to place the value 'groupID' (set in the first tr's td) into the second row's td element, then the following jQuery will do the trick:
$(document).ready(function() {
// Scrape the XML out of the TD containing the xml
var tdXml = $('table tr').eq(0).find('td').html();
// Grab the value of the value attribute (groupID)
var value = $(tdXml).attr('value');
// Set this value in the second row's TD
$('table tr').eq(1).find('td').text(value);
}​);​
jsFiddle here

Categories

Resources