Getting Attribute from Table Cell into Script - javascript

I'm generating an HTML table which contains rows like this one: I've been able to successfully get the ID and the trackingNumber value, but I'm trying to get the data-categoryName-id value and I'm stumped. Here's my script:
$("input[type='text']").change(function() {
var parent = $(this).parents('tr');
var recid = $(this).closest('td').attr('id');
var trackingNumber = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr id="53462365">
<td>JB44566</td>
<td>SKU123</td>
<td>CARTON PAPER A4</td>
<td>PAPER</td>
<td></td>
<td>966257111</td>
<td></td>
<td id="53462365"><input type="text" class="form-control" placeholder="Tracking #" name="trackingNumber" data-categoryName-id="Office Supplies" autocomplete="off" value=""></td>
<td id="53462365"><input type="number" id="53462365" class="form-control" autocomplete="off" placeholder="ID Tag" name="idTag" value=""></td>
</tr>
Trying to add another like, e.g.:
var categoryName =
that returns the value for the data-categoryName-id for the current row but completely stumped.

you can use .attr()
$("input[type='text']").change(function() {
var parent = $(this).parents('tr');
var recid = $(this).closest('td').attr('id');
var trackingNumber = $(this).val();
var categoryName = $(this).attr('data-categoryName-id');
console.log(categoryName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr id="53462365">
<td>JB44566</td>
<td>SKU123</td>
<td>CARTON PAPER A4</td>
<td>PAPER</td>
<td></td>
<td>966257111</td>
<td></td>
<td id="53462365"><input type="text" class="form-control" placeholder="Tracking #" name="trackingNumber" data-categoryName-id="Office Supplies" autocomplete="off" value=""></td>
<td id="53462365"><input type="number" id="53462365" class="form-control" autocomplete="off" placeholder="ID Tag" name="idTag" value=""></td>
</tr>

jQuery has a .data() method that allows you to get or set data-* attributes:
var categoryName = $(this).data('categoryName-id');

Related

when checkbox is checked not able to fetch data that are against that checkbox

I have data that is displayed in the form of a table and each row has a checkbox.
I am trying to fetch the data of each row when the checkbox is clicked against that row.
<tr>
<td><input type="text" name="child_name"></td>
<td><input type="text" name="child_age"></td>
<td><input type="checkbox" ></td>
</tr>
<tr>
<td><input type="text" name="child_name"></td>
<td><input type="text" name="child_age"></td>
<td><input type="checkbox" ></td>
</tr>
These will get generated dynamically, so the naming needs to same for the input box, however when i am fetching the value typed by the user,it fetches the value of only first row, and the values is getting repeated multiple times
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
$tr = $(this).closest('tr');
var arr = [];
var data = $tr.children("td").map(function(){
var one = $("[name='child_name']").val();
var two = $("[name='child_age']").val();
arr.push(one)
arr.push(two)
return arr;
}).get();
console.log(data);
$('#post-result').append(data);
}
else if($(this).prop("checked") == false){
console.log("Checkbox is unchecked.");
}
});
});
Can anyone please tell how to resolve the issue
The name attribute in this case could complicate things a little bit. What I would do is use data-attributes to have specific identifiers for each row. Something like this:
UPDATED
I changed the behavior to work with dynamically added rows.
Using $(document).on("click"... you can affect future elements of the same type while $("[type='checkbox']").click() works only for currently existing elements.
I also took some liberty in expanding the example.
var children = [];
$(document).on("click", ".child-selector", function() {
var id = $(this).data("id");
if($(this).is(":checked")) {
var info = [];
info.push($(".child-name[data-id='"+ id +"']").val());
info.push($(".child-age[data-id='"+ id +"']").val());
console.log(info);
// An example of using objects to give some structure to the data
// and then store it to an array with all the checked rows
var child = {};
child.id = id;
child.name = $(".child-name[data-id='"+ id +"']").val();
child.age = $(".child-age[data-id='"+ id +"']").val();
children.push(child);
console.log(children);
} else {
console.log("Checkbox is unchecked.");
// An example of removing the specific children from the array
children.forEach(function(child, index) {
if(child.id == id) {
children.splice(index, 1);
}
});
console.log(children);
}
});
var clickCounter = 0;
var dataCounter = 13;
$("#add-child").click(function() {
var html = '<tr>'+
'<td><input type="text" class="child-name" data-id="'+ dataCounter +'" value="Child '+ clickCounter +'"></td>'+
'<td><input type="text" class="child-age" data-id="'+ dataCounter +'" value="'+ clickCounter +'"></td>'+
'<td><input class="child-selector" type="checkbox" data-id="'+ dataCounter +'"></td>'+
'</tr>';
$("table").append(html);
clickCounter++;
dataCounter++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" class="child-name" data-id="9" value="John Connor"></td>
<td><input type="text" class="child-age" data-id="9" value="12"></td>
<td><input class="child-selector" type="checkbox" data-id="9"></td>
</tr>
<tr>
<td><input type="text" class="child-name" data-id="10" value="Jane Connor"></td>
<td><input type="text" class="child-age" data-id="10" value="12"></td>
<td><input class="child-selector" type="checkbox" data-id="10"></td>
</tr>
<tr>
<td><input type="text" class="child-name" data-id="11" value="Tom Connor"></td>
<td><input type="text" class="child-age" data-id="11" value="13"></td>
<td><input class="child-selector" type="checkbox" data-id="11"></td>
</tr>
<tr>
<td><input type="text" class="child-name" data-id="12" value="T800"></td>
<td><input type="text" class="child-age" data-id="12" value="1"></td>
<td><input class="child-selector" type="checkbox" data-id="12"></td>
</tr>
</table>
<button type="button" id="add-child">Add Child</button>
Now, if you need to send the data via post you should review your usage of name because as it currently is it would only send one value.
You can use the context parameter of $(selector [, context]) to only search inside the current <tr>:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
if ($(this).prop("checked") == true) {
$tr = $(this).closest('tr');
var arr = [];
var one = $("[name='child_name']", $tr).val();
var two = $("[name='child_age']", $tr).val();
arr.push(one)
arr.push(two);
console.log(arr);
$('#post-result').append(arr);
} else if ($(this).prop("checked") == false) {
console.log("Checkbox is unchecked.");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" name="child_name" value="A Name"></td>
<td><input type="text" name="child_age" value="A Age"></td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td><input type="text" name="child_name" value="B Name"></td>
<td><input type="text" name="child_age" value="B Age"></td>
<td><input type="checkbox"></td>
</tr>
</table>
<pre id="post-result"></pre>

HTML Table - Iterate over row and sum the fields

I have then following table:
<table style="width:100%" id="testTable">
<tr>
<th>length per</th>
<th>width per</th>
<th>length</th>
<th>width</th>
<th>total</th>
</tr>
<tr align='right'>
<td>
<input type="text" name="length-per-input">
</td>
<td>
<input type="text" name="width-per-input">
</td>
<td>
<input type="text" name="length-total-input">
</td>
<td>
<input type="text" name="width-total-input">
</td>
<td>
<input type="text" name="total-output" disabled="disabled">
</td>
</tr>
<tr align='right'>
<td>
<input type="text" name="length-per-input">
</td>
<td>
<input type="text" name="width-per-input">
</td>
<td>
<input type="text" name="length-total-input">
</td>
<td>
<input type="text" name="width-total-input">
</td>
<td>
<input type="text" name="total-output" disabled="disabled">
</td>
</tr>
</table>
<input type=button value='+' onclick="addRow()" />
<input type=button value='Calculate' onclick="Calculate()" />
I also have the javascript which adds the value and puts it in total:
<script>
function Calculate() {
var lengthPerInput = $("input[name='length-per-input']").val();
var widthPerInput = $("input[name='width-per-input']").val();
var lengthTotal = $("input[name='length-total-input']").val();
var widthTotal = $("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
$("input[name='total-output']").val(total);
}
</script>
The aim here is to have it iterate over the two rows, then add each one separately.
I know how to get each row by using:
$('#testTable tr').each(function(){
console.log(this);
$(this).find('length-per-input').each(function(){
console.log(this);
})
})
But using the row (accessed via "this") I don't know how to get the correct cells, get their value, then perform the calculate on that row for the total.
Any advice on this please? Thank you!
function Calculate(tr_row) {
var lengthPerInput = tr_row.find("input[name='length-per-input']").val();
var widthPerInput = tr_row.find("input[name='width-per-input']").val();
var lengthTotal = tr_row.find("input[name='length-total-input']").val();
var widthTotal = tr_row.find("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
tr_row.find("input[name='total-output']").val(total);
}
For every row you call function to summ the values
To the function you pass the row, then it can collect values on that row
$('#testTable tr').each(function(){
Calculate($(this))
})
You can use each() function to iterate through table and use find() function to find cell values.
function Calculate() {
$('#testTable tr').each(function() {
var lengthPerInput = $(this).find("input[name='length-per-input']").val();
var widthPerInput = $(this).find("input[name='width-per-input']").val();
var lengthTotal = $(this).find("input[name='length-total-input']").val();
var widthTotal = $(this).find("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
$(this).find("input[name='total-output']").val(total);
});
}
Working Plunker
How to get a table cell value using jQuery?

JavaScript add new row and populate new rows inputs with data from dropdown value

I hope you can help me with a Javascript problem I'm having, I've been staring at this for days and I just can't figure it out!!
I've got a script that splits the value of an option dropdown and populates certain feilds with the splitted values.
Then I've got an 'Add Order Line' hyperlink to add a new row to a table, but I want the above feature to happen on any new line as well but nothing happens
I've recreated this in jsfiddle.
$(window).load(function(){
var selectEl = document.getElementById('part_selection');
selectEl.onchange = function () {
//var input1 = document.getElementsByName('PART_NO');
var input2 = document.getElementById('PART_DESCRIPTION');
var input3 = document.getElementById('PART_PRICE');
var input4 = document.getElementById('UNIT_MEAS');
var val = this.value;
var parts = val.split("_");
/*input1.value = parts[0];*/
input2.value = parts[1];
input3.value = parts[2];
input4.value = parts[3];
}
});
$(function(){
var counter = 1;
$('a.add-line').on('click',function()
{
counter ++;
$(this).prev('table.orderlinelist').find('tr').last().clone().find('input').val('').end().find('input.ORDER_LINE_NO').val(counter).end().appendTo('table.orderlinelist');
});
});
<table class="orderlinelist">
<tr>
<td>Line</td>
<td>Part</td>
<td>Part Description</td>
<td>Unit Price</td>
<td>Qty</td>
<td>UoM</td>
<td>Line Total</td>
</tr>
<tr >
<td>
<input type="text" name="ORDER_LINE_NO[]" class="ORDER_LINE_NO" id="ORDER_LINE_NO" value="1" readonly="readonly"/>
</td>
<td>
<select name="PART_NO" id="part_selection">
<option value="">Select a Part</option>
<option class="dropdown1" value="5461_Coxmoor Sideboard_299.00_EACH">5461</option>
</select>
</td>
<td>
<input type="text" name="part_desc" id="PART_DESCRIPTION" readonly />
</td>
<td>
<input type="text" name="PART_PRICE[]" id="PART_PRICE" class="orderprice"/>
</td>
<td>
<input type="text" name="QTY[]" id="QTY" class="orderqty"/>
</td>
<td>
<input type="text" name="UNIT_MEAS[]" id="UNIT_MEAS" class="orderuom"/>
</td>
<td>
<input type="text" name="TOTAL" id="TOTAL" class="orderprice"/>
</td>
</tr>
</table>
Add Line
Can you point me in the right direction?
Cheers
These are steps you can take to do what you want:
first add class attributes to the input tags, instead of ID.
Use jQuery .on() to handle your dynamic event.
Use closest to find the current row.
then using jQuery find, find the inputs based on their class attributes.
And continue the rest of your code scenario.
I took these steps on your code like:
$(document).on("change", "table.orderlinelist .part_selection", function () {
var jrow = $(this).closest('tr');
var input2 = jrow.find('.PART_DESCRIPTION');
var input3 = jrow.find('.PART_PRICE');
var input4 = jrow.find('.UNIT_MEAS');
var val = this.value;
var parts = val.split("_");
input2.val(parts[1]);
input3.val(parts[2]);
input4.val(parts[3]);
});
This is your working DEMO
you are duplicating the identifiers of elements and assigning this event change the "select" Specific.
yours is better to work with classes in this way
http://jsfiddle.net/4dPX2/16/
$(".orderlinelist").on("change", ".part_selection", function (e) {});

Grab the text from the nearest span tag using jquery on keyup press

I'm trying to grab the text from the nearest span tag with the class 'item_price' and save it to a variable - can anyone tell me whats wrong
Also I am trying to grab the 'hidden' input also
$('#ajax_basket').on('keyup','input',function(event) {
var qty = $(this).val();
var item_price = $(this).find('span.item_price').text();
var hidden_id;
console.log(qty);
console.log(item_price);
});
<form id="ajax_basket">
<table>
<tr><td><input type="hidden" name="1[rowid]" value="5333a934f53d623eb18c490b57522d93"></td></tr>
<tr>
<td>Apple iPhone 2G</td>
<td><input type="text" name="1[qty]" value="1" maxlength="2" size="1" class="input-mini qty" /></td>
<td style="text-align:right" class="item_price_row">$<span class="item_price">15.00</span></td>
<td style="text-align:right" class="sub_total">$15.00</td>
</tr>
<tr>
<td>Apple iPhone 5G</td>
<td><input type="text" name="1[qty]" value="1" maxlength="2" size="1" class="input-mini qty" /></td>
<td style="text-align:right" class="item_price_row">$<span class="item_price">115.00</span></td>
<td style="text-align:right" class="sub_total">$115.00</td>
</tr>
</tr>
</table>
</form>
You have to backstep to the parent tr, then find
$('#ajax_basket').on('keyup','input',function(event) {
var qty = this.value
var item_price = $(this).closest("tr").find('span.item_price').text();
var hidden_id;
console.log(qty);
console.log(item_price);
});
The below line
$(this).find('span.item_price').text();
gets searches for span with class item_price among descendents of text box.
Try something like below:
$(this).parent().parent().find('span.item_price').text();

Show hide elements based on ID from select dropdown javascript

I know this is proboly the most asked question out there but I have scoured the net and tried several examples and none of them have worked. Here is my issue.
First I have no control over the TR TD structure, can't use DIV.
I need to be able to display certain TD's based on the select dropdown menu value. I have 4 different id's I am using "to", "to_field", "from", "from_field". The script I have shown is not working. Can someone help me out?
Example: If someone selects "In Use" in the dropdown then I just want all the elementID that have "from" and "from_field" to display only. If someone selects a different value then I would like to change that around.
<script type="text/javascript">
function showstuff(element){
document.getElementById("from").style.display = element=="in_use"?"visibility":"visible";
document.getElementById("to").style.display = element=="in_use"?"visibility":"hidden";
document.getElementById("from_field").style.display = element=="in_use"?"visibility":"visible";
document.getElementById("to_field").style.display = element=="in_use"?"visibility":"hidden";
document.getElementById("from").style.display = element=="relocated"?"visibility":"visible";
document.getElementById("to").style.display = element=="relocated"?"visibility":"visible";
document.getElementById("from_field").style.display = element=="relocated"?"visibility":"visible";
document.getElementById("to_field").style.display = element=="relocated"?"visibility":"visible";
}
</script>
<table>
<tr>
<td><h2>Add/Edit Parts</h2></td>
</tr>
</table>
<form action="includes/inventory_parts.php" method="post" name="myform">
<table cellpadding="10" style="border:solid 1px #000000">
<tr>
<td colspan="20"><h3>Add New Part</h3></td>
</tr>
<tr>
<td style="font-weight:bold">Printer Man Part#</td>
<td style="font-weight:bold">Part#</td>
<td style="font-weight:bold">Title</td>
<td style="font-weight:bold">Serial#</td>
<td style="font-weight:bold">Status</td>
<td id="from" style="font-weight:bold;visibility:hidden">From Printer Serial#</td>
<td id="to" style="font-weight:bold;visibility:hidden;">To Printer Serial#</td>
<td style="font-weight:bold">Submit</td>
</tr>
<tr>
<td><input type="text" name="printer_man_part_number" /></td>
<td><input type="text" name="part_number" /></td>
<td><input type="text" name="title" /></td>
<td><input type="text" name="this_part_serial_number" /></td>
<td>
<select name="status" onchange="showstuff(this.value);">
<option></option>
<option value="in_use">In Use</option>
<option value="relocated">Relocated</option>
<option value="disposed">Disposed</option>
<option value="selling">Selling</option>
</select>
</td>
<td id="from_field"><input type="text" name="from" style="visibility:hidden" /></td>
<td id="to_field"><input type="text" name="to" style="visibility:hidden" /></td>
<td><input type="submit" name="submit" value="Add Part" /></td>
</tr>
</table>
</form>
function showstuff(element) {
// first hide everything
document.getElementById("from").style.visibility = 'hidden';
document.getElementById("to").style.visibility = 'hidden';
document.getElementById("from_field").style.visibility = 'hidden';
document.getElementById("to_field").style.visibility = 'hidden';
var targets;
// select the IDs that should be unhidden based on element
switch (element) {
case 'in_use': targets = ['from', 'from_field']; break;
case 'relocated': targets = ['to', 'to_field']; break;
...
}
// now unhide the selected IDs.
for (var i = 0; i < targets.length; i++) {
document.getElementById(targets[i]).style.visibility = 'visible';
}
}

Categories