How to get <td> value in textbox - javascript

I've done some code in html and in JavaScript ... My query is when I click on <td>, whatever the value associated with it, has to be displayed in the corresponding text box ...
In front of <td> I've taken the textbox ... for an example I've taken 3 <td> and 3 textboxes
<script type="text/javascript">
function click3(x) {
x = document.getElementById("name").innerHTML
var a = document.getElementById("txt");
a.value = x;
}
function click1(y) {
y = document.getElementById("addr").innerHTML
var b = document.getElementById("txt1");
b.value = y;
}
function click2(z) {
z = document.getElementById("email").innerHTML
var c = document.getElementById("txt2");
c.value = z;
}
</script>
this is my JavaScript code , I know this is not an adequate way to deal such problem, since its giving static way to deal with this problem
does anyone have a better solution for this problem ??
In JavaScript/jQuery

If click1, click2 and click3 are supposed to be three event then you have to keep all three function you can shorted the script code for assigning values to text field.
<script type="text/javascript">
function click3(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
}
function click1(y) {
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
}
function click2(z) {
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
</script>
You can make a single function if you have single click event and shorten the code for assignment like this,
function SomeClick(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}

As far as I understood your question, you could try the following, assuming that's how your HTML is structured:
HTML Markup:
<table id="mytable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
<tr>
<td class="name">Tom</td>
<td class="addr">789</td>
<td class="email">tom#dot.com</td>
</tr>
<tr>
<td class="name">Dick</td>
<td class="addr">456</td>
<td class="email">dick#dot.com</td>
</tr>
<tr>
<td class="name">Harry</td>
<td class="addr">123</td>
<td class="email">harry#dot.com</td>
</tr>
</table>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />​
jQuery:
$(".name").click(function(){
$("#txt1").val($(this).text());
$("#txt2").val($(this).nextAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(1).text());
});​
$(".addr").click(function(){
$("#txt2").val($(this).text());
$("#txt1").val($(this).prevAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(0).text());
});
$(".email").click(function(){
$("#txt3").val($(this).text());
$("#txt2").val($(this).prevAll().eq(0).text());
$("#txt1").val($(this).prevAll().eq(1).text());
});
DEMO: http://jsfiddle.net/Z9weS/

You can combine columns and rows. Per cell consisting id you give it th column title and
number of series it could be the index of the row combination of row and column gives the
address as per table cell by a specific event you can read the value of the id
Then you know to pull the cell value.
$('tr')
.click(function() {
ROW = $(this)
.attr('id');
$('#display_Colume_Raw')
.html(COLUME + ROW);
$('#input' + COLUME + ROW)
.show();
STATUS = $("#input" + COLUME + ROW)
.val();
});

Related

refreshing javascript calculated sum total on new checkbox use without input fields

With help I've gotten this script to change the class of the function to include countable but need to get the total calculation to update the sum of all fields shown when that change takes place.
The scripts are split with the top one set to calculate the total of all countable class fields and the second script section set to show the line items and add the countable class.
<script>
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.countable').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
</script>
<script>
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
These checkboxes allow display of the line items when selected.
<input class="my-activity" type="checkbox" value="42"/> example<br/>
<input class="my-activity" type="checkbox" value="43"/> example<br/>
<table id="sum_table">
<tr class="42" style="display:none">
<td>example</td>
<td></td>
<td></td>
<td class="price">7800</td>
</tr>
<tr class="43" style="display:none">
<td>First Area</td>
<td></td>
<td></td>
<td class="price">6900</td>
</tr>
<tr class="totalColumn">
<td>Total:</td>
<td></td>
<td class="totalCol"></td>
</tr>
</table>
You need to load jQuery before you can use it, so move:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
above the other 2 scripts. Then, replace your first script with this:
function showTotal(){
//grab the .countable elements from the #sum_table
var $countables =$("#sum_table .countable");
//loop through and add up the total from their texts
var total = 0;
for(var i = 0; i < $countables.length; i++){
total += Number($countables.eq(i).text());
}
//put the total in the .totalCol element
$("#sum_table td.totalCol").html(total);
}
and call this function at the end of your onchange function, like this:
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
//CALL IT HERE:
showTotal();
});
});

td background colouring applied to complete column rather to a single cell

I've below html.
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
Below is the jquery I've written.
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')').text());
}
}); var idx2 = [];
for(var x=0;x<list2.length;x++){
if(list[x]===list2[x]){
//console.log(list[x]);
}else{
console.log('mismatched : '+list[x]);
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
idx2.push(x);
}
}
});
I'm trying to compare values in list with values in lqwasb02 column and if it finds the difference, it should highlight the background of td cell in red colour.
Current issue with jquery code, it is highlighting the complete column.
Can someone please help me where I'm getting wrong? If possible, please pass on the recommended solutions.
Many Thanks in advance.
The problem is that in your .find you are returning multiple elements that it's selector matches. So as opposed to storing the text value for your td elements in the second array, just store the actual td element, compare it's text, and then you can assign the background color directly to the element as opposed to finding it again via it's index:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')')); // <-- Store the object here, not it's text value.
}
});
var idx2 = [];
for(var x=0; x < list2.length; x++){
if(list[x]===list2[x].text()) { // <-- compare list[x] to the text value of list2[x]
//console.log(list[x]);
} else {
list2[x].css("background-color", "red"); // <-- no find or selector needed, just apply it to the object you stored earlier.
};
idx2.push(x);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
this piece of code assign a background colour to each cell of index 'x' for each rows (each cells of index x of each table rows represent a column).
You have to select only the rows which contains the cells you want to colour.
Here is how i would have approached solving this issue:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
var colIndex = findColIndex('lqwasb02');
// Loop over table rows
$('tr').each(function(){
// Look up cell with specific index
var $cell = $(this).find('td').eq(colIndex);
// Check if the text of the cell is not present in the list and do smth
if ($.inArray($cell.text(), list) === -1) {
$cell.css('background', 'red')
}
});
});
// helper function to find the index of column by text in the header
function findColIndex (headerText) {
var $col = $('.myTable th:contains(' + headerText + ')');
return $('.myTable th').index($col);
}
https://jsbin.com/fafegi/1/edit?js,output

How to make one JavaScript function, handle multiple sets of inputs, being mathematically prosessed the same way

I have made this table: https://jsfiddle.net/Hougaard114/7qy70wpo/
It looks like i want it to, but it doesn't work quite like i want to. At the moment every input field has its own name, and therefor its own variable in JavaScript.
What i want is to have a Javascript function with a minimal amount of variable. What happens in each row is the same. The last row "u-værdi" spits out the result of 1/sum of"isolans"s. So i thought i could make a javascript looking like this:
function isolansBeregn () {
var calc1 = document.getElementById('lambda').value;
var calc2 = document.getElementById('tykkelse').value;
var result = calc2/calc1;
var numb = result;
numb = numb.toFixed(0);
document.getElementById('isolans').innerHTML = numb;
var uVærdi = 1/result;
uVærdi = uVærdi.toFixed(3);
document.getElementById('uværdi').innerHTML = uVærdi;}
It works, but only for the first row of inputs. Even though i give the next row the same id's, nothing happens when i type in numbers.... So now it looks like this:
HTML
<table>
<thead>
<th colspan="4">Demo</th>
</thead>
<tbody>
<tr>
<td style="width: 30%" class="tdh">Materiale</td>
<td style="width: 30%"class="tdh">Lambda værdi (λ<sub>50</sub>)</td>
<td style="width: 30%"class="tdh">Tykkelse (m)</td>
<td style="width: 10%"class="tdh">Isolans</td>
</tr>
<tr>
<td>Yderbeklædning</td>
<td><input type="number" id="lambda" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td><input type="number" id="tykkelse" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td id="isolans"></td>
</tr>
<tr>
<td>Isolering</td>
<td><input type="number" id="lambda2" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td><input type="number" id="tykkelse2" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td id="isolans2"></td>
</tr>
<tr>
<td>Inderbeklædning</td>
<td><input type="number" id="lambda3" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td><input type="number" id="tykkelse3" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td id="isolans3"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">U-værdi</td>
<td id="uværdi"></td>
</tr>
</tfoot>
</table>
and JavaScript
function isolansBeregn () {
var calc1 = document.getElementById('lambda').value;
var calc2 = document.getElementById('tykkelse').value;
var calc3 = document.getElementById('lambda2').value;
var calc4 = document.getElementById('tykkelse2').value;
var calc5 = document.getElementById('lambda3').value;
var calc6 = document.getElementById('tykkelse3').value;
var result = calc2/calc1;
var result2 = calc4/calc3;
var result3 = calc6/calc5;
var numb = result;
numb = numb.toFixed(0);
var numb2 = result2;
numb2 = numb2.toFixed(0);
var numb3 = result3;
numb3 = numb3.toFixed(0);
document.getElementById('isolans').innerHTML = numb;
document.getElementById('isolans2').innerHTML = numb2;
document.getElementById('isolans3').innerHTML = numb3;
var uVærdi = 1/((result+result2)+result3);
uVærdi = uVærdi.toFixed(3);
document.getElementById('uværdi').innerHTML = uVærdi;}
It feels like overkill.
The reason this is a problem for me, is because i want the user to be able to add another row, looking exactly like the others, with a JavaScript that doesn't mind.
Thank you in advance!
The minimal modifications version is:
Change the ids to names (except for uværdi)
Change your
onchange="isolansBeregn()"
to
onchange="isolansBeregn(this)"
so it passes a reference to the element on where the change occurred into the function.
Then we can work from that element what row we're in, and therefore find the other input elements in that row:
function isolansBeregn(input) {
// Update this row
var row = $(input).closest("tr");
var calc1 = row.find('[name=lambda]').val(); // Probably worth converting these to number explicitly
var calc2 = row.find('[name=tykkelse]').val();
var result = Math.round(calc2 / calc1); // Added rounding at the number rather than text level
row.find('[name=isolans]').html(result).data("result", result); // ** see below
// Get the sum of all the results
var sum = $("[name=isolans"]).get().reduce(function(s, el) {
return s + $(el).data("result");
}, 0);
var uVærdi = 1 / sum;
uVærdi = uVærdi.toFixed(3);
$('#uværd').html(uVærdi); // Again, perhaps .text()
}
Re my ** see below: We're displaying the number as text, but we'll need it as a number later, so we use jQuery's data feature to store it as a number as well. We could use the text are reparse it as a number, but I went the other way.
Explanation of reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Note: I used jQuery because you tagged jquery, but your code doesn't seem to be using jQuery anywhere. The above is totally possible without jQuery as well. The only bit that's really any more work is the .closest part.
However, this is a good use case for event delegation. You can get rid of all of those onchange=... attributes, and instead hook change on the table, and then use e.target to know which actual input changed. (The change event doesn't bubble natively, but jQuery makes it bubble, so event delegation works with it.)

how to add variable to 'classname' in jquery using match function?

I want to check the classname with pattern eg. sort-order12, sort-order13 using the match function in jquery.
The below usage is not working. Anyone can help ?
var sort_order = $('.js-data-selector.active:first').data('sort-order');
sort_order_next -> is the variable containing integer value.
var child = $("table tr td").filter(function() {
return $(this).prop("class").match(/"sort-order"+(sort_order_next)/)
}).closest("tr");
child.show();
I am trying to display the nodes with classname with pattern "sort-order-1", "sort-order-2" etc. according to the node value (sort-order-next) obtained.
Try this
var sort_order_next = 12;
var child = $("table tr td").filter(function() {
return $(this).prop("class").match(new RegExp('sort-order-' + sort_order_next));
}).closest("tr");
console.log(child);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="sort-order-12"></td>
</tr>
<tr>
<td class="sort-order-13"></td>
</tr>
<tr>
<td class="some-cls"></td>
</tr>
</table>

How to get the values from dynamically created row of textboxes in JSON

I am trying to create a row of text boxes dynamically through Javascript and read the values of the textbox in JSON. Later,I have to read JSON and display the values in textarea and this should achieved only though jquery and javascript.
I am able to create the text boxes dynamically but I am unable to read the values in JSON. When I use the jQuery part(mentioned below),the javascript to dynamically create textboxes is not working.Any suggestions please.
<table id="myTable">
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Occupation and Employer</th>
<th>Add</th>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtAge" /></td>
<td><input type="text" id="txtGender" /></td>
<td><input type="text" id="txtOccupation" /></td>
<td><input type="button" id="btnAdd" class="button-add" onClick="insertRow()" value="add"></input></td>
<td><input type="button" id="btnSave" class="button-add" value="Save"></input> </td>
</tr>
</table>
<script>
var index = 1;
function insertRow()
{
var table=document.getElementById("myTable");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
cell1.appendChild(t1);
var cell2=row.insertCell(1);
var t2=document.createElement("input");
t2.id = "txtAge"+index;
cell2.appendChild(t2);
var cell3=row.insertCell(2);
var t3=document.createElement("input");
t3.id = "txtGender"+index;
cell3.appendChild(t3);
var cell4=row.insertCell(3);
var t4=document.createElement("input");
t4.id = "txtOccupation"+index;
cell4.appendChild(t4);
index++;
}
$(document).ready(function(){
$("#btnsave").click(function ()
{
alert("Hi");
var dataToSend={
'Name':[],
'Age':[]};
dataToSend.Name.push({$("txtName").val().trim()});
dataToSend.Age.push({$("txtAge").val().trim()});
localStorage.setItem('DataToSend', JSON.stringify(DataToSend));
var restoredSession = JSON.parse(localStorage.getItem('dataToSend'));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
alert(restoredSession);
});
});
JSFIddle:http://jsfiddle.net/S7c88/
Since you are using jQuery you can greatly simplify the whole process by using methods like clone().
Here's a working example where I created one array of row objects. Since you aren't doing this in a form, I removed the ID's and just used data-name.
var $row;
function insertRow() {
$('#myTable').append($row.clone());
}
$(function () {
$row = $('tr').eq(1).clone(); /* clone first row for re-use*/
$('#myTable').on('click', '.btnSave', function () {
var dataToSend = [];
$('tr:gt(0)').each(function () {
var data = {};
$(this).find('input').each(function () {
data[$(this).data('name')] = this.value
});
dataToSend.push(data);
});
/* display data in textarea*/
$('#output').val(JSON.stringify(dataToSend, null, '\t'))
});
}) ;
I changed your input type=button to button to take advantage of using input selector while looping rows to create data and not have to filter out the buttons
Your demo has invalid html, missing <tr> for top set of <th>
DEMO
Some areas where you were going wrong:
$("txtName") Invalid selector
No row references in attempt to gather data

Categories

Resources