I have the following code:
var table = $("#b-table");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
qLine = $tds.eq(0).text(),
qPartNumber = $tds.eq(1).text(),
qComments = $tds.eq(5).val();
console.log(qLine);
console.log(qPartNumber);
console.log(qComments);
});
qLine and qPartNumber are copying over fine, as these are text values within the td element, but qComments is not copying over, as within the td element is another input element, like so:
<td><input class="qComments" type="text"></td>
I've tried using:
$tds.eq(5).val();
$tds.eq(5).html();
$tds.eq(5).text();
$tds.input.eq(5).val();
$tds.eq(5).input.val();
and none of these capture the value of the input - and the last two error out for bad syntax.
Try something like this
$tds.eq(5).find("input").val();
Related
I am rather new to JavaScript. In my experimentation with some sample code, I have created an html file which contains a table. In one of the table data fields I have a text type field. Is there a way to make a button that inserts a pre-defined template for entry that allows for manipulation? aka I press a button "money" that inputs an additional formatted text to "$0.00".
so for example
function input_button(){
var template = "$0.00"
var my_txt = document.getElementById("money");
my_txt.value += Template;
On a side note, what if I wanted to use subscript and superscript? I have tried utilizing the .sup() and .sub() methods, but it just inserts the tags and doesn't alter the aesthetics of the text. ( so in the table, it looks like
<sub> things to be subscript </sub>
opposed to
things to be subscript
I'm not familiar with any way to template text formats, so you might just have to hard code in the logic. As to your second question, when you use the .sup and .sub methods, are you inserting the result in the inner html? For example:
function helloWorldSuper(){
var str = "Hello World";
var result = str.sup();
document.getElementById("tableCell").innerHTML = result;
}
To apply a mask to the input field in order to auto-format values with a template you will need to listen to input key press events and handle according to your mask. There are some scripts that already do this, like Masked Input Plugin for jQuery.
If you want the input text to just have $0.00 as an initial value, it's quite easy to do.
You can create and insert a row into the table via JavaScript like this:
<html>
<body>
<button id="insertRowButton">Insert</button>
<table>
<thead>
<tr><th>Text</th><th>Input</th></tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<script>
(function() {
// Elements used
var tableBody = document.getElementById('tableBody'),
insertRowButton = document.getElementById('insertRowButton');
// Create a new row template
function createRow() {
var tr = document.createElement('tr'),
tdText = document.createElement('td'),
tdInput = document.createElement('td'),
sub = document.createElement('sub'),
input = document.createElement('input'),
text = document.createTextNode('This is a text node '),
subscriptText = document.createTextNode('with subscript');
sub.appendChild(subscriptText);
tdText.appendChild(text);
tdText.appendChild(sub);
input.value = '$0.00';
tdInput.appendChild(input);
tr.appendChild(tdText);
tr.appendChild(tdInput);
return tr;
}
// Insert a new row into table
function insertRow() {
var tr = createRow();
tableBody.appendChild(tr);
}
// Bind events
insertRowButton.addEventListener('click', insertRow);
}());
</script>
</body>
</html>
Here is it at JSFiddle: http://jsfiddle.net/ck7qargw/
I'm a little confused but I'm making the assumption that you are trying to add sup/sub script via innerHTML?
var template = "<span class='supStyle'>$0.00</span>"
CSS:
.supStyle{vertical-align:top;font-size:smaller;}
Or, you can use a forloop:
mySup = document.getElementsByClassName("supStyle");
for (var i=0;i<mySup.length;i++)
{
mySup[i].style.verticalAlign = "sub";
mySup[i].style.fontSize = "smaller";
}
I'm writing some JavaScript to clone a table row containing form elements.
It's working well so far but there's one piece I can't quite figure out.
The element names have a number which increases with every row.
E.g:
<table>
<tbody>
<tr>
<td><input type="text" name="name[0][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
<tr>
<td><input type="text" name="name[1][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
</tbody>
</table>
I need the cloned row to update the number. There are multiple fields in each row which need this updated number so I can't just include the new name in the jQuery code. What I think has to happen is I need get the name, use a regex replace, then update the attribute.
Here's my current (simplified for the example) jQuery:
// Current num of elements. Names are 0 based so this will be the number used
// for the new name.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Set the new field selector.
var $newRow = $(this).closest('tr').next();
$newRow.find('input[type="text"]').val('');
formRowCount++;
});
Can someone point me in the right direction. Before formRowCount++; I need to get the current element name and update the number with formRowCount.
Yeah, you can use regex if you want.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row and insert it.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Select the input field
var $newInput = $(this).closest('tr').next().find('input[type="text"]');
// Update the input value and name attribute
var newName = $newInput.attr('name').replace(/^(name\[)\d+(\].+)$/, '$1' + formRowCount + '$2');
$newInput.val('').attr('name', newName);
// Update the number
formRowCount++;
});
I have two table on my page like the picture shown here.
What I want to do is:
select rows in the Source Table
read the data in ID field, Name field from the Source Table, and also the value of radio button.
Form these data as rows of Target Table and append these rows into Target Table.
Now Im using two arrays to store the ID and Name that read from Source Table, but im a bit confused about how to form a row for the Target Table.
$('#btnLinkCase').click(function (event) {
var caseID = $('#caseID').text();
var linkedIDArr = []; //array list for selected id
var linkedNameArr = []; //array list for selected name
$('#linkCaseTable tbody tr td:nth-child(2)').each(function (index, el) { //store each paire of <tr> into array
linkedIDArr.push(el);
});
$('#linkCaseTable tbody tr td:last-child').each(function (index, el) { //store each paire of <tr> into array
linkedNameArr.push(el);
});
$.each(linkedCaseIDArr, function (index, val) {
//whats next?
});
});
Please see all source code here
Any ideas of doing this? Thanks in advance
Edit:
If multiple rows are selected they will use the same value from the radio button. eg: two rows are selected and "Type 1" is checked. In target table, their relationship all are "Type 1". I hope I have explained myself..
Try:
$('button').click(function (event) {
$("#sourceTable tr:gt(0)").each(function(){
var th = $(this);
console.log("dfg")
if($(th).find("input[name='link-cbx']").is(":checked")){ //assuming ids are unique remove condition if you do notwant so
var id = $(th).find("td:eq(1)").text();
var name = $(th).find("td:eq(7)").text();
var type = "Type "+$("input[name='linkType']:checked").val();
if($("#targetTable:contains('"+id+"')").length < 1){
$("#targetTable").append("<tr><td>"+id+"</td><td>"+name+"</td><td>"+type+"</td></tr>");
}
}
});
});
Updated fiddle here.
I have a datatable containing a list of Cars. each row in the html contains a Car ID. I have added checkbox column to the first cell in my datatable - if it is checked the row is highligted to indicate to the user they have selected that row. What I waht to do is get all the IDs of all the cars a user has selected on clicking a button on the page. (also there are other columns in the table row where I have checkboxes (i.e - a Manual column or an Automatic column which will somtime be checked - like in column 5 ot 6 in the table)
so this is part of the cshtml for my page..
#foreach (var car in Model.Cars)
{
<tr carId="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
//more stuff set in other tds in table
Then this is the JS I have for the page so far.
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
carsListTable.find("tr").each(function (index, para) {
$('tr').find('td:input:checked:first').each(function () {
var car= new Object();
alert($(this).parent().parent().attr("carId"));
car.ID = $(this).parent().parent().attr("carId");
cars.push(car);
});
});
var jsonString = $.toJSON(cars);
I want to then return the json string to my controller (I do this by passing the value into a hidden field on my model and then deserialize - but at the minute I am getting it as empty. My problem is getting the best way to get the id from the row if it is checked?
You can use the selectors :checkbox:checked and use the jQuery.map to convert the array. The jQuery.closest() method will give the closest ancestor matching the given selector.
var cars = carsListTable.find('.table-data :checkbox:checked').map(function(i, v){
return {
ID : $(v).closest('tr').attr('carId')
}
});
Demo Fiddle
Note: The id of elements should be unique in a document so the id of the checkbox should be removed or has to be suffixed or prefixed by a dynamic value like the car id.
First, you should use class instead id for elements that will be present more than once. I suggest change #SelectIndividual for .SelectIndividual on the checkbox input). Another thing you should change is the carId attribute, because is not semantic valid. You should use custom data attributes instead. This is how your code should look like:
HTML
#foreach (var car in Model.Cars)
{
<tr data-carID="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
Jquery
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
$('SelectIndividual:checked').each(function () {
var car= new Object();
car.ID = $(this).parent().parent().data('carID');
cars.push(car);
});
});
//keep doing things
I would suggest to use the data-* attributes that are valid HTML5 as well as the jQuery.data() methods for the id of the car.
Can you assign a class to all checkboxes in first column and then try this
$('.cbClass:checked').each(function () {
tr = $(this).closest('tr');
// use the row
})
In my web application, I've set of checkboxes which on check populate a textbox above them.(If more than one checkbox is selected, then their values appear in the textbox separated by commas).
These set of checkboxes appear as rows in my HTML table.
Here's my HTML code.
<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">
<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>"
onclick="javascript:updateTextArea(<%=rCount%>);">
And the corresponding JS function is as follows:
function updateTextArea(rCount) {
var allVals = new Array();
$("#contactInfo input['commentText' + rCount]:checked").each(function() {
(allVals).push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
}
The rCount variable in the above function is the row # of my table.
Using this above, I'm not getting the expected behaviour..
For ex. If for row 1 of my table, I check chkbox 1 and 2, it correctly gets populated with values of those checkboxes. Now, for 2 of my table, I check only chkbox 3, it gets populated with the values 1,2 and 3 and not only 3 as I expect it to.
Any help will be greatly appreciated.
It would be better to use jQuery to set an event handler rather than setting it inline.
You want to use the onchange event not the onclick event.
If you add class names of checkboxes (or whatever you want) to the checkboxes the following will work:
$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked
var par = $(this).closest("tr")[0];
var parID = par.id;
var patt1=/([0-9]+)$/g;
var rCount = parID.match(patt1); //Gets number off end of id
var allVals = new Array();
//Get all checkboxes in current row that are checked
$(par).find("td input.checkboxes:checked").each(function() {
allVals.push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
allVals = null; //empty array as not needed
});
I believe this or something along these lines will do what you want
You're trying to use the rCount variable from within the quoted string. Try this instead:
$("#contactInfo input['commentText" + rCount + "']:checked")