Loop through a form which contains another form - javascript

I want to loop through a form with Javascript but my problem is that I have another form in the first form.
I'd like to loop through the first form only, not the inner one. I found this method on an other post :
var table = $("#table_cultures tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + productId
+ '\nProduct: ' + product
+ '\nQuantity: ' + Quantity);
});
This method works but loop through the both forms.
EDIT 1 :
The html looks like :
<form>
<table>
<tr>
<td>Something here</td>
</tr>
<tr>
<td>
<form>
<table>
//tr td ...
</table>
</form>
</td>
</tr>
</table>
</form>

nesting of <form> elements is not allowed
please see:
https://www.w3.org/TR/html5/forms.html#the-form-element
"...Flow content, but with no form element descendants..."

Related

Datatable row : manually update field

I have a datatable. I get a set of selected rows.
When i loop through, and update the value of a field remark,
I can't do it.
how do i manually update the value of a specific field in a row?
var table = $('#bankReconDataListing').DataTable();
$.map(table.rows('.selectedrow').data(), function (item) {
item.remarks = 'updated values';
console.log('-----------------1>',item);
});
<table id="bankReconDataListing">
<thead>
<tr>
<td>head</td>
<td>gender</td>
</tr>
</thead>
<tbody>
<tr><td>one</td><td>boy</td></tr>
<tr class="selectedrow"><td>two</td><td>boys</td></tr>
<tr><td>three</td>
<td>boys</td></tr>
</tbody>
</table>
var table = $('#bankReconDataListing').DataTable();
var temp = table.row(2).data();
alert("value before update = " + temp[0]);
temp[0] = "six";
table.row(2).data(temp).draw();
alert("value after update = " + temp[0]);

Duplicate items appearing in shopping cart

I'm trying to basically build a shopping cart on a static site. Items are displayed on a table. I built this shopping cart from scratch, no external jQuery shopping cart libraries used.
There's one feature I can't seem to get to work: When a user adds an item that already exists in the shopping cart, it should only increase the quantity instead of adding the item to the table.
Here's a JSFiddle link with everything I've implemented so far and a working demo, but you can also see the code below.
Here's the JS that adds the item:
$( "#addBtn" ).click(function() {
var item = $("#orderMenu option:selected").text();
var qty = $("#orderQty option:selected").text();
var newRowContent = "<tr><td>" + qty + "</td><td>" + item + "</td>";
$("#cart-info tbody").append(newRowContent);
});
Here's the simplified HTML, for the sake of simplicity:
<table class="table" id="cart-info">
<thead>
<tr>
<th>#</th>
<th>Item</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<select id="orderMenu">
<option>Foo</option>
<option>Bar</option>
</select>
<select id="orderQty">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<button id="addBtn">ADD TO CART</button>
Here's the pseudocode I'd like to convert to jQuery but have no idea how.
(Apologies for the weird pseudocode/jQuery hybrid, I'm still learning jQuery)
for each <td> in #cart-info {
if (<td>.html() == item) {
qtyCell = the previous <td>
oldQty = Number(qtyCell.text())
newQty = oldQty + qty
qtyCell.html(newQty)
exit for loop
}
}
The website itself is written purely in HTML/CSS/JS, so it is a completely static site.
Thank you very much in advance!
Check this fiddle
new fiddle
Use the value of each option to determine if it has already been added to the table:
$( "#addBtn" ).click(function() {
var item = $("#orderMenu option:selected").text();
var item_val = $("#orderMenu").val();
var qty = $("#orderQty option:selected").text();
var newRowContent = "<tr><td class='qty'>" + qty + "</td><td data-val='"+item_val+"'>" + item + "</td>";
if ($("#cart-info tbody [data-val='"+item_val+"']").length < 1)
$("#cart-info tbody").append(newRowContent);
else {
var new_qty = parseInt($("#cart-info tbody [data-val='"+item_val+"']").prev('.qty').text())+parseInt(qty);
$("#cart-info tbody [data-val='"+item_val+"']").prev('.qty').text(new_qty);
}
});
EDIT:
fixed fiddle url
EDIT 2
new fiddle updating quantities
You can achieve it on
Maintaining a list
An array which consists of key-pair value(JSON) item ID and it's quantity as field
Ex:-
var items = [
{
itemID:101,
name:"Mobile:"
qty:1
},
{
itemID:102,
name:"Pen Drive"
qty:3
}
]
On adding a new item push the respective itemID, qty, name, etc.. into the list
On already exists then query with itemID and increment the qty field
The cart you are displaying is available in cart-info tbody so in that case make sure you have an unique ID in row(tr)
Ex: <tr id=item-101><td>1</td><td>Mobile</td></tr>
Finally update the text of the respective id with your updated quantity

Get selected drop-down value of a row in html table using JavaScript/jQuery

I have a html table with 4 columns and multiple rows
column1 : simple text
column2 : simple text
column3 : select list with 2 values
column4 : Button that performs some operation
At run time, I want to get the selected / entered values for all the columns of that row against which column4 button is clicked. I know a little of JavaScript/jQuery.
Here is the static table code
<table id="invoiceTbl" border="1">
<thead>
<tr>
<th>Broker info</th>
<th>Receivable Amount</th>
<<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
And I am populating table i.e. inserting data on AJAX call like this:
$.ajax({
type: "POST",
data: $('#searchDetails').serialize(),
async: false,
cache: false,
url: "/opsadmin/search.json",
dataType: 'json',
success: function (result) {
var i = 1;
$.each(result, function (index, value) {
alert(index + ": " + value.brokerInfo);
$('table#invoiceTbl TBODY').append('<tr> <td>' + i + '</td><td>' + value.brokerInfo + '</td><td>' + value.receivableAmount + '</td><td><select name="act" id="s"><option>PENDING</option><option>CLEARED</option></select></td><td><input type="button" value="Process" onclick="updateStatus(\'' + index + '\')"</input></td></tr>');
i++;
});
}
});
return false;
First set the unique ID to each of your "select" with help of index like:
'<select name="act" id="s'+ index +'">'
and pass the index with "updateStatus(index)" function call.
function updateStatus(index) {
$('#s'+index).val(); // value of selected box.
}
$("#invoiceTbl input[type=button]").click(function(e){
$(e.target).closest("tr").find("td").slice(0,2).each(function(){
console.log($(this).text());
});
});
On #button click you will get an array (arr) that holds the values of the clicked row cells:
$('#button').on('click', function() {
var arr = [];
$(this).closest('tr').find('td').each(function() {
var that = $(this);
if (that.find('input[type="text"]').length > 0) {
arr.push(that.find('input[type="text"]').val());
} else if (that.find('select').length > 0) {
arr.push(that.find('select').val());
} else {
arr.push(that.text());
}
});
alert(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>text</td>
<td>text2</td>
<td>
<select>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
<option value="opt3">opt3</option>
</select>
</td>
<td><button id="button">Click</button></td>
</tr>
</tbody>
</table>
There's already a few good answers, but my solution is a bit different:
$("#invoiceTbl tr").each(function(){
var select = $(this).find("select");
var button = $(this).find("button");
button.click(function(){
alert(select.val());
});
});
If you also want the content of the other columns, that's a bit more difficult:
$("#invoiceTbl tr").each(function(){
var tr = $(this);
var button = $(this).find("button");
button.click(function(){
tr.find("td").each(function(){
var select = $(this).find("select");
var td_button = $(this).find("button");
if(!td_button.length)
{
if(select.length)
console.log(select.val());
else
console.log($(this).text());
}
});
});
});
Check out https://jsfiddle.net/cgfjewoe/ to see it run.

javascript - Table row not created after second change of text input

This is my HTML code:
<table id="display_table"><tr>
<td>No. of Questions: </td>
<td><input type="text" id="questions_num"></td>
</tr><tr>
<td>No. of Options: </td>
<td><input type="text" id="options_num"></td>
</tr></table>
I want to make it such that when the user enters x in the text input (whose id is options_num), x rows will be created. For each new row that is created, there should be a left column and a right column. The left column will contain the "Option" + somenumber, where somenumber refers to the row that has been created, and the right column will create a text input.
This is what I have tried in my JS:
document.getElementById("options_num").onkeyup = function() {
var options_num = parseInt(document.getElementById("options_num").value);
var display_text = '<tr><td>No. of Questions: </td><td><input type="text" id="questions_num"></td></tr><tr><td>No. of Options: </td><td><input type="text" id="options_num"></td></tr>'
for(var i = 1; i <= options_num; i++) {
display_text += "<tr><td>Option " + i + ": </td><td>" + "<input type='text' id='option_" + i + "'</td></tr>";
}
document.getElementById("display_table").innerHTML = display_text;
document.getElementById("options_num").value = options_num.toString();
document.getElementById("options_num").focus();
}
And it works when I first enter a value into the text input (whose id is question_num), but when I change the value, it does not work (it does not do anything). Demo.
So how do I get my JS code to work?
The reason it doesn't work after the first time, is that innerHTML actually destroys event binding. So after you modify table.innerHTML browser completely rebuilds new DOM elements without original onkeyup event listener attached.
I would recommend to change HTML a little, it will make everything simpler:
<table id="display_table">
<tbody>
<tr>
<td>No. of Questions:</td>
<td><input type="text" id="questions_num"/></td>
</tr>
<tr>
<td>No. of Options:</td>
<td><input type="text" id="options_num"/></td>
</tr>
</tbody>
<tbody id="rows"></tbody> <!-- append generated HTML here -->
</table>
and modified JS:
document.getElementById("options_num").onkeyup = function () {
var options = document.getElementById("options_num"),
optionsNum = parseInt(options.value),
tbody = document.getElementById("rows"),
rows = '';
for (var i = 1; i <= optionsNum; i++) {
rows += "<tr><td>Option " + i + "</td><td>" + "<input type='text' id='option_" + i + "'</td></tr>";
}
tbody.innerHTML = rows;
options.focus();
}
So the idea is to put table rows into tbody and it makes easy adding new and replacing replacing old rows.
Demo: http://jsfiddle.net/8yYyW/2/

Get the Checked and Unchecked table data via jquery

I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});

Categories

Resources