jQuery Map To Retrieve Comma Separated Values Separately - javascript

I am using multiple text box to insert data into database table. So doing few researches and used online resources to make it work. But stuck into one basic thing, I guess. The issue is with the jQuery mapping. Let me share the code here:
//Add row to the table
$('#btnAddRow').on('click', function() {
var $clone = $('#tblQuesAns tbody tr:last').clone();
$clone.find('input').val('')
$('#tblQuesAns tbody').append($clone);
});
//Add more rows for option
$('body').on('click', '.addOptions', function() {
$(this).parent().append('<div><input class="txtOptions" type="text" /></div>');
});
//Get text box values
$('#btnGetValues').on('click', function() {
const allData = $('#tblQuesAns tbody tr').map(function() {
const $row = $(this),
question = $row.find('.txtQuestion').val(),
options = $row.find('.txtOptions').map(function() {
return this.value;
}).get().join(" ");
//return { question, options };
alert(question + ' ' + options.replace(/\s+/g, "_"));
}).get();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="btnAddRow" type="button">
Add Row
</button>
<button id="btnGetValues" type="button">
Get Values
</button>
<table id="tblQuesAns" border="1">
<thead>
<tr>
<th>Question</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="txtQuestion" value="Capital of Englnad" />
</td>
<td>
<input class="txtOptions" value="London" />
<span class="addOptions">(+)</span>
</td>
</tr>
<tr>
<td>
<input class="txtQuestion" value="Current Pandemic" />
</td>
<td>
<input class="txtOptions" value="Corona" />
<span class="addOptions">(+)</span>
</td>
</tr>
</tbody>
</table>
By default, jQuery map uses comma and I tried to remove those by using replace method as follows:
options.join(' ').replace(/\s+/g, "_")
Now I may have options that may contain comma. For example:
Question Options
Question 1 New York
Jakarta
London, Paris
Munich
So problem is, the values having space from text boxes also get replaced with the underscore sign replace(/\s+/g, "_"). So I get this output:
New_York_Jakarta_London,_Paris_Munich
But my expected output is this:
New York_Jakarta_London, Paris_Munich
I tried a different way that works but in this case all the text box values get concatenated:
var options = $("input[name*='txtOptions']");
var str = "";
$.each(options, function(i, item) {
str += $(item).val();
});
The problem with the above is, when I've different questions say question 1, question 2, it'll merge all the options to both of them. Though I want specific options for both questions.

Something like this?
//Add row to the table
$('#btnAddRow').on('click', function() {
var $clone = $('#tblQuesAns tbody tr:last').clone();
$clone.find('input').val('')
$('#tblQuesAns tbody').append($clone);
});
//Add more rows for option
$('body').on('click', '.addOptions', function() {
$(this).parent().append('<div><input class="txtOptions" type="text" /></div>');
});
//Get text box values
$('#btnGetValues').on('click', function() {
const allData = $('#tblQuesAns tbody tr').map(function() {
const $row = $(this),
question = $row.find('.txtQuestion').val(),
options = $row.find('.txtOptions').map(function() {
return this.value;
}).get().join("_");
return {question,options}
}).get()
const x = allData.map(item => `${item.question}_${item.options}`).join(" ")
console.log(x)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="btnAddRow" type="button">
Add Row
</button>
<button id="btnGetValues" type="button">
Get Values
</button>
<table id="tblQuesAns" border="1">
<thead>
<tr>
<th>Question</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="txtQuestion" value="Capital of England" />
</td>
<td>
<input class="txtOptions" value="London" />
<span class="addOptions">(+)</span>
</td>
</tr>
<tr>
<td>
<input class="txtQuestion" value="Current Pandemic" />
</td>
<td>
<input class="txtOptions" value="Corona" />
<span class="addOptions">(+)</span>
</td>
</tr>
</tbody>
</table>

Related

Live search in table for specific column

I'm currently trying to create a live search for a specific column in a table. I've searched a bit but I can only find solutions to search over all columns. This is my code:
function searchInTable(table) {
var value = this.value.toLowerCase().trim();
jQuery(table).each(function (index) {
if (!index) return;
jQuery(this).find("td").each(function () {
var id = $(this).text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
return not_found;
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search-table-input" class="search-table-input" type="text"
onkeyup="searchInTable('.table tr')" placeholder="Search Number...">
<table class="table">
<thead>
<tr>
<th class="table-number">
<span class="nobr">Number</span>
</th>
<th class="table-date">
<span class="nobr">Date</span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a>264</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
<tr>
<td>
<a>967</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
<tr>
<td>
<a>385</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
<tr>
<td>
<a>642</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
</tbody>
</table>
My function has some errors and don't work like it should.
How can I change my function that way that when I start typing only the number gets filtered? I need to make the function dynamically so that I can pass the column which should be used for the search.
The line that's causing it to search over all the columns is this one:
jQuery(this).find("td").each(function () {
...which takes each cell in the current row and looks to see if it contains value. If you only want to check as specific column, you should pass in the column index as something like columnIndex, and then you can select the correct column by doing jQuery(this).find("td").eq(columnIndex), using jQuery's .eq() function to select the correct one. The code should look something like this:
function searchInTableColumn(table, columnIndex) {
//check this.value exists to avoid errors
var value = this.value ? this.value.toLowerCase().trim() : "";
jQuery(table).each(function (index) {
if (!index) return;
var tableCell = jQuery(this).find("td").eq(columnIndex);
var id = tableCell.text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
});
}
Then you can call searchInTableColumn(table, 0) and it will only look in the first column.

How do I locate elements in the same row as another in a dynamic table?

I am making a page that contains a table with a button to add a row. It is a table for users to input data, and will eventually be submitted to a database.
Currently, I have a price and a quantity field in each row. When either of them change, I want to calculate the total and write it to another cell.
This is my event handler (wrapped in $(document).ready()):
$(".quantity_input, .price_input").change(function () {
console.log(this.value);
cal_total();
});
This is my current code:
function cal_total() {
if (isNaN(parseFloat(this.value))) {
alert("You must enter a numeric value.");
this.value = "";
return;
}
var cell = this.parentNode;
var row = cell.parentNode;
var total = parseFloat($("#items_table tr").eq(row.index).find("td").eq(3).find("input").first().val()) * parseFloat($("#items_table tr").eq(row.index).find("td").eq(4).find("input").first().val());
if (!isNaN(total)) {
$("#items_table tr").eq(row.index).find("td").eq(5).html(total.toFixed(2));
}
}
And this is what the inputs look like:
<input type='text' class='fancy_form quantity_input' name='quantities[]' size='4' style='text-align:center;border-bottom:none;'>
In addition to my original question, the event is never fired. Can anyone see why?
But more importantly, is this the best way to retrieve the values? I really don't think so but I cant come up with anything more clever.
Thank you!
you have to pass paremeter to calc_total to define input or tr
try this code
$(".quantity_input, .price_input").change(function () {
$(".quantity_input, .price_input").change(function () {
cal_total(this);
});
});
function cal_total(elem){
var row=$(elem).closest("tr")
var quantity=row.find(".quantity_input").val()-0
var price=row.find(".price_input").val()-0
var total=quantity * price
row.find(".totl_input").val(total)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
</table>

jQuery math function not working for dynamically added new table row

I need to use jQuery to perform basic math function as well as adding additional rows to a table dynamically. So far I have this piece of code:
<script type="text/javascript">
$(document).ready(function() {
$(".sub").focusout(
function() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = (gross - tare);
$("#net").html(Math.round(net * 1000) / 1000);
});
$("#add").click(function() {
$('#lineItemTable tbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
return false;
});
});
</script>
And my html looks like this:
<body>
<a id="add">add Line</a>
<table id="lineItemTable">
<tr>
<th>Gross</th>
<th>Tare</th>
<th style="padding-right: 10px">Net Weight</th>
</tr>
<tr class="row_to_clone">
<td>
<input type='number' step="any" name='gross' id='gross' class='sub' />
</td>
<td>
<input type='number' step="any" name='tare' id='tare' class='sub' />
</td>
<td id="calculated">
<p id='net' class='sub1'></p>
</td>
</tr>
</table>
</body>
Now, before adding another row to the table, the basic math function works, but the math function does not works for the new added row after I click the add Line button. What am I missing here?
You are violating html rules basically by cloning elements with id. According to html rules the ids in the DOM should be unique. So what I suggest is, change id to class and make use of $(this) to fetch correct elements as below:
DEMO
Your updated html would be as follows:
<a id="add">add Line</a>
<table id="lineItemTable">
<tr>
<th>Gross</th>
<th>Tare</th>
<th style="padding-right: 10px">Net Weight</th>
</tr>
<tr class="row_to_clone">
<td>
<input type='number' step="any" name='gross' class='gross sub' />
<!-- Remove id and add it as class-->
</td>
<td>
<input type='number' step="any" name='tare' class='net sub' />
<!-- Remove id and add it as class-->
</td>
<td>
<p class='net'></p>
<!-- Remove id and add it as class-->
</td>
</tr>
</table>
and JS would be:
$(document).ready(function() {
$(".sub").focusout( //get it using class
function() {
var parent=$(this).closest('.row_to_clone'); //find its parent first
parent.find(".net").html(''); //then get all those elements with necessary class belonging to its parent
var gross = parent.find('.gross').val();
var tare = parent.find('.net').val();
var net = (gross - tare);
parent.find(".net").html(Math.round(net * 1000) / 1000);
});
$("#add").click(function() {
var newRow=$('#lineItemTable tbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
newRow.find('input').val(''); //Comment this if you you want to persist the value
newRow.find('p').text('');//Comment this if you you want to persist the value
return false;
});
});
You have to write a function and have to call it again after inserting the html. The new html is not in the DOM when you call the site:
<script type="text/javascript">
function do_math() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = (gross - tare);
$("#net").html(Math.round(net * 1000) / 1000);
});
$(document).ready(function() {
$(".sub").focusout(
do_math();
);
$("#add").click(function() {
$('#lineItemTabletbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
do_math();
return false;
});
});
</script>

Iterating through table and get the value of a button in each tablerow jQuery

I have buttons in a table which are created dynamically. I want to iterate through a table, get the tablerows which contain a checked checkbox and get the value of a button inside the tablerow. I want to push the values in an array after. The buttons don't have a unique ID so I cannot get their values by id.
I tried to get the values through giving the buttons a class and itering works fine but the array is filled with empty entries.
$("#bt_multiple_deletion").off().on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).find(".filefolder-button").text());
});
})
I really don't know what Im doing wrong. I tried to get the values with .text(), .val() etc.
My table row looks like this:
<tr class="select">
<td>
<span class="countEntries"><input id="lv_fifo_ctrl7_cb_delete_file" type="checkbox" name="lv_fifo$ctrl7$cb_delete_file" /></span>
</td>
<td>
<img src="images/icons/013_document_02_rgb.png" alt="document" />
</td>
<td class="name">//the button i want to get the value from
<input type="submit" name="lv_fifo$ctrl7$bt_file" value="013_document_png.zip" id="lv_fifo_ctrl7_bt_file" class="filefolder-button download file del" style="vertical-align: central" />
</td>
<td>
<span id="lv_fifo_ctrl7_lb_length">33.14 KB</span>
</td>
<td>
<span id="lv_fifo_ctrl7_lb_CreationTime">21.10.2014 07:34:46</span>
</td>
<td></td>
<td>
<input type="submit" name="lv_fifo$ctrl7$bt_del_file" value="delete" id="lv_fifo_ctrl7_bt_del_file" class="delete-button delete-file" />
</td>
</tr>
The problem is rows is the input elements not the tr elements so in the loop you need to find the tr which contains the input then find the target element inside it
$("#bt_multiple_deletion").off().on("click", function () {
var checked = $(".select").find("input[type=checkbox]:checked");
var files = checked.map(function () {
return $(this).closest('tr').find(".filefolder-button").val();
}).get();
})
Another option is
$("#bt_multiple_deletion").off().on("click", function () {
var rows = $(".select").find("tr").has('input[type=checkbox]:checked');
//var rows = $(".select").find('input[type=checkbox]:checked').closest('tr');
var files = rows.map(function () {
return $(this).find(".filefolder-button").val();
}).get();
})
#Timo Jokinen Do you need this
$("#bt_multiple_deletion").on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).parents("tr").find("td.filefolder-button").text());
});
console.log(files);
})
<table class="select">
<tr>
<td class="filefolder-button">test1</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test2</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test3</td>
<td><input type="checkbox" /></td>
</tr>
</table>
<button id="bt_multiple_deletion">delete</button>
Checkout example link here

Deleting a specific row in a table

I'm trying to delete a specific row from a table using javascript. The way I'm trying to do it now, is by retrieving the ID of the current row by clicking a button (the delete button) and then deleting the row. The problem is that I'm not retrieving the current row ID in the table. If someone could help me retrieve the the ID of the current row when the user clicks the delete button, I think I can solve the rest myself. Thanks
/*The Javascript*/
function delete_row() {
alert('id goes here');
//getElementById('row').innerHTML ='hello';
//id.deleteRow();
//var table = document.getElementByTagName('items_table');
//var row = table.rows[index];
//document.getElementByTagName('items_table').deleteRow(0);
}
/*The HTML of the Table*/
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
/* Five rows in this table... */
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
</table>
You could just ascend the tree until you find a row:
function delete_row(btn) {
var tr = btn;
while(tr && tr.nodeName != "TR") tr = tr.parentNode;
if( !tr) throw new Error("Failed to find the row, was the function called correctly?");
tr.parentNode.removeChild(tr); // delete it
}
And:
<button onClick="delete_row(this);">X</button>
The this is important, as it provides a reference to the button that was clicked, so we can find the row it is in.
Check this code. It has been verified and will do your job perfectly. :)
<script>
function delete_row(me) {
alert(me.parentNode.parentNode.id);
}
</script>
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
</table>
Can't you just change <button onclick="delete_row();">X</button> to <button onclick="delete_row('row_5');">X</button>, in each row, respectively?
Your handler would look like:
function delete_row(theID) {
alert(theID);
}

Categories

Resources