I have a formfield with a static row for an invoice position. With + and - buttons I can add or remove additional rows for invoice positions dynamically. This works fine, but within each row I have a have a selectbox that switches the calculation method for the row (from km- to hour- or misc-based). This last feature only works for the first static row, not for the added rows?
HTML
<form action="" method="post">
<div class="mb-3">
<div id="position_0" class="row align-items-start">
<div class="col-4">
<label for="description" class="form-label">Beschreibung</label>
<textarea class="form-control" id="description_0" name="description_0" rows="1"></textarea>
</div>
<div class="col-2">
<label for="date" class="form-label">Tag der Leistung</label>
<input type="text" class="form-control" id="date_0" name="date_0">
</div>
<div class="col-1">
<label for="amount" class="form-label">Menge</label>
<input type="text" class="form-control" id="amount_0" name="amount_0">
</div>
<div class="col-2">
<label for="type" class="form-label">Abrechnungsform</label>
<select class="form-select" id="type_0" name="type_0">
<option value="km" selected>Kilometer</option>
<option value="hours">Stunden</option>
<option value="misc">Sonstiges</option>
</select>
</div>
<div class="col-1">
<label for="price" class="form-label">Einzelpreis</label>
<input type="text" class="form-control" id="price_0" name="price_0" value="{{price_km}}">
</div>
<div class="col-2">
<label for="sum" class="form-label">Summe</label>
<input type="text" class="form-control" id="sum_0" name="sum_0">
</div>
</div>
</div>
<div id="multiple"></div>
<button type="submit" class="btn btn-primary float-start">Speichern</button>
</form>
<button class="btn btn-primary float-end" onclick="addItems()"><i class="bi bi-plus"></i></button>
<button class="btn btn-primary float-end" onclick="removeItems()"><i class="bi bi-dash"></i></button>
Javascript/JQuery
<script>
var formatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
});
var km = 0.97;
var hours = 12;
var misc = 0;
// THIS DOES NOT WORK START
$("#multiple").each(function () {
var n = $(this).find("div.mb-3").length;
$('#type_' + n).on('change', function () {
if (this.value === 'km') {
$('#price_' + n).val(formatter.format(km));
} else if (this.value === 'hours') {
$('#price_' + n).val(formatter.format(hours));
} else if (this.value === 'misc') {
$('#price_' + n).val(formatter.format(misc));
}
});
});
// THIS DOES NOT WORK END
function addItems() {
$("#multiple").each(function () {
var i = $(this).find("div.col").length;
var n = (i / 6) + 1;
$(this).append(`<div class="mb-3">
<div id="position_` + n + `" class="row align-items-start">
<div class="col col-4">
<textarea class="form-control" id="description_` + n + `" name="description_` + n + `" rows="1"></textarea>
</div>
<div class="col col-2">
<input type="text" class="form-control" id="date_` + n + `" name="date_` + n + `">
</div>
<div class="col col-1">
<input type="text" class="form-control" id="amount_` + n + `" name="amount_` + n + `">
</div>
<div class="col col-2">
<select class="form-select" id="type_` + n + `" name="type_` + n + `">
<option value="km" selected>Kilometer</option>
<option value="hours">Stunden</option>
<option value="misc">Sonstiges</option>
</select>
</div>
<div class="col col-1">
<input type="text" class="form-control" id="price_` + n + `" name="price_` + n + `" value="{{price_km}}">
</div>
<div class="col col-2">
<input type="text" class="form-control" id="sum_` + n + `" name="sum_` + n + `">
</div>
</div>
</div>`);
});
}
function removeItems() {
$("#multiple").each(function () {
var n = $(this).find("div.mb-3").length;
if (n != 0) {
$("#position_" + n).parents("div.mb-3").remove();
}
});
}
</script>
Only the initial items are "wired" the change event because you run
// this line loops only on the initial items
$("#multiple").each(function () {
To solve this you have to set an .on(event) function
// this is NOT a complete example
// 1. add a generic class to all the selects
<select class="form-select mytypeselect" id="type_0" name="type_0">
<option value="km" selected>Kilometer</option>
<option value="hours">Stunden</option>
<option value="misc">Sonstiges</option>
</select>
// 2. Set the on event, but all thing relative to the element (not fixed to the index or id
$('.mytypeselect').on('change', function () {
var self = $(this);
var row = self.closest(".row"); // find the row the select belongs at
if (self.val() === 'km') {
// find the input inside the row to change
row.find('.mypriceinput').val(formatter.format(km));
This is not optimal, but it solves my problem
// First row of the invoice
$('select#type_0').on('change', function () {
if ($(this).val() === 'km') {
$(this).parents('div').find('#price_0').val(formatter.format(km));
} else if ($(this).val() === 'hours') {
$(this).parents('div').find('#price_0').val(formatter.format(hours));
} else if ($(this).val() === 'misc') {
$(this).parents('div').find('#price_0').val(formatter.format(misc));
}
});
// Everytime the DOM changes
$("#multiple").bind("DOMSubtreeModified", function () {
$('.mytypeselect').on('change', function () {
var sibling = $(this).parents('div');
var n = (($(this).attr('id')).split('_'))[1];
if ($(this).val() === 'km') {
sibling.find('#price_' + n).val(formatter.format(km));
} else if ($(this).val() === 'hours') {
sibling.find('#price_' + n).val(formatter.format(hours));
} else if ($(this).val() === 'misc') {
sibling.find('#price_' + n).val(formatter.format(misc));
}
});
});
Related
I have an ajax function that is actually working well but I don't know how to use it on the HTML.
What I need to achieve is that basically, attached to each checkbox there is a certain number of questions. They're all selected by default but, if I deselect one of them, the number of questions of that particular checkbox should be removed.
The function I am using is working fine (in the console) but I couldn't find a way to use it on the HTML.
I post some code for more clarity.
let subjectId;
$("#selection").on("change", function () {
const selectSubjBtn = document.getElementById("select_subject");
subjectId = $(this).children(":selected").val();
let labelText = gettext(
"Select the number of questions by moving the button to the right or left!"
);
let title = gettext("Select Number of Questions");
let selectedQuestionsNum;
$.ajax({
type: "GET",
url: "/quiz/ajax_questions/" + subjectId,
success: function (response) {
let questions = response.questions;
let topics = response.topics;
let topicQuestionNum = response.question_num_list;
if (topicQuestionNum != 0) {
let topicsObj = topics.map(function (e, i) {
return [e, topicQuestionNum[i]];
});
let subTopicHtml;
// $("#sub_topic_box").append(
// '<input class="form-check-input mt-0 ms-3" type="checkbox" value="" id="selectAll" checked aria-label="Checkbox for following text input">'
// );
topicsObj.forEach((el) => {
subTopicHtml = '<div class="row mt-3">';
subTopicHtml += '<div class="input-group mb-3">';
subTopicHtml += '<div class="input-group-text">';
subTopicHtml +=
'<input class="form-check-input selectedTopic mt-0" type="checkbox" value="' +
el[1] +
'" id="' +
el[0].id +
'" checked aria-label="Checkbox for following text input">';
subTopicHtml += "</div>";
subTopicHtml +=
'<input value="' +
el[0].name +
'" type="text" class="form-control" aria-label="Text input with checkbox" disabled>';
subTopicHtml +=
'<span class="input-group-text">' + el[1] + "</span>";
subTopicHtml += "</div></div>";
$("#sub_topic_box").append(subTopicHtml);
});
$("#selectAll").click(function () {
if (this.checked) {
$(":checkbox").each(function () {
this.checked = true;
});
} else {
$(":checkbox").each(function () {
this.checked = false;
});
}
});
let selectedQuestionTopic =
document.getElementsByClassName("selectedTopic");
let selectedCheckboxes = [];
let selectedBoxesNum;
function selectedTopics() {
selectedCheckboxes = [];
let checked = document.querySelectorAll(
"[type='checkbox']:checked"
);
checked.forEach(function (el) {
selectedCheckboxes.push(Number(el.value));
selectedBoxesNum = selectedCheckboxes.reduce(
(pv, cv) => pv + cv,
0
);
});
console.log(selectedBoxesNum);
return selectedBoxesNum;
}
selectedQuestionTopic.forEach(function (el) {
el.addEventListener("change", function () {
selectedTopics();
});
});
quizBox.innerHTML = `
<div class="h5 mb-3">${title}</div>
<div class="row mt-3">
<label for="customRange1" class="form-label">${labelText}</label>
<div class="input-group">
<input type="text" class="form-control" id="textInput" value="${selectedQuestionsNum}" oninput="${selectedQuestionsNum};" >
<span class="input-group-text">on ${
questions.length
}</span>
<input type="range" name="question_number" class="form-range mt-3" min="0" max="${
questions.length
}" value="${
questions.length
}" id="customRange1" onchange="updateTextInput(this.value);"
oninput="updateTextInput(this.value);">
<div class="mt-3">
<button class="btn btn-primary" id="select_subject">${gettext(
"Select Subject"
)}</button>
</div>
</div>
</div>
`;
} else {
quizBox.innerHTML = `
<div class="h5 mb-3">${title}</div>
<div class="row mt-3">
<label for="customRange1" class="form-label">${labelText}</label>
<div class="input-group">
<input type="text" class="form-control" id="textInput" value="${
questions.length
}" oninput="customRange1.value=amount.value" >
<span class="input-group-text">on ${
questions.length
}</span>
<input type="range" name="question_number" class="form-range mt-3" min="0" max="${
questions.length
}" value="${
questions.length
}" id="customRange1" onchange="updateTextInput(this.value);"
oninput="updateTextInput(this.value);">
<div class="mt-3">
<button class="btn btn-primary" id="select_subject">${gettext(
"Select Subject"
)}</button>
</div>
</div>
</div>
`;
}
},
error: function (error) {
console.log(error);
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Basically, topicQuestionNum variable is an array, which I sum in the selectedTopics function and, in case I uncheck one of the checkboxes, it gives me a new result.
What I need to do, is updating also the result in the input field I create with the ajax request down below.
I tried in many different ways but I don't have much experience, especially with Javascript.
I've created a form with a dynamically generated radio button group, 2 checkboxes and 3 text input fields and I'm having a hard time finding a solution to how to total up these fields using JQuery. I either get nothing, NaN or two or more values to concatenate. I've tried more examples I've found on the internet than I can count. Could someone please tell me what I'm doing wrong?
Html
<div id="campaignPackageList" class="campaign-package-list form-group">
<input class="form-check-input" id="campaign_package" name="campaign_package" type="radio" data-packageid="1" data-package="business_dominators_pkg" value="23988" required="">
</div>
<div id="creativeNeeds" class="form-group">
<label class="required">What are the client's creative needs?</label>
<div class="form-check">
<input class="form-check-input" id="creative_image_set" name="creative_image_set" type="checkbox" value="300.00">
<label class="form-check-label" for="creative_image_set">Creative: 5 Image Ad Set Designed by Landmarks - $300.00</label>
</div>
<div class="form-check">
<input class="form-check-input" id="microsite_landingpage" name="microsite_landingpage" type="checkbox" value="800.00">
<label class="form-check-label" for="microsite_landingpage">Micro Site/Landing Page Designed by Landmarks - $800.00</label>
</div>
</div>
<div class="form-group w-25">
<label class="required" for="setup_fee">Setup Fee (Per Individual Campaign)</label>
<input class="form-control" id="setup_fee" name="setup_fee" type="number" value="300.00" readonly="">
</div>
<div id="depositAmountDiv" class="form-group w-25">
<label class="required" for="deposit_amount">Deposit Amount</label>
<input class="form-control " id="deposit_amount" name="deposit_amount" type="number" value="" required="">
</div>
<div id="monthlyImpressionCostDiv" class="form-group w-25">
<label class="required" for="monthly_impressions_cost">Monthly Impression Cost</label>
<input class="form-control " id="monthly_impressions_cost" name="monthly_impressions_cost" type="number" value="" required="">
</div>
<div class="form-group mb-3 w-25">
<label>Campaign Total Amount</label>
<div id="campaign_total_amount"><span>300</span></div>
</div>
JavaScript
let totalPrice = 0;
let packagePrice = 0;
let creativeImageSetPrice = 0;
let micrositeLandingPagePrice = 0;
let setupFee = 0;
let depositAmount = 0;
let monthlyImpressionCost = 0;
$('#campaignPackageList').on('click', 'input[name=campaign_package]', function() {
if ($(this).is(':checked')) {
packagePrice = parseFloat($(this).val());
}
});
console.log(packagePrice);
let $creativeNeedsDiv = $('#creativeNeeds');
$creativeNeedsDiv.on('change', 'input[name=creative_image_set]', function() {
if ($(this).val()) {
creativeImageSetPrice = parseFloat($(this).val());
}
});
$creativeNeedsDiv.on('change', 'input[name=microsite_landingpage]', function() {
if ($(this).val()) {
micrositeLandingPagePrice = parseFloat($(this).val());
}
});
setupFee = parseFloat($('#setup_fee').val());
$('#depositAmountDiv').on('change', 'input[name=deposit_amount]', function() {
if ($(this).val()) {
depositAmount = parseFloat($(this).val());
}
});
$('#monthlyImpressionCostDiv').on('change', 'input[name=monthly_impression_cost]', function() {
if ($(this).val()) {
monthlyImpressionCost = parseFloat($(this).val());
}
});
totalPrice = packagePrice +
creativeImageSetPrice +
micrositeLandingPagePrice +
setupFee +
depositAmount +
monthlyImpressionCost;
$('#campaign_total_amount span').text(totalPrice);
For numeric inputs, I used the input event instead of the change event.
$('#monthlyImpressionCostDiv').on('input', 'input[name=monthly_impressions_cost]', function() {
if ($(this).val().length > 0) {
monthlyImpressionCost = parseFloat($(this).val());
}
else
monthlyImpressionCost = 0;
cal();
});
And I put a value calculation function that is called with every change
function cal()
{
totalPrice = packagePrice + creativeImageSetPrice +
micrositeLandingPagePrice + setupFee + depositAmount +
monthlyImpressionCost;
$('#campaign_total_amount span').text(totalPrice);
}
Full code
let totalPrice = 0;
let packagePrice = 0;
let creativeImageSetPrice = 0;
let micrositeLandingPagePrice = 0;
let setupFee = 0;
let depositAmount = 0;
let monthlyImpressionCost = 0;
$('#campaignPackageList').on('click', 'input[name=campaign_package]', function() {
if ($(this).is(':checked')) {
packagePrice = parseFloat($(this).val());
}
else
packagePrice = 0;
cal();
});
//console.log(packagePrice);
let $creativeNeedsDiv = $('#creativeNeeds');
$creativeNeedsDiv.on('change', 'input[name=creative_image_set]', function() {
if ($(this).is(':checked')) {
creativeImageSetPrice = parseFloat($(this).val());
}
else
creativeImageSetPrice = 0;
cal();
});
$creativeNeedsDiv.on('change', 'input[name=microsite_landingpage]', function() {
if ($(this).is(':checked')) {
micrositeLandingPagePrice = parseFloat($(this).val());
}
else
micrositeLandingPagePrice = 0;
cal();
});
setupFee = parseFloat($('#setup_fee').val());
$('#depositAmountDiv').on('input', 'input[name=deposit_amount]', function() {
if ($(this).val().length > 0) {
depositAmount = parseFloat($(this).val());
}
else
depositAmount = 0;
cal();
});
$('#monthlyImpressionCostDiv').on('input', 'input[name=monthly_impressions_cost]', function() {
if ($(this).val().length > 0) {
monthlyImpressionCost = parseFloat($(this).val());
}
else
monthlyImpressionCost = 0;
cal();
});
function cal()
{
totalPrice = packagePrice +
creativeImageSetPrice +
micrositeLandingPagePrice +
setupFee +
depositAmount +
monthlyImpressionCost;
$('#campaign_total_amount span').text(totalPrice);
}
<div id="campaignPackageList" class="campaign-package-list form-group">
<input class="form-check-input" id="campaign_package" name="campaign_package" type="radio" data-packageid="1" data-package="business_dominators_pkg" value="23988" required="">campaign package
<input class="form-check-input" id="campaign_package" name="campaign_package" type="radio" data-packageid="1" data-package="business_dominators_pkg" value="0" required="">no campaign package
</div>
<div id="creativeNeeds" class="form-group">
<label class="required">What are the client's creative needs?</label>
<div class="form-check">
<input class="form-check-input" id="creative_image_set" name="creative_image_set" type="checkbox" value="300.00">
<label class="form-check-label" for="creative_image_set">Creative: 5 Image Ad Set Designed by Landmarks - $300.00</label>
</div>
<div class="form-check">
<input class="form-check-input" id="microsite_landingpage" name="microsite_landingpage" type="checkbox" value="800.00">
<label class="form-check-label" for="microsite_landingpage">Micro Site/Landing Page Designed by Landmarks - $800.00</label>
</div>
</div>
<div class="form-group w-25">
<label class="required" for="setup_fee">Setup Fee (Per Individual Campaign)</label>
<input class="form-control" id="setup_fee" name="setup_fee" type="number" value="300.00" readonly="">
</div>
<div id="depositAmountDiv" class="form-group w-25">
<label class="required" for="deposit_amount">Deposit Amount</label>
<input class="form-control " id="deposit_amount" name="deposit_amount" type="number" value="" required="">
</div>
<div id="monthlyImpressionCostDiv" class="form-group w-25">
<label class="required" for="monthly_impressions_cost">Monthly Impression Cost</label>
<input class="form-control " id="monthly_impressions_cost" name="monthly_impressions_cost" type="number" value="" required="">
</div>
<div class="form-group mb-3 w-25">
<label>Campaign Total Amount</label>
<div id="campaign_total_amount"><span style="font-size:14px;color:green;">300</span></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
I am cloning four field (sl no,stationery type ,quantity, Remove ) of a form by using java script.I can very well append or remove these field
I am not able to generate the serial no on the first column and if I delete any row in between this should also adjust the serial no.How can i achieve this My code is below
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
$(document).on('keypress', '.number_only', function(e) {
return isNumbers(e, this);
});
function isNumbers(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<br />
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;>
<div class=" row ">
<div class="col-md-4 ">
</div>
<div class="col-sm-12 ">
<h4 align="center "><b><u>Add Stationery Stock<b></u></h4>
<br />
<form method="post " id="insert_form ">
<div class="col-sm-6 ">
<input type="text " name="Order No. " class="form-control " placeholder="Order NO "/>
</div>
<div class="col-sm-6 ">
<input type="date " name="Date " class="form-control " placeholder="Date " />
</div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center "><b><u>Stationery Details<b></u></h4>
<div> </div>
<div class="table-repsonsive ">
<span id="error "></span>
<table class="table table-bordered " id="item_table ">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button " name="add " class="btn btn-success btn-sm add "><span class="glyphicon glyphicon-plus "></span></button></th>
</tr>
</table>
<div align="center ">
<input type="submit " name="submit " class="btn btn-info "style="margin-bottom:20px " value="Insert " />
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Using
html += '<td><input type="text" name="item_name[]" class="form-control item_name"></td>';
you can do
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
when needed
I fixed your invalid HTML (u and b not correctly closed and a missing quote on the first inline style)
I ALSO remove the name="submit" - you never want to have name="submit" on a form you plan to submit using script
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
$(function() {
$("#item_table").on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
renum()
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
renum()
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;">
<div class="row">
<div class="col-md-4"></div>
<div class="col-sm-12">
<h4 align="center"><b><u>Add Stationery Stock</u></b></h4>
<form method="post" id="insert_form">
<div class="col-sm-6"><input type="text" name="Order No." class="form-control" placeholder="Order NO " /></div>
<div class="col-sm-6"><input type="date" name="Date" class="form-control" placeholder="Date" /></div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center"><b><u>Stationery Details</u></b></h4>
<div> </div>
<div class="table-repsonsive"><span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center"><input type="submit" class="btn btn-info" style="margin-bottom:20px" value="Insert" /></div>
</div>
</form>
</div>
</div>
</div>
I am working on Billing System, where i have a dropdown which consist of lot of items and a textbox in front of it, which is a price of that item.
I am calling new dropdown and textbox each time using add button.
var i = 1;
var j = 11;
$(".btnAdd").click(function() {
i += 1;
j += 1;
$('#myDiv').after('<div class="row"><div class="col"><select id="' + i + '" style="width: 130px"><option value="val1">a</option><option value="val2">b</option><option value="val3">c</option><option value="valn">z</option></select><input type="text" id="' + j + '" /> </div></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv" class="row">
<div class="col">
<select id=" 1 " style='width: 130px'>
<option value='val1'>a</option>
<option value='val2'>b</option>
<option value='val3'>c</option>
<option value='valn'>z</option>
</select>
<input type="text" id=" 11 " name="txt" />
</div>
</div>
<button class="btnAdd">Add</button>
<div>
<input type="text" id=" totval " name="txt" />
<button class="Submit">Total</button>
</div>
My question is how to add all the values when the TOTAL button is clicked and store in TOTAL textbox ? Please help me in this ..
CHECK THIS FIDDLE -> https://fiddle.jshell.net/e20hc1wo/2/
Try this Fiddle
var i = 1;
var j = 11;
$(".btnAdd").click(function() {
i += 1;
j += 1;
$('#myDiv').after('<div class="row"><div class="col"><select id="' + i + '" style="width: 130px"><option value="val1">a</option><option value="val2">b</option><option value="val3">c</option><option value="valn">z</option></select><input type="text" id="' + j + '" /> </div></div>');
});
$('.Submit').on('click', function() {
var total = 0;
$('input[type=text]').not('#totval').each(function(index, item) {
total += parseInt($(item).val());
});
$('#totval').val(total);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="myDiv" class="row">
<div class="col">
<select id=" 1 " style='width: 130px'>
<option value='val1'>a</option>
<option value='val2'>b</option>
<option value='val3'>c</option>
<option value='valn'>z</option>
</select>
<input type="text" id=" 11 " name="txt" />
</div>
</div>
<button class="btnAdd">Add</button>
<div>
<input type="text" id="totval" name="txt" />
<button class="Submit">Total</button>
</div>
Implementing the sum is possible:
$(".Submit").click(function () {
var total = 0;
$("input:not(#totval)").each(function (_, e) {
total += parseInt(e.value, 10)
});
$("#totval").val(total);
});
Fiddle: https://fiddle.jshell.net/e20hc1wo/12/
But I think the code can be improved a lot if you add meaningful classes to these inputs created.
Improved: The following implementation uses a template row to avoid concatenating HTML code in JS.
<div class="row template">
<div class="col">
<select class="typeSelect" style='width: 130px'>
<option value='val1'>a</option>
<option value='val2'>b</option>
<option value='val3'>c</option>
<option value='valn'>z</option>
</select>
<input type="text" class="numberInput" />
</div>
</div>
<button class="btnAdd">Add</button>
<div>
<input type="text" id="totval" name="txt" />
<button class="Submit">Total</button>
</div>
JS:
var template = $(".template").remove();
$(".btnAdd").click(function () {
template.clone(true).insertBefore('.btnAdd');
}).click();
$(".Submit").click(function () {
var total = 0;
$(".numberInput").each(function (_, e) {
total += parseInt(e.value, 10)
});
$("#totval").val(total);
});
It is much shorter and cleaner
Fiddle: https://fiddle.jshell.net/e20hc1wo/23/
Add id to button
<button class= "Submit" id="btnTotal">Total</button>
Add function to javascript
$("#btnTotal").click(function () {
var total = 0;
$(".row input").each(function(){
total += parseInt($(this).val(),10);
})
$('#totval').val(total);
});
html code
<div class="control-group">
<label class="control-label-m">Product Name :</label>
<div class="controls-m">
<input id="input1tray040" class="span10 " type="text">
</div>
</div>
<div class="control-group">
<label class="control-label-m">Available Qty :</label>
<div class="controls-m">
<input id="input2tray040" class="span10 " type="text">
</div>
</div>
<div class="control-group">
<label class="control-label-m">Total Inward :</label>
<div class="controls-m">
<input id="input3tray040" class="span10 " type="text">
</div>
</div>
<div class="control-group">
<label class="control-label-m">Total Sales :</label>
<div class="controls-m">
<input id="input4tray040" class="span10 " type="text">
</div>
</div>
Jquery
I am able to assign id to my input textbox ,but my problem is that i need to assign a value to the specified input text box while creating this div, How to achieve this.My jquery code what i have tried so far
$table.find('input[type="text"]').attr('id', function () {
var idval = 'input' + ($(this).parent().parent().index() + 1) + $(this).closest('td').attr('id');
return idval;
});
var foo = 'input' + ($(this).parent().parent().index() + 1) + $(this).closest('td').attr('id');
var bar = foo.split("input")[1];
$tdid = $(this).closest('td').attr('id');
var mapid = '1' + $tdid + '';
var addid = '3' + $tdid + '';
var editid = '2' + $tdid + '';
if (bar == addid) {
$("#" + foo + "").val(data.product_name);
} else if (bar == mapid) {
// $("#"+foo+"").val(data.map_name);
} else if (bar == editid) {
$("#" + foo + "").val(data.edit_val);
}