Jquery not looping inside parent loop - html

I have a jquery code that clones a "selector" wherein it is a parent of many other elements.
EDIT : I added the function that calls the "cloneMore". It supposed to be called when the user clicks the button inside the row and creates another row below it.
EDIT 2 : I added the table that the <tr> belongs to. I tried to run it without the <tr> <td> tags and the function works! But sadly it removes it from the html table. Why does this happen?
jquery snippet
$(document).on('click', '.add-form-row', function(e){
alert("Button Click!");
e.preventDefault();
cloneMore('.form-row.spacer:last', 'form');
return false;
function cloneMore(selector, prefix) {
var newElement = $(selector).clone(true);
newElement.find('input[type=text]').each(function() { //loops through the textfields
console.log("print1");
});
newElement.each(function () {
console.log("print2");
});
html code
<div class="display_table">
<table class="table table-hover table-striped">
<thead class="thead-dark">
<tr class="tablerow">
<th scope="col">Item</th>
<th scope="col">Item Description</th>
<th scope="col">Quantity</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
{{ formset.management_form }}
{% for form in formset %}
<div class="row form-row spacer">
<tr scope="row">
<div class="input-group">
<td><input type="text" name="form-0-item" class="form-control" id="id_form-0-item" value="" readonly="readonly"></td>
<td><input type="text" name="form-0-description" class="form-control" id="id_form-0-description" value="" readonly="readonly"></td>
<td><input type="text" name="form-0-quantity" class="form-control" id="id_form-0-quantity" value="" readonly="readonly"></td>
<div class="input-group-append"><td><button class="btn btn-success add-form-row">+</button></td></div>
</div>
</tr>
</div>
{% endfor %}
</tbody>
</table>
</div>
However, it doesn't even pass through the loop even once and I don't get a "print" in the console. I'm sure that there is a text field inside the parent. In this case its the div with class "row form-row spacer"
Is there something wrong with my syntax? I've seen somewhere where they get the parent through a selector but in my case I put it in a variable. Is there anything wrong or any work around this?

I think I kind of figured it out. I was trying to select the <input> tags even without referencing the <td> and <tr> tags. So jquery didn't know what I was trying to select. So after I made some changes in the whole table and the jquery script, it works just as I intended it would. However, any suggestions on how I could improve this code will be appreciated! I'm putting this up in case someone needs it.
Also, I forgot to credit to this Stack Overflow answer for the snippets.
html code
<table class="table table-hover table-striped" id="part_table">
<thead class="thead-dark">
<tr class="tablehead">
<th scope="col">Item</th>
<th scope="col">Item Description</th>
<th scope="col">Quantity</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
{{ formset.management_form }}
{% for form in formset %}
<div class="row form-row">
<tr class="tablerow">
<td><input type="text" name="form-0-item" class="form-control" id="id_form-0-item" value="" readonly="readonly"></td>
<td><input type="text" name="form-0-description" class="form-control" id="id_form-0-description" value="" readonly="readonly"></td>
<td><input type="text" name="form-0-quantity" class="form-control" id="id_form-0-quantity" value="" readonly="readonly"></td>
<td><button class="btn btn-success add-form-row">+</button></td>
</tr>
</div>
{% endfor %}
</tbody>
</table>
jquery snippet
<script type="text/javascript">
function cloneMore(prefix) {
var lastrowtbl = $('#part_table tr.tablerow:last').clone(true);
var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
var currentnum = total - 1
lastrowtbl.find('input[type=text]').each(function (i, el) {
console.log(this);
var name = $(this).attr('name');
if(name) {
name = name.replace('-' + currentnum + '-', '-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name' : name, 'id' : id}).val('').removeAttr('checked');
}
});
total++;
$('#id_' + prefix + '_TOTAL_FORMS').val(total);
$('#part_table tr.tablerow:last').after(lastrowtbl);
var conditionRow = $('#part_table tr.tablerow:not(:last)');
conditionRow.find('.btn.add-form-row')
.removeClass('btn-success').addClass('btn-danger')
.removeClass('add-form-row').addClass('remove-form-row')
.html('-');
return false;
}
$(document).on('click', '.add-form-row', function(e){
alert("Button Click!");
e.preventDefault();
cloneMore('form');
return false;
});
</script>

Related

Unable to fetch data in request.form in flask

I am using flask as the backend and i have my html template as
<div id="tablediv">
<form action="{{ url_for('useraction') }}" method="post">
<table class="table" id="displaytable">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Address</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{%for i in range(0, len)%}
<tr>
<td id="username" name = "username">{{unverifieduser[i][1]}}</td>
<td id="useremail" name="useremail">{{unverifieduser[i][2]}}</td>
<td id="useraddress" name="useraddress">{{unverifieduser[i][3]}}</td>
<td >
<button type="submit" class="btn btn-danger" id="delete" name="delete">Delete</button>
<button type="submit" class="btn btn-warning" id="verify" name="verify">Verify</button>
</td>
</tr>
{%endfor%}
</tbody>
</table>
</form>
</div>
My API call looks like
#app.route('/useraction', methods = ['GET', 'POST'])
def useraction():
print(request.form)
if request.method =='POST':
cursor = mysql.connection.cursor()
cursor.execute('SELECT * FROM user where isVerified = false');
user = cursor.fetchall()
return render_template('user.html', len = len(user), unverifieduser = user)
The output gives only the button which i click for example 'verify'
enter image description here
Is there any html attribute I am missing to get all the elements of the table for example username, useremail, useraddress
An HTML table or HTML table elements are not Form elements. In HTML, only Form elements are sent along with such a POST request. Here is an overview of all HTML Form elements. Note that these elements should be inside a form element, which is in your case the following line:
<form action="{{ url_for('useraction') }}" method="post">
As for why you only have verify in your form: the sole other input element in your form is the delete button, with its type set to submit. While you can have multiple submit buttons, only the one you click is sent along with the form.

Laravel add row to table without refreshing page

I'm trying to add row to the table without refreshing page is it possible without using js? Basically I have a table and input in the modal my problem is that I need to refresh the page whenever I'm adding data to table which closes modal and data from the table has to be saved only when pressing save button in the modal. Maybe it is possible to do that using Laravel Controllers?
<table class="table" style="margin-top: 16px">
<tbody>
<tr>
<td class="table-text">
<div style="float: left">TASK NAME</div>
</td>
<td style="width: 10%">
<div style="float: end">DELETE</div>
</td>
</tr>
</tbody>
This is not possible without javascript.
Assuming you are using jquery, I would do something like this:
$('form').on('submit', function(e) {
e.preventDefault(); // Disable the sending of the form
var one = $('#one').val();
var two = $('#two').val();
$('#one').val('');
$('#two').val('');
$.ajax({
url: "/api/products/add",
method: 'post',
data: {
product: one,
price: two
},
success: function(){
appendToTable(one, two);
}
});
appendToTable(one, two); // The Success function in this ajax would never reach, because the url is not set. Thats because the function is called here.
});
function appendToTable(one, two) {
$('table').append(`
<tr>
<td>${one}</td>
<td>${two}</td>
</tr>
`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/api/products/add" method="post">
<input id="one" name="product" type="text" placeholder="product" required>
<input id="two" name="price" type="number" placeholder="price" required>
<button>Add</button>
</form>
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>PC</td>
<td>500</td>
</tr>
</table>
You disable the forms default behavior (submitting) and do the nessesarry work with js (or jquery). If the user hover disables js, the form submits as normal and sends the data.

Buttons in JSP Table

I have JSP page with a table:
<table class="table table-hover">
<tbody>
<thead class="thead-light">
<th scope="col">#</th>
<th scope="col">Number</th>
<th scope="col">Tariff</th>
<th scope="col">Cost</th>
<th scope="col">Action</th>
</thead>
<tbody>
<c:forEach items="${contractsList}" var="contract" varStatus="loop">
<thead>
<th scope="col">${loop.index + 1}</th>
<th>${contract.number}</th>
<th>${contract.tariffName}</th>
<th>TODO</th>
<th><input type="submit" value="Block"></th>
</thead>
</c:forEach>
</tbody>
</table>
How can I make a button in each row send POST request with data from this row? For example, I'm pressing a button in row #2 and it sends post request to some url with number of contract from this row as a request parameter. I tried adding <form> tag but it ruins formatting of the table and for me it's not clear how to pass contract's number as a request parameter in this case.
UPDATE: I did it this way
<tr onclick="showContract('${contract.contractId}')" style="cursor: pointer;">
<script>
function showContract(id) {
var form = document.createElement('form');
document.body.appendChild(form);
form.method = 'post';
form.action = '/client/show_contract';
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'contractId';
input.value = id;
form.appendChild(input);
form.submit();
}
</script>
Easiest way is to put your form tag inside the loop.
<c:forEach items="${contractsList}" var="contract" varStatus="loop">
<form action="..YourServlet" method="post">
<thead>
<th scope="col">${loop.index + 1}</th>
<th>${contract.number}</th>
<th>${contract.tariffName}</th>
<th>TODO</th>
<th><input type="submit" value="Block"></th>
</thead>
<input type="hidden" name="cnumber" value="${contract.number}"/>
<input type="hidden" name="ctarrif" value="${contract.tarrifName}"/>
</form>
</c:forEach>
Then in your servlet just get parameters like you would normally do:
String contractNumber = request.getParameter ("cname");
String tarrifName = request.getParameter ("ctarrif");

how to bind dynamic generated inputs to $scope

I am retrieving items from db put them in dir-paginate or ng-repeat what i am trying here to pass id in as model name to get key and name also as key as i am fetching a array to create many inputs and retrieve them in controller, but when i retrieve ng-model object values with console.log($scope.values); it says undefined.
how i will pass multiple generated inputs to controller in scope object is my question even ng-click dont work ??
view
<form angular-validator-submit="submitForm()"
name="submit-form" class="form-horizontal" novalidate
angular-validator>
<table>
<thead>
<tr>
<th>S.No</th>
<th>id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="x in items| itemsPerPage: pageSize" current-page="currentPage">
<td><input type="text" name="id" ng-model="values.{{x.id}}[$index]"></td>
<td><input type="text" name="test" ng-model="values.{{x.name}}[$index]"></td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary">Save</button>
</form>
$scope.submitform = function(){
console.log($scope.values);
}
ng-model="values[x.id]" will do the work and define $scope.values = []; as suggested in comments.

Initial data is not loading to the input field when ui-mask is added

I have the below table,
<table class="me-checkbox-table">
<thead>
<th class="checkbox-column">
<md-checkbox md-no-ink aria-label="Check all"></md-checkbox>
</th>
<th>sku#</th>
<th class="item-name-column">item name</th>
<th class="id-column">qty</th>
<th>price</th>
<th>sale price</th>
</thead>
<tbody>
<tr ng-repeat="inventory in inventoryList">
<td class="checkbox-row">
<md-checkbox md-no-ink aria-label="Check one item"></md-checkbox>
</td>
<td ng-model="inventory.sku">{{inventory.sku}}</td>
<td>{{inventory.name}}</td>
<td><input type="text" name="quantity" ng-pattern="/[0-9]+/" ui-mask="999" ng-model="inventory.quantity" />
</td>
<span class="error" ng-show="allItems.quantity.$error.minlength"></span>
<td><input type="number" ng-model="inventory.price" /></td>
<td class="sale-yes"><input type="number" ng-model="inventory.discount" /></td>
</tr>
</tbody>
</table>
I get data from backend using controller and below is my controller,
inventoryService.getInventoryList()
.success(function (result) {
$scope.inventoryList = result;
console.log("result "+result[0]);
}).error(function (error) {
alert("Inventory Loading Error : " + error);
})
the value for Quantity is loading when I do not add ui-mask in the input field but When I do, it won't load data to the Quantity field. Please help
I just created sample of mine on top of yours and here is what I found:
<div ng-app="MyApp">
<div ng-controller="Controller">
{{ quantity }}
<input type="text" name="quantity" ng-pattern="/[0-9]+/" ui-mask="999" ng-model="quantity" />
</div>
</div>
When I assign values from 0 to 99, ui-mask rejects it and I see empty input.
angular.module('MyApp', ['ui.mask'])
.controller('Controller', function($scope) {
$scope.quantity = 70;
});
When I assign values from 100 to 999 it works properly:
angular.module('MyApp', ['ui.mask'])
.controller('Controller', function($scope) {
$scope.quantity = 544;
});