jquery shopping cart value onchange - javascript

I wrote a code for a shopping cart. In that for each change in quantity value (either increasing or decreasing) there should be a change in the price. I tried to implement this for a decreasing price with respect to the quantity. I can change the quantity but I am not able to change the price field because the price still gives me the type of object as I console.log. Can anyone point out what I am doing wrong?
Below is the code:
product.html
<tr>
<td class="product-thumbnail">
<img src="images/cloth_1.jpg" alt="Image" class="img-fluid">
</td>
<td class="product-name">
<h2 class="h5 text-black">Top Up T-Shirt</h2>
</td>
<!-- The price -->
<td>$49.00</td>
<td>
<div class="input-group mb-3" style="max-width: 120px;">
<div class="input-group-prepend">
<button class="btn btn-outline-primary js-btn-minus" type="button">−</button>
</div>
<input type="text" class="form-control text-center" value="1" placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
<div class="input-group-append">
<button class="btn btn-outline-primary js-btn-plus" type="button">&plus;</button>
</div>
</div>
</td>
<td>
<div class="price"></div>
</td>
<td>X</td>
</tr>
<tr>
<td class="product-thumbnail">
<img src="images/cloth_2.jpg" alt="Image" class="img-fluid">
</td>
<td class="product-name">
<h2 class="h5 text-black ">Polo Shirt</h2>
</td>
<td>$49.00</td>
<td>
<div class="input-group mb-3" style="max-width: 120px;">
<div class="input-group-prepend">
<button class="btn btn-outline-primary js-btn-minus" type="button">−</button>
</div>
<input type="text" class="form-control text-center" value="1" placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
<div class="input-group-append">
<button class="btn btn-outline-primary js-btn-plus" type="button">&plus;</button>
</div>
</div>
</td>
<td>
<div class="price">8</div>
</td>
<td>X</td>
</tr>
main.js
<script>
$('.js-btn-minus').on('click', function(e)
{
e.preventDefault();
if ( $(this).closest('.input-group').find('.form-control').val() !=0 && $(this).closest('.input-group').find('.form-control').val() >0)
{
$(this).closest('.input-group').find('.form-control').val(parseInt($(this).closest('.input-group').find('.form-control').val()) - 1);
var va = parseInt($(this).closest('.input-group').find('.form-control').val());
va = (parseInt(va));
this.a = va;
console.log(this.a);
var price = $(this).closest('tr').find('.price');
console.log(price.val(parseInt(this.a)));
}
}
</script>

use price.html or price.text instead of price.val and then remember, input get value by .val() but other element get by .html() or .text()

First thing is that your table is not well structured. Second thing is that your requirement is not exactly clear to me.
Thought I assume you want to increase or decrease the price where the class is price.
You are receiving the whole element as you are using val() and it is always going to be the object.
If you could tell the exact issue/requirement, I can help you out.
$('.js-btn-minus').on('click', function(e)
{
e.preventDefault();
var next_val = parseInt($(this).closest('.input-group').find('.form-control').val()) - 1;
if (next_val < 0){
next_val = 0
$(this).closest('.input-group').find('.form-control').val(0)
}
else{
$(this).closest('.input-group').find('.form-control').val(next_val);
var existing_value = $(this).closest('tr').find('.price').html()
if ((existing_value || '') == ''){
$(this).closest('tr').find('.price').html(next_val)
}
else{
$(this).closest('tr').find('.price').html(existing_value - 1)
}
}
// Price updates
//var current_price = parseInt($(this).closest('.input-group').parent().prev('td').html().replace('$', ''))
//var final_price = current_price - next_val;
});
$('.js-btn-plus').on('click', function(e)
{
e.preventDefault();
var next_val = parseInt($(this).closest('.input-group').find('.form-control').val()) + 1;
if (next_val < 0){
next_val=0;
$(this).closest('.input-group').find('.form-control').val(0)
}
else{
$(this).closest('.input-group').find('.form-control').val(next_val);
var existing_value = parseInt($(this).closest('tr').find('.price').html())
if ((existing_value || '') == ''){
$(this).closest('tr').find('.price').html(next_val)
}
else{
$(this).closest('tr').find('.price').html(existing_value + 1)
}
}
// Price updates
//var current_price = parseInt($(this).closest('.input-group').parent().prev('td').html().replace('$', ''))
//var final_price = current_price + 1
//console.log(final_price)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="product-thumbnail">
<img src="images/cloth_1.jpg" alt="Image" class="img-fluid">
</td>
<td class="product-name">
<h2 class="h5 text-black">Top Up T-Shirt</h2>
</td>
<!-- The price -->
<td class="current_price">$49.00</td>
<td>
<div class="input-group mb-3" style="max-width: 120px;">
<div class="input-group-prepend">
<button class="btn btn-outline-primary js-btn-minus" type="button">−</button>
</div>
<input type="text" class="form-control text-center" value="1" placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
<div class="input-group-append">
<button class="btn btn-outline-primary js-btn-plus" type="button">&plus;</button>
</div>
</div>
</td>
<td>
<div class="price"></div>
</td>
<td>X</td>
</tr>
<tr>
<td class="product-thumbnail">
<img src="images/cloth_2.jpg" alt="Image" class="img-fluid">
</td>
<td class="product-name">
<h2 class="h5 text-black ">Polo Shirt</h2>
</td>
<td class="current_price">$49.00</td>
<td>
<div class="input-group mb-3" style="max-width: 120px;">
<div class="input-group-prepend">
<button class="btn btn-outline-primary js-btn-minus" type="button">−</button>
</div>
<input type="text" class="form-control text-center" value="1" placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
<div class="input-group-append">
<button class="btn btn-outline-primary js-btn-plus" type="button">&plus;</button>
</div>
</div>
</td>
<td>
<div class="price">8</div>
</td>
<td>X</td>
</tr>
</table>

Related

How to update values for each columns of row from modal?

I have an HTML code like this:
<body>
<div class="container">
<div style="margin-top: 50px;">
<table class="table table-hover" style="width: 100%;">
<tbody>
<tr>
<th>0</th>
<td class="cTenSanPham">Samsung Galaxy Note 8</td>
<td class="cGiaSanPham">23.000.000 VND</td>
<td>
<button type="button" class="btn btn-primary edit" data-toggle="modal" data-target="#exampleModal" onclick="editProductModal()">Chỉnh sửa</button>
<button type="button" class="btn btn-danger delete-row-tb">Xóa</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
In modal code
<div class="modal-body">
<form>
<div class="form-group">
<label>
<h5 class="">Mã sản phẩm</h5>
</label>
<input type="text" class="form-control" id="iMaSanPham" name="nMaSanPham" readonly>
</div>
<div class="form-group">
<label>
<h5 class="">Tên sản phẩm</h5>
</label>
<input type="text" class="form-control" id="iTenSanPham" name="nTenSanPham">
</div>
<div class="form-group">
<label>
<h5 class="">Giá sản phẩm</h5>
</label>
<input type="number" min="500" max="999999999" class="form-control" id="iGiaSanPham"
name="nGiaSanPham">
</div>
</form>
</div>
And an Javascript code like this:
function editProductModal() {
$(document).on("click", ".edit", function () {
$(this).parents("tr").find("th").each(function () {
document.getElementById("iMaSanPham").value = $(this).text();
});
$(this).parents("tr").find(".cTenSanPham").each(function () {
document.getElementById("iTenSanPham").value = $(this).text();
});
$(this).parents("tr").find(".cGiaSanPham").each(function () {
document.getElementById("iGiaSanPham").value = parseInt($(this).text().replace(/\D/g, ''));
});
});
}
I want when I click the button 'Chỉnh sửa' on any row, a modal will open and fill data from this row into this modal (the modal of bootstrap 4). I can edit on this modal, then I press a button to pass updated data to table. How to do it in function editProductModal() in file JS. Thank you so much
var $currentEditRow;
$(document).on("click", ".edit", function() {
$currentEditRow = $(this).parents("tr");
editProductModal($(this).parents("tr"));
});
function editProductModal(row) {
document.getElementById("iMaSanPham").value = $(row).find("th").text();
document.getElementById("iTenSanPham").value = $(row).find(".cTenSanPham").text();
document.getElementById("iGiaSanPham").value = parseInt($(row).find(".cGiaSanPham").text().replace(/\D/g, ''));
}
function update() {
$currentEditRow.find("th").text(document.getElementById("iMaSanPham").value);
$currentEditRow.find(".cTenSanPham").text(document.getElementById("iTenSanPham").value);
$currentEditRow.find(".cGiaSanPham").text(document.getElementById("iGiaSanPham").value);
$('#exampleModal').modal('hide');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<div class="container">
<div style="margin-top: 50px;">
<table class="table table-hover" style="width: 100%;">
<tbody>
<tr>
<th>0</th>
<td class="cTenSanPham">Samsung Galaxy Note 8</td>
<td class="cGiaSanPham">23.000.000 VND</td>
<td>
<button type="button" class="btn btn-primary edit" data-toggle="modal" data-target="#exampleModal" onclick="editProductModal()">Chỉnh sửa</button>
<button type="button" class="btn btn-danger delete-row-tb">Xóa</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label>
<h5 class="">Mã sản phẩm</h5>
</label>
<input type="text" class="form-control" id="iMaSanPham" name="nMaSanPham" readonly>
</div>
<div class="form-group">
<label>
<h5 class="">Tên sản phẩm</h5>
</label>
<input type="text" class="form-control" id="iTenSanPham" name="nTenSanPham">
</div>
<div class="form-group">
<label>
<h5 class="">Giá sản phẩm</h5>
</label>
<input type="number" min="500" max="999999999" class="form-control" id="iGiaSanPham" name="nGiaSanPham">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="update()">Save</button>
</div>
</div>
</div>
</div>
When editing the current tr row, store the dom of the current row, so you can determine which line to update to in the modal.
You can try to update the row data in my code snippet.
You are improperly mixing inline onclick and jQuery click event listeners together.
Remove the function and the onclick and just use the jQuery code inside the function by itself to manage the event
You also don't need an each loop to access the elements within the row.
Simplified version:
$(document).on("click", ".edit", function() {
var $row = $(this).closest('tr'),
thText = $row.find('th').text(),
cTenSanPham = $row.find('.cTenSanPham').text(),
cGiaSanPham = $('.cGiaSanPham').text().replace(/\D/g, '');
$('#iMaSanPham').val(thText);
$('#iTenSanPham').val(cTenSanPham);
$('#iGiaSanPham').val(cGiaSanPham);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div style="margin-top: 50px;">
<table class="table table-hover" style="width: 100%;">
<tbody>
<tr>
<th>0</th>
<td class="cTenSanPham">Samsung Galaxy Note 8</td>
<td class="cGiaSanPham">23.000.000 VND</td>
<td>
<button type="button" class="btn btn-primary edit" data-toggle="modal" data-target="#exampleModal">Chỉnh sửa</button>
<button type="button" class="btn btn-danger delete-row-tb">Xóa</button>
</td>
</tr>
<tr>
<th>66</th>
<td class="cTenSanPham">Another Item</td>
<td class="cGiaSanPham">99.000.000 VND</td>
<td>
<button type="button" class="btn btn-primary edit" data-toggle="modal" data-target="#exampleModal">Chỉnh sửa</button>
<button type="button" class="btn btn-danger delete-row-tb">Xóa</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<h3>Modal</h3>
<div class="modal-body">
<form>
<div class="form-group">
<label>
<h5 class="">Mã sản phẩm</h5>
</label>
<input type="text" class="form-control" id="iMaSanPham" name="nMaSanPham" readonly>
</div>
<div class="form-group">
<label>
<h5 class="">Tên sản phẩm</h5>
</label>
<input type="text" class="form-control" id="iTenSanPham" name="nTenSanPham">
</div>
<div class="form-group">
<label>
<h5 class="">Giá sản phẩm</h5>
</label>
<input type="number" min="500" max="999999999" class="form-control" id="iGiaSanPham" name="nGiaSanPham">
</div>
</form>
</div>

How to save the data in local storage?

I want to use the local storage option where the data is displayed on the screen even when the page is refreshed.
As in when a row gets added using the addRow(), then i refresh the page, i need to see the table with the added Row data as well.
I want to use javascript as i am new to javascript i need a bit of help. i was able to do the edit and delete option on my own. But i need help in using local storage.
let addRow = () => {
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
let email = document.getElementById("email").value;
let contact = document.getElementById("number").value;
if(name === ""){
alert('Please Fill Your Full Name');
document.getElementById("name").focus();
return false;
}
if(age === ""){
alert('Please Fill Your Age');
document.getElementById("age").focus();
return false;
}
if(email === ""){
alert('Please Fill Your Email');
document.getElementById("email").focus();
return false;
}
if(contact === ""){
alert('Please Fill Your Mobile Number');
document.getElementById("number").focus();
return false;
}
let tr=document.createElement('tr');
tr.innerHTML=`
<td>${name}</td>
<td>${age}</td>
<td>${email}</td>
<td>${contact}</td>
<td>
<button type="button" class="btn btn-warning" id="editBtn"> Edit </button>
<button type="button" class="btn btn-danger" id="deleteBtn"> Delete </button>
</td>`
document.getElementById("tableDisplay").appendChild(tr);
document.getElementById("name").value = '';
document.getElementById("age").value = '';
document.getElementById("email").value = '';
document.getElementById("number").value = '';
document.getElementById("tableDisplay").value = '';
};
document.getElementById("tableDisplay").addEventListener("click", (event) => {
if (event.target.matches("#deleteBtn")) {
let row = event.target.closest("tr");
row.remove();
}
});
document.getElementById("tableDisplay").addEventListener("click", (event) => {
if (event.target.matches("#editBtn")) {
let row = event.target.closest("tr");
row.setAttribute("contenteditable", "true");
alert("Click on the text you want to edit!");
row.cells[4].innerHTML = `<button type="button" class="btn btn-primary" id="saveBtn"> Save </button>`;
}
});
document.getElementById("tableDisplay").addEventListener("click", (event) => {
if (event.target.matches("#saveBtn")) {
let row = event.target.closest("tr");
row.setAttribute("contenteditable", "false");
alert("Row data changed!");
row.cells[4].innerHTML = `
<button type="button" class="btn btn-warning" id="editBtn"> Edit </button>
<button type="button" class="btn btn-danger" id="deleteBtn"> Delete </button>`;
}
});
document.getElementById("done").addEventListener("click", addRow);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="border border-dark rounded p-1 bg-light">
<table class="text-center table" align="center" id="tableDisplay">
<tr class="bg-warning">
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Contact Number</th>
<th></th>
</tr>
<tr>
<td>John</td>
<td>26</td>
<td>foresto#worksmail.tk</td>
<td>+917007984498</td>
<td>
<button type="button" class="btn btn-warning" id="editBtn"> Edit </button>
<button type="button" class="btn btn-danger" id="deleteBtn"> Delete</button>
</td>
</tr>
<tr>
<td>Jimmy</td>
<td>45</td>
<td>foresto#official-sunveno.ru</td>
<td>+917007985598</td>
<td>
<button type="button" class="btn btn-warning" id="editBtn"> Edit </button>
<button type="button" class="btn btn-danger" id="deleteBtn"> Delete</button>
</td>
</tr>
<tr>
<td>Sarah</td>
<td>32</td>
<td>foresto#abac-compressoren.ru</td>
<td>+917897984498</td>
<td>
<button type="button" class="btn btn-warning" id="editBtn"> Edit </button>
<button type="button" class="btn btn-danger" id="deleteBtn"> Delete</button>
</td>
</tr>
<tr>
<td>Vanessa</td>
<td>22</td>
<td>foresto#newmotionrp.ru</td>
<td>+917078984498</td>
<td>
<button type="button" class="btn btn-warning" id="editBtn"> Edit </button>
<button type="button" class="btn btn-danger" id="deleteBtn"> Delete</button>
</td>
</tr>
</table>
</div>
<div class="border border-dark rounded bg-warning p-3 mt-5">
<form>
<div class="form-group row">
<label for="name" class="col-md-2 col-form-label">Name</label>
<div class="col-md-10">
<input class="form-control" type="text" placeholder="Full Name" id="name">
</div>
</div>
<div class="form-group row">
<label for="number" class="col-md-2 col-form-label">Age</label>
<div class="col-md-10">
<input class="form-control" type="number" placeholder="Age" id="age">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-2 col-form-label">Email</label>
<div class="col-md-10">
<input class="form-control" type="email" placeholder="emailaddress#example.com" id="email">
</div>
</div>
<div class="form-group row">
<label for="number" class="col-md-2 col-form-label">Contact Number</label>
<div class="col-md-10">
<input class="form-control" type="text" placeholder="Call On" id="number">
</div>
</div>
</form>
<button class="btn btn-primary btn-block" id="done">ADD</button>
</div>
There is a little bit of an issue with your HTML. You have multiple elements with the same id: e.g.
id="editBtn" & id="deleteBtn".
Also, you have five columns in the th, but only 4 in the rows. I edited the HTML and the JS a bit, so that it looks like it will delete the rows. The way that you had it is was appending the row after the tbody, but you want that before the tbody, so I added an id to tbody, but you could handle that another way.
window.delRow = function(element)
is there because Fiddle apparently wraps the functions in a function so that there was a problem calling that. Not really a complete answer, but I hope that helps. You would have to see what browser support there is for:
element.closest('tr').remove();
I changed the HTML to this:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div class="border border-dark rounded p-1 bg-light">
<table class="text-center table" align="center" id="tableDisplay">
<thead class="bg-warning">
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Contact Number</th>
<th></th>
</tr>
</thead>
<tbody id = "tabelBody">
<tr>
<td>1</td>
<td>Hello</td>
<td>2</td>
<td>2</td>
<td>
<button type="button" class="btn btn-warning editBtn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<button type="button" class="btn btn-danger deleteBtn" onclick="delRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></button>
</td>
</tr>
<tr>
<td>2</td>
<td>Hello</td>
<td>2</td>
<td>2</td>
<td>
<button type="button" class="btn btn-warning editBtn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<button type="button" class="btn btn-danger deleteBtn" onclick="delRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></button>
</td>
</tr>
<tr>
<td>3</td>
<td>Hello</td>
<td>2</td>
<td>2</td>
<td>
<button type="button" class="btn btn-warning editBtn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<button type="button" class="btn btn-danger deleteBtn" onclick="delRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="border border-dark rounded bg-warning p-3 mt-5">
<form>
<div class="form-group row">
<label for="name" class="col-md-2 col-form-label">Name</label>
<div class="col-md-10">
<input class="form-control" type="text" placeholder="Full Name" id="name">
</div>
</div>
<div class="form-group row">
<label for="number" class="col-md-2 col-form-label">Age</label>
<div class="col-md-10">
<input class="form-control" type="number" placeholder="Age" id="age">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-2 col-form-label">Email</label>
<div class="col-md-10">
<input class="form-control" type="email" placeholder="emailaddress#example.com" id="email">
</div>
</div>
<div class="form-group row">
<label for="number" class="col-md-2 col-form-label">Contact Number</label>
<div class="col-md-10">
<input class="form-control" type="text" placeholder="Call On" id="number">
</div>
</div>
</form>
<button class="btn btn-primary btn-block" id="done">ADD</button>
</div>
and the JS to this:
let addRow = () => {
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
let email = document.getElementById("email").value;
let contact = document.getElementById("number").value;
let tr=document.createElement('tr');
tr.innerHTML=`
<td>${name}</td>
<td>${age}</td>
<td>${email}</td>
<td>${contact}</td>
<td>
<button type="button" class="btn btn-warning editBtn"><i class="fa fa-pencil" aria-hidden="true"></i></button>
<button type="button" class="btn btn-danger deleteBtn" onclick="delRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></button>
</td>`
document.getElementById("tabelBody").appendChild(tr);
document.getElementById("name").value = '';
document.getElementById("age").value = '';
document.getElementById("email").value = '';
document.getElementById("number").value = '';
document.getElementById("tableDisplay").value = '';
};
window.delRow = function(element) {
alert("test");
element.closest('tr').remove();
}
document.getElementById("done").addEventListener("click", addRow);
Not sure exactly what you wanted to do when editing.
There is apparently a Fiddle setting regarding wrapping of JS.

multi ng -repeat and remove rows in angular js

I'm new to AngularJs and I'm stuck in multi ng-repeat.
HTML CODE
<table class="table table-bordered tdPaddingNull verTop">
<thead>
<tr>
<th width="200px">Product Details </th>
<th width="250px">Current Availability</th>
<th width="200px">Batch </th>
<th>Quantity</th>
<th>Rate INR </th>
<th>Amt. INR</th>
<th>Converted Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(i,product) in listproducts track by $index">
<td style="padding: 7px;">
<input auto-complete ui-items="prductdetail" ng-model="formData.product_name[i]" class="form-control form-white" my-id="{{i}}"/>
<input id="product_id{{i}}" placeholder="productid" type="hidden" value="" ng-model="formData.product_id[i]" my-id="{{i}}"/>
<a ng-click="addProductBatch()" title="Add Another Batch Quantity" style="float:right;"><i class="fa fa-plus" aria-hidden="true"></i> ADD BATCH </a>
</td>
<td class="line-item-column item-currentavail transferorder-lineitem">
<div class="row text-muted font-sm">
<div class="col-md-6">
Source Stock
</div>
<div class="separationline col-md-6">
Destination Stock
</div>
</div>
<div class="row font-xs">
<div class="col-md-6">
0.00 Units
</div>
<div class="separationline col-md-6">
0.00 Units
</div>
</div>
</td>
<td style="padding: 7px;">
<div style="display:inline-block;width:100%;" ng-repeat="addBatch in listAddbatches">
<select class="form-control form-white selectNor" ng-model="formData.batch_id[i]" ng-change="changedBatchValue(formData.batch_id)" style="margin-bottom: 5px;width: 88%;float: left;">
<option value="">Select Batch</option>
<option value="{{blist.batch_id}}" ng-repeat="blist in batchList">{{blist.batch_number}}</option>
</select>
<a class="inputTabel1" ng-click="removeBatch($index)" title="Remove Batch" style="float:left;margin-left: 4px;"> <i class="fa fa-times-circle-o" aria-hidden="true" ></i>
</a>
</div>
</td>
<td style="padding: 7px;">
<input class="form-control form-white" type="text" value="" ng-model="formData.product_count[i]" ng-repeat="addBatch in listAddbatches" style="margin-bottom: 5px;"/>
</td>
<td style="padding: 7px;">
<input class="form-control form-white " placeholder="Selling Price" type="text" value="0.00" ng-model="formData.sel_inr_rate[i]">
</td>
<td>
<input class="form-control form-white form-Tabel" placeholder="Amount in INR" type="text" value="0.00" ng-model="formData.sel_inr_amount[i]" readonly />
</td>
<td class="Amount ">
<input class="form-control form-white form-Tabel" placeholder="" type="text" value="0.00" ng-model="formData.exc_total_amount[i]" readonly />
<button class="inputTabel" ng-click="removeProduct($index)"> <i class="fa fa-times-circle-o" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
ANGULAR CODE
/****************ADD ANOTHER BATCH QUANTITY**************/
$scope.addAnotherProduct = function(listproducts,$event) {
newItemNo = $scope.listproducts.length+1;
$scope.listproducts.push({'batch_id[newItemNo]':'','product_count[newItemNo]':''});
};
$scope.removeProduct = function(index) {
/*var lastItem = $scope.listproducts.length-1;
$scope.listproducts.splice(lastItem);
$scope.listAddbatches = '';*/
$scope.listproducts.splice(index,1);
};
$scope.removeBatch = function(index) {
/*var lastItem = $scope.listAddbatches.length-1;
$scope.listAddbatches.splice(lastItem);
$scope.listAddbatches = '';*/
$scope.listAddbatches.splice(index,1);
};
$scope.addProductBatch = function() {
var newItemNo = $scope.listAddbatches.length+1;
$scope.listAddbatches.push({'id':'batch'+newItemNo});
};
Here when I click ADD ANOTHER PRODUCT it should create an entire row in the table without the columns of Batch and Quantity, but now it's appearing as it in before row created.
Then when I click ADD BATCH it should create under the table column Batch and Quantity of the corresponding row, but now it's adding in all the rows and when I remove added batch, it should remove the corresponding batch, but now it's removing the last added batch.
The same happens when I remove added product (Entire Row), it should remove the corresponding row of the product but now it's removing lastly added Product row.
How can I fix all the aforementioned issues?
Please help me
There are multiple issues with your approach:
1) You are using a global array listAddbatches but you want to add the batches by product, so why shouldn't you use product.listAddbatches array?
2) When using track by $index you will not able to delete correct element from array or object since compiler directive is not re-compiling the element when its data attribute changes.
3) Using array length to generate id like var newItemNo = $scope.listAddbatches.length + 1; is not a good idea since the array length could change (when removing items) in a way that you will have the same ids for different elements.
4) This line is very strange {'batch_id[newItemNo]':'','product_count[newItemNo]':''}, since you are calculating newItemNo, but this is a simple string 'batch_id[newItemNo]'. Why do you need this?
5) Do not recommend to use $index to remove items, since it could point to some other element in case of filtering.
Your code could like this (simplified version), hope this helps:
angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
$scope.listproducts = [];
$scope.addAnotherProduct = function(listproducts) {
listproducts.push( {
listAddbatches: []
});
};
$scope.removeProduct = function(product) {
var index = $scope.listproducts.indexOf(product);
if (index >= 0)
$scope.listproducts.splice(index, 1);
};
$scope.removeBatch = function(product, batch) {
var index = product.listAddbatches.indexOf(batch);
if (index >= 0)
product.listAddbatches.splice(index, 1);
};
$scope.addProductBatch = function(product) {
product.listAddbatches.push({ });
};
});
<script src="https://code.angularjs.org/1.6.4/angular.js" ></script>
<html ng-app="plunker">
<body ng-controller="MainCtrl">
<table class="table table-bordered tdPaddingNull verTop">
<thead>
<tr>
<th width="200px">Product Details </th>
<th width="250px">Current Availability</th>
<th width="200px">Batch </th>
<th>Quantity</th>
<th>Rate INR </th>
<th>Amt. INR</th>
<th>Converted Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(i, product) in listproducts">
<td style="padding: 7px;">
<input auto-complete ui-items="prductdetail" ng-model="formData.product_name[i]" class="form-control form-white" my-id="{{i}}"/>
<input id="product_id{{i}}" placeholder="productid" type="hidden" value="" ng-model="formData.product_id[i]" my-id="{{i}}"/>
<a ng-click="addProductBatch(product)" title="Add Another Batch Quantity" style="float:right;"><i class="fa fa-plus" aria-hidden="true"></i> ADD BATCH </a>
</td>
<td class="line-item-column item-currentavail transferorder-lineitem">
<div class="row text-muted font-sm">
<div class="col-md-6">
Source Stock
</div>
<div class="separationline col-md-6">
Destination Stock
</div>
</div>
<div class="row font-xs">
<div class="col-md-6">
0.00 Units
</div>
<div class="separationline col-md-6">
0.00 Units
</div>
</div>
</td>
<td style="padding: 7px;">
<div style="display:inline-block;width:100%;" ng-repeat="addBatch in product.listAddbatches">
<select class="form-control form-white selectNor" ng-model="formData.batch_id[i]" ng-change="changedBatchValue(formData.batch_id)" style="margin-bottom: 5px;width: 88%;float: left;">
<option value="">Select Batch</option>
<option value="{{blist.batch_id}}" ng-repeat="blist in batchList">{{blist.batch_number}}</option>
</select>
<a class="inputTabel1" ng-click="removeBatch(product, addBatch)" title="Remove Batch" style="float:left;margin-left: 4px;"> <i class="fa fa-times-circle-o" aria-hidden="true" ></i>
</a>
</div>
</td>
<td style="padding: 7px;">
<input class="form-control form-white" type="text" value="" ng-model="formData.product_count[i]" ng-repeat="addBatch in product.listAddbatches" style="margin-bottom: 5px;"/>
</td>
<td style="padding: 7px;">
<input class="form-control form-white " placeholder="Selling Price" type="text" value="0.00" ng-model="formData.sel_inr_rate[i]">
</td>
<td>
<input class="form-control form-white form-Tabel" placeholder="Amount in INR" type="text" value="0.00" ng-model="formData.sel_inr_amount[i]" readonly />
</td>
<td class="Amount ">
<input class="form-control form-white form-Tabel" placeholder="" type="text" value="0.00" ng-model="formData.exc_total_amount[i]" readonly />
<button class="inputTabel" ng-click="removeProduct(product)"> <i class="fa fa-times-circle-o" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
<button ng-click="addAnotherProduct(listproducts)">Add Another Product</button>
</body>
</html>

How can I pass a variable in mvc method used in jQuery code to call partial view?

I have a dropdown control in my view and if user select a option in dropdown button then I have to pass it to my jQuery code and pass to MVC method which is use in jQuery code to call partial view. I have attached my code image.
this is my working code
#{
ViewBag.Title = "CreateBidSecondStep";
}
<div id="container">
<div class="wrapper white-bg">
<div class="row mar-xsm-b">
<div class="col s12 l12 m12">
<div class="step">
<span class="pull-left">Step 1 ></span>
<span class="active pull-left">Step 2 ></span>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="row mar-sm-b">
<div class="col s12 m12 l12">
<form id="form1" name="form1" method="post" action="">
<div class="border-light">
<div class="heading24 mar-sm-l mar-sm-r">Bill of Material</div>
<div class="row">
<div class="col s8 m8 l8" id="billMaterial">
<div class="ProdHeading">Search</div>
<div class="pull-left">
<label class="label pull-left">Item Code</label>
<select class="browser-default pull-left width_120" name="itemcode" id="itemcode" enable>
<option>Item Code</option>
<option>Item Code</option>
<option>Item Code</option>
</select>
</div>
<div class="pull-left mar-lg-l">
<label class="label pull-left">Item Name</label>
<input type="text" class="pull-left" name="cap" />
</div>
<div class="pull-left mar-lg-l">
<button class="btn waves-effect waves-light" type="submit" name="action" id="btnsearch">Search</button>
</div>
<div class="clearfix"></div>
<div class="bdr-gray-b mar-sm-t mar-sm-b"></div>
<div class="pull-left">
<label class="label pull-left width_120">Total Item Quantity</label>
<input type="number" maxlength="5" class="pull-left width_80" name="cap" />
<div class="clearfix"></div>
<label class="label pull-left width_120">Item Quantity</label>
<input type="number" class="pull-left width_80" name="cap" />
<div class="clearfix"></div>
<label class="label pull-left width_120">Location</label>
<input type="text" class="pull-left width_80" name="cap" />
</div>
<div class="pull-left mar-lg-l">
<label>Description</label>
<div class="clearfix"></div>
<textarea></textarea>
</div>
<div class="pull-left mar-lg-l mar-md-t">
<button class="btn waves-effect waves-light" style="bottom:0px" type="submit" name="action">Add to BOM</button>
</div>
</div>
<div class="col s4 m4 l4">
<div class="table_h2" id="SAPdiv">
</div>
</div>
</div>
<div class="row">
<div class="col s12 l12 m12 ">
<div class="table_h2">
<table class="TableID2">
<thead>
<tr>
<th>Item Code</th>
<th>Description</th>
<th>Quantity</th>
<th>Approved Supplied</th>
</tr>
</thead>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="row border-light mar-sm-t pad-sm">
<div class="col s12 l12 m12">
<div class="pull-left">
</div>
<div class="pull-right">
<button class="btn waves-effect waves-light" type="submit" name="action">PREVIOUS</button>
<button class="btn waves-effect waves-light" type="submit" name="action">SEND TO ADVANCE PURCHASE</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script src=" ~/Scripts/JobManager/BiddingSecondStepPartial.js"></script>
<script type="text/javascript">
$(function () {
$('#btnsearch').click(function (data) {
var itemcode = $('#itemcode').value;
$.post("#Url.Action("SAPPartailView", "CreateBid")", function(data) {
if (data) {
$('#SAPdiv').append(data);
}
});
});
});
</script>
</div>
Try This one
$(function () {
$('#btnsearch').click(function (data) {
var itemcode = $('#itemcode').value;
$.post("/SAPPartailView/CreateBid", { itemcode : itemcode }, function(data) {
if (data) {
$('#SAPdiv').append(data);
}
});
});
});
});
i just got a solution ....thanks for giving your efforts.
this is the way by which i can call a partial view from my jquery code passing with a parameter..
<script type="text/javascript">
var url = '#Url.Action("SAPPartailView", "CreateBid")';
$('#btnsearch').click(function () {
var keyWord = $('#itemcodeid').val();
$('#SAPdiv').load(url, { searchText: keyWord });
})
and in partial view i have to take parameter like..
public PartialViewResult SAPPartailView(string searchText)
{
return PartialView("_CreateBidSecondStepSAP",newlist);
}
this is working solution

Why is my value getting appended to the hidden field instead of overwritten?

I have a simple filesector i have made (with links as the file names). When i click a filename the following javascript is run:
<script>
$(function () {
$(".fileSelect").click(function () {
var name = $(this).text(); //gets the name of the clicked file
var id = $(this).attr("id");// gets the id of the clicked file
$("#filehiddenid").val(id); // sets the file id, but wrongly appends
$("#fileDisplayText").val(name); //sets the display name
$("#mySelectFile").modal("hide"); //hides the modal file dialog
});
})
</script>
The value being set in the hidden field is the internal id of my file (database id), and the filename is for display.
My problem is that when i repeatedly select a new file, post the form and then selct and post then form etc. etc. Then the value from the file select is appended to the forms collection, so that when i post the form i get something like: 176, 178, 179,
as the values, instead of just 176 which is the latest value I have selected.
*edit: markup added *
This is the markup, please ignore the Razor variables, i named the id's of the input fields to match the javascript, in my code they are generated server side:
<div class="templateSetting">
<div>
<span>
<strong>
#setting.SettingData.Name
</strong>
</span> <br />
<span>#setting.SettingData.Description</span>
<input type="hidden" id="filehiddenid" name="setting_#setting.SettingData.Alias" value="#setting.Value" />
</div>
<div>
<div style="float: left; width: 40%;">
<input type="text" style="width:545px;" id="fileDisplayText" name="meta_setting_#setting.SettingData.Alias" value="#fileName" class="form-control" /></div>
<div style="width: 60%;">
Select File
</div>
<div class="templatealias">#setting.SettingData.Alias</div>
<div style="clear:both;"></div>
</div>
</div>
edit: This the entire markup, rendered:
<form action="/InteractiveApplications/EditApplication/23" id="editform" method="post" name="editform">
<section id="container">
<div id="wrapping" class="clearfix" style="padding-left:10px;width:100%;">
<div id="WorkContent">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul>
<li style="display:none"></li>
</ul>
</div>
<input data-val="true" data-val-number="The field CurrentFolderId must be a number." data-val-required="Feltet CurrentFolderId skal udfyldes." id="CurrentFolderId" name="CurrentFolderId" type="hidden" value="0">
<input data-val="true" data-val-number="The field ApplicationId must be a number." data-val-required="Feltet ApplicationId skal udfyldes." id="ApplicationId" name="ApplicationId" type="hidden" value="23">
<table style="width: 50%;padding-left: 20px;" class="tablelist">
<tbody>
<tr>
<td valign="top">
<table width="100%">
<tbody>
<tr>
<td style="width:120px;vertical-align:top;">
<label for="Name">Name</label>:
</td>
<td>
<input class="form-control" id="Name" name="Name" type="text" value="Afstemning">
</td>
</tr>
<tr>
<td style="width:120px;vertical-align:top;">
<label for="Description">Description</label>:
</td>
<td>
<textarea class="form-control" cols="20" id="Description" name="Description" rows="2">This is a poll to take when entering the library</textarea>
</td>
</tr>
<tr>
<td style="width:120px;vertical-align:top;">
<label for="Templates">Template</label>:
</td>
<td>
Simple Poll Template
</td>
</tr>
<tr>
<td style="width:120px;vertical-align:top;">
<label for="ApplicationData">Path</label>:
</td>
<td>
<input class="form-control" id="ApplicationData" name="ApplicationData" type="text" value="http://10.0.0.44:81/">
</td>
</tr>
<tr>
<td style="width:120px;vertical-align:top;">
<label for="BlockHostExit">Block host exit</label>:
</td>
<td>
<input checked="checked" data-val="true" data-val-required="Feltet Block host exit skal udfyldes." id="BlockHostExit" name="BlockHostExit" type="checkbox" value="true"><input name="BlockHostExit" type="hidden" value="false">
</td>
</tr>
</tbody>
</table>
</td>
<td valign="top" style="padding-left: 20px">
<img src="/InteractiveImages/689a492e-7e01-49cc-b0b3-57e23b621706.jpg" width="100%" style="text-align: center;max-width: 200px;"><br>
<input id="ImagePath" name="ImagePath" type="hidden" value="/InteractiveImages/689a492e-7e01-49cc-b0b3-57e23b621706.jpg"> <a style="color: gray" href="/InteractiveApplications/ChangePicture/23">
Change Picture
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<div class="titleBar" style="padding-left:-10px;height:30px;border-bottom:1px solid #307AAB">
<h2> Application configuration</h2>
</div>
<div style="padding: 10px">
<div>
<div id="templateSettings" class="templateSettings">
<div class="templateSetting">
<div class="templateSettingLeading">
<strong>
Submit Text
</strong><br>
This is the text for the submit button
</div>
<div class="templateSettingInput">
<div style="width:50%;float:left;"> <input type="text" name="setting_submittext" value="qwer" class="form-control"></div>
<div class="templatealias">submittext</div>
<div style="clear:both;"></div>
</div>
</div>
</div>
<div id="templateSettings" class="templateSettings">
<div class="templateSetting">
<div class="templateSettingLeading">
<strong>
Multiple choice
</strong><br>
This determines if the poll has multiple right answers
</div>
<div class="templateSettingInput">
<input type="hidden" id="setting_ismultiplechoice" name="setting_ismultiplechoice" value="off">
<input id="ismultiplechoice" type="checkbox" name="setting_ismultiplechoice">
<div class="templatealias">
ismultiplechoice
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#checkbox_ismultiplechoice").click(function () {
var settingId = "#setting_ismultiplechoice";
var currentVal = $(settingId).val();
if (currentVal == "off") {
$(settingId).val("on");
}
else {
$(settingId).val("off");
}
});
});
</script>
</div>
<div id="templateSettings" class="templateSettings">
<script type="text/javascript">
var answerCounter = 1;
var trueFalseCounter = 0;
$(document).ready(function () {
$("#addbutton").click(function () {
answerCounter += 1;
trueFalseCounter += 1;
$("#questioninput_question").append("<div id='answer_" + answerCounter + "'>Answer: <input type='text' name='setting_question:" + answerCounter + "' value='' class='form-control' /><input type='checkbox' name='answer_setting_question:" + answerCounter + "' />This is the correct answer <input type='button' value='Delete' class='deleteButton btn btn-warning btn-xs' id='deletebutton_" + answerCounter + "'/></div>");
});
$(".templateSettingInput").on("click", ".deleteButton", function () {
if(confirm("Are you sure you want to delete this answer?"))
{
$(this).parent().remove();
}
});
});
</script>
<div class="templateSetting">
<div class="templateSettingLeading">
<strong> Question</strong>
This is the question and the answers for the poll
</div>
<div class="templatealias">
question
</div>
<div class="templateSettingInput" id="questioninput_question" style="width:50%;">
<textarea cols="40" rows="4" name="setting_question" class="form-control">werwe</textarea>
<input style="vertical-align: top" type="button" id="addbutton" value="Add answer" class="addbutton btn btn-info btn-xs navbar-btn"><br>
<div id="answer_1">
Answer:
<input type="text" name="setting_question:1" value="wer" class="form-control">
<!--<input type='checkbox' name='answer_setting_question:1' />This
is the correct answer-->
<input type="button" value="Delete" id="deletebutton_1" class="deleteButton btn btn-warning btn-xs">
</div>
</div>
</div>
</div>
<div id="templateSettings" class="templateSettings">
<div class="templateSetting">
<div class="templateSettingLeading">
<strong>
Show Answer to user
</strong><br>
determines if the user should see answers
</div>
<div class="templateSettingInput">
<input type="hidden" id="setting_showanswer" name="setting_showanswer" value="off">
<input id="showanswer" checked="'checked'" type="checkbox" name="setting_showanswer">
<div class="templatealias">
showanswer
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#checkbox_showanswer").click(function () {
var settingId = "#setting_showanswer";
var currentVal = $(settingId).val();
if (currentVal == "off") {
$(settingId).val("on");
}
else {
$(settingId).val("off");
}
});
});
</script>
</div>
<div id="templateSettings" class="templateSettings">
<div class="templateSetting">
<div>
<span>
<strong>
Background
</strong>
</span> <br>
<span>Please select a background image</span>
<input type="hidden" id="id_background" name="setting_background" value="172,201,173,175,172,178,178,,">
</div>
<div>
<div style="float: left; width: 40%;"><input type="text" style="width:545px;" id="text_background" name="meta_setting_background" value="611a756c4c3d338fc4ffcebf8b1979d6.png" class="form-control"></div>
<div style="width: 60%;">
Select File
</div>
<div class="templatealias">background</div>
<div style="clear:both;"></div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="mySelectFile" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Select file</h4>
</div>
<div class="modal-body">
<div class="foldertree">
<ul>
<li id="0" class="folder">
All
<ul>
<li id="173" class="file">iStock_000032787140Large.jpg</li>
<li id="174" class="file">52_fordele.jpg</li>
<li id="175" class="file">11376047043_a06bed34bd_o.jpg</li>
<li id="177" class="file">DigitalSignage.png</li>
<li id="178" class="file">mediawall_search_br.jpg</li>
</ul>
</li>
<ul>
<li id="59" class="folder">
Test interactive folder
<ul>
<li id="172" class="file">611a756c4c3d338fc4ffcebf8b1979d6.png</li>
</ul>
</li>
</ul>
</ul>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<div class="templateSettingInput">
<input type="text" name="setting_background" value="172,201,173,175,172,178,178,," class="form-control">
<div class="templatealias">background sdhsdsd</div>
</div>
</div>
<script>
$(function () {
$(".fileSelect").click(function () {
var name = $(this).text();
var id = $(this).attr("id");
var elementId = 'id_background';
var elementText = 'text_background';
$("#" + elementId).val(id);
$("#" + elementText).val(name);
$("#mySelectFile").modal("hide");
});
})
</script>
</div>
</div>
</div>
</div>
</form>
Make sure there aren't other hidden inputs on the page with the same id and view the html in your browser and verify that the value on the element is correct before jquery modifies it.
The jquery id selector (http://api.jquery.com/id-selector/) will only select the first element in the DOM that has that id.
If there are multiple hidden input elements with the same name on the form, they will all get posted to the server.

Categories

Resources