multiple dynamic input onchange and onblur function javascript - javascript

I have multiple input that when you select the option, the stock and the price would come out on other input to be used for another function.
i've tried to add unique id's for the inputs added but i just cant seem to figure out how to apply the function to the added inputs.
here is the Html:
<div id="container1">
<div class="form-group row">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
#foreach ($stoks as $stok)
<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>
#endforeach
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
here is the javascript:
$(document).ready(function() {
var add_button = $("#add_button");
var inputs = document.getElementsByTagName('input');
var select = document.getElementById("produk_nama");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
var html = '<div class="form-group row">';
// select buah
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama'+i+'" name="produk_nama[]">';
html += '<option value="">Pilih Produk</option>';
html += '#foreach ($stoks as $stok)';
html += '<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>';
html += '#endforeach';
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok'+i+'" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga'+i+'" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah'+i+'" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal'+i+'" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
// clone entire div
// $("#container1")
// .append(
// $("#container1")
// .children(inputs)
// .first()
// .clone()
// )
});
// main input function
$('#produk_nama'+i).on('change', function(){
alert(i);
var hargaproduk = $('#produk_nama'+i+' option:selected').data('price');
var stok = $('#produk_nama'+i+' option:selected').data('stok');
$('#stok'+i).text('Stok '+stok);
$('#harga'+i).val(hargaproduk);
});
document.getElementById('jumlah'+i).addEventListener("blur", function(){
var jumlah = $('#jumlah'+i).val();
var harga = $('#harga'+i).val();
var subtotal = jumlah * harga;
$('#subtotal'+i).val(subtotal);
})
});
any help and explanation would be much appreciated, thank you

As your first select-box i.e :produk_nama is same for all divs you can use clone() method to get clone of that select instead of writing laravel code inside jquery code.
Then , you can use $(document).on("change", "select[name*=produk_nama]".. to capture all change event on select-box . Inside this you can use .closest() and .find() method to get required values from input you needed and add the value to required inputs.Same you can do for jumlah input .
Demo Code :
$(document).ready(function() {
var add_button = $("#add_button");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
//get first div > selct clone it
var slects = $('.outer:first').find("select").clone();
var html = '<div class="form-group row outer">';
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama' + i + '" name="produk_nama[]">';
html += $(slects).html(); //add that
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok' + i + '" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga' + i + '" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah' + i + '" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal' + i + '" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
});
//on change of selct
$(document).on("change", "select[name*=produk_nama]", function() {
//get attrs values
var hargaproduk = $(this).find("option:selected").attr('data-price');
var stok = $(this).find("option:selected").attr('data-stok');
//add the values to required elemnt
$(this).closest(".outer").find(".d-block span").text('Stok ' + stok)
$(this).closest(".outer").find("input[name*=harga]").val(hargaproduk);
});
$(document).on("blur", "input[name*=jumlah]", function() {
var jumlah = $(this).val(); //get value
var harga = $(this).closest(".outer").find("input[name*=harga]").val();
var subtotal = jumlah * harga;
//add value to subtotal
$(this).closest(".outer").find("input[name=subtotal]").val(subtotal);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container1">
<!--just added outer class-->
<div class="form-group row outer">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
<option data-stok="something" data-price="12" value="1">1</option>
<option data-stok="something" data-price="13" value="2">2</option>
<option data-stok="something" data-price="14" value="3">3</option>
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
<button id="add_button">Add more</button>

Related

By click of the button the same form is added under that form but how can i get the value of the number of times it getting printed &store it in table

by click of the button the same form is added under that form but how can i get the value of the number of times it getting printed &store it in table. How can I insert the data into table if the user add more experiences from model. On the click of the button the value in the value field should increment too and how can I enter if the user add any number of experiences so how can I enter the data in the table. I am inserting this data in table in row wise fashion in table
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<input type="hidden" name="1experience" id="1experience" value="<?php $i = 1; ?>">
<div class="form-group">
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience['status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience['status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
</div>
<script>
function addexperience(){
var i = $('#1experience').val();
i++;
$('#addexperience').append('<div class="col-md-3"> <label>Status</label> <select class="form-control" name="status'+i+'">'+
'<option value="">Select</option>'+
'<option value="Current">Current</option>'+
'<option value="Past">Past</option> </select> </div>'+
'<div class="col-md-3">'+
'<label>Designation</label>'+
'<input type="text" class="form-control" name="designation'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Duration</label>'+
'<input type="text" class="form-control" name="duration'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Employer</label>'+
'<input type="text" class="form-control" name="employer'+i+'">'+
'</div>'+
'</div>');
$(function () {
$('#1experience').val(i);
});
}
</script>
If you modify the HTML slightly in both the initial page display and within the javascript function so that the newly added items are grouped within a single container(div) and the initial elements are similarly grouped and a name assigned to the immediate ancestor of the initially displayed elements ( here I chose data-id='receiver' ) then this matter of deducing the number of times the elements have been added becomes a matter of counting the child elements within the common parent - querySelectorAll being useful here though no doubt jQuery has a concise method to do this too.
With that said though if you were to use the array syntax form form element names, such as designation[] or duration[] when the form is submitted you will have access to each element as an array in PHP ( or other backend language ) which will also, as a byproduct, reveal that same number of elements. Using the array syntax means you do not need to try to keep track of this number within the client
function addexperience() {
let i=document.querySelectorAll('[data-id="receiver"] > div').length;
$('[data-id="receiver"]').append('<div><div class="col-md-3"> <label>Status</label> <select class="form-control" name="status' + i + '">' +
'<option value="">Select</option>' +
'<option value="Current">Current</option>' +
'<option value="Past">Past</option> </select> </div>' +
'<div class="col-md-3">' +
'<label>Designation</label>' +
'<input type="text" class="form-control" name="designation' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Duration</label>' +
'<input type="text" class="form-control" name="duration' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Employer</label>' +
'<input type="text" class="form-control" name="employer' + i + '">' +
'</div>' +
'</div></div>');
alert(i);
document.querySelector('input[name="duplicates"]').value=i;
fetch( location.href, {method:'post',body:'total='+i})
.then(r=>r.text())
.then(text=>{
alert(text)
})
}
[data-id='receiver']{border:1px solid red;margin:1rem;padding:1rem;}
[data-id='receiver'] > div{margin:1rem;border:1px solid black;padding:0.5rem}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<div data-id='receiver' class="form-group">
<div>
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience[ 'status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience[ 'status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
<!-- additional content inserted here within common parent -->
</div>
</div>
<input type='hidden' name='duplicates' />

Required field form by using id attribute in Javascript

here is my form. When user want to add another form they just click the "tambah bil".
my problem is the function of required just detect the name of input filed. I want the function of required detect by the id of input field because it have the same name in one form.
<fieldset>
<div id="item">
<div class="callout callout-warning" style="margin-top:15px">
<div class="row">
<div class="col-md-12">
<h6><i class="far fa-file-alt"style="font-size:20px"></i><b style="padding-left:7px">Maklumat Bil</b>
<span class="float-sm-right">
<button type="button" name="add" id="add" class="btn btn-block btn-primary btn-sm right add"><i class="fa fa-plus"></i> Tambah Bil</button>
</span></h6><hr>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Jabatan</label>
<input type="hidden" name="jabatan[]" class="form-control" value="<?php echo $dept; ?>">
<span class="form-control form-control-sm"><?php echo $jab; ?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Kod*</label>
<select class="form-control select2bs4" name="kod[]" id= "kod" required>
<option value="" disabled="disabled" selected="selected">--Pilih Kod--</option>?php foreach($kod as $k):?>
<option value="<?php echo $k->kod;?>"><?php echo $k->kod;?> - <?php echo $k->keterangan;?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Perkara (Wajid isi ruangan pertama)*</label>
<input type="text" class="form-control form-control-sm" name="perkara1[]" id="perkara1" required>
<input type="text" class="form-control form-control-sm" name="perkara2[]" id="perkara2" required="false" style="margin-top:6px !important" >
<input type="text" class="form-control form-control-sm" name="perkara3[]" id="perkara3" required="false" style="margin-top:6px !important" >
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>No. Rujukan*</label>
<input id="noruj" type="text" class="form-control form-control-sm" name="noruj[]" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Jumlah (RM)* </label>
<input type="text" id="currency" class="form-control form-control-sm currency" name="jumlah[]" required>
</div>
</div>
</div>
<span>*Ruangan wajib diisi</span>
</div>
</div>
</fieldset>
here is my form in javascript when user want to add another bil.
$('html, body').animate({scrollTop: '+=550px'}, 400);
var html = '';
html += '<div class="callout callout-warning">';
html += '<div class="row"><div class="col-md-12"><h6><i class="far fa-file-alt"style="font-size:20px"></i><b style="padding-left:7px">Maklumat Bil</b><span class="float-sm-right" style="padding-left:5px"><button type="button" name="remove" class="btn btn-block btn-danger btn-sm right remove"><i class="fa fa-minus"></i> Padam Bil</button></span><span class="float-sm-right"><button type="button" name="add" class="btn btn-block btn-primary btn-sm right add"><i class="fa fa-plus"></i> Tambah Bil</button></span></h6><hr></div></div>';
html += '<div class="row"><div class="col-md-12"><div class="form-group"><label>Jabatan*</label><input type="hidden" name="jabatan[]" class="form-control" value="<?php echo $dept; ?>"><span class="form-control form-control-sm"><?php echo $jab; ?></span></div></div></div>';
html += '<div class="row"><div class="col-md-6">';
//html += '<div class="form-group"><label>Kategori*</label><select name="kategori'+i+'[]" class="form-control select2bs4" style="width: 100%;" required><option value="" disabled="disabled" selected="selected">--Pilih Kategori--</option><option value="INDIVIDU">Individu</option><option value="SYARIKAT">Syarikat</option></select></div>';
html += '<div class="form-group"><label>Kod*</label><select class="form-control select2bs4" name="kod[]" id ="kod'+i+'" required><option value="" disabled="disabled" selected="selected">--Pilih Kod--</option><?php foreach($kod as $k):?><option value="<?php echo $k->kod;?>"><?php echo $k->kod;?> - <?php echo $k->keterangan;?></option><?php endforeach;?></select></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Perkara (Wajib isi ruangan pertama)*</label><input type="text" class="form-control form-control-sm" name="perkara1[]" id="perkara1'+i+'" required><input type="text" class="form-control form-control-sm" name="perkara2[]" id="perkara2'+i+'" style="margin-top:6px !important" ><input type="text" class="form-control form-control-sm" name="perkara3[]" id="perkara3'+i+'" style="margin-top:6px !important" ></div>';
html += '</div></div>';
html += '<div class="row"><div class="col-md-6">';
html += '<div class="form-group"><label>No. Rujukan*</label><input id="noruj'+i+'" type="text" class="form-control form-control-sm" name="noruj[]" required></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Jumlah (RM)*</label><input type="text" id="currency" class="form-control form-control-sm currency" name="jumlah[]" required></div>';
html += '</div><span>*Ruangan wajib diisi</span></div>';
html += '</div>';
$('#item').append(html);
$(function()
{
const inputs = $("input").prop('required',true);
console.log('return value:');
inputs.each(log);
console.log('');
console.log('selector:');
$("input[required]").each(log);
function log(index, element)
{
console.log($(element).attr("id"));
}
});
the coding required field just read input field outside the javascript...
how i want to detect the input in javascript form is required by using id attribute??
function required cannot detect the id of input field, function detect the name of input field it is because in one form have same name of input field.
anybody can help me??
thank you in advance.
You could use it immediately after you set the prop
const inputs = $("input").prop('required',true);
console.log(inputs);
You can also use an attribute selector
const inputs = $("input[required]");
const i = 1;
$('html, body').animate({scrollTop: '+=550px'}, 400);
var html = '';
html += '<div class="callout callout-warning">';
html += '<div class="row"><div class="col-md-12"><h6><i class="far fa-file-alt"style="font-size:20px"></i><b style="padding-left:7px">Maklumat Bil</b><span class="float-sm-right" style="padding-left:5px"><button type="button" name="remove" class="btn btn-block btn-danger btn-sm right remove"><i class="fa fa-minus"></i> Padam Bil</button></span><span class="float-sm-right"><button type="button" name="add" class="btn btn-block btn-primary btn-sm right add"><i class="fa fa-plus"></i> Tambah Bil</button></span></h6><hr></div></div>';
html += '<div class="row"><div class="col-md-12"><div class="form-group"><label>Jabatan*</label><input type="hidden" name="jabatan[]" class="form-control" value="<?php echo $dept; ?>"><span class="form-control form-control-sm"><?php echo $jab; ?></span></div></div></div>';
html += '<div class="row"><div class="col-md-6">';
//html += '<div class="form-group"><label>Kategori*</label><select name="kategori'+i+'[]" class="form-control select2bs4" style="width: 100%;" required><option value="" disabled="disabled" selected="selected">--Pilih Kategori--</option><option value="INDIVIDU">Individu</option><option value="SYARIKAT">Syarikat</option></select></div>';
html += '<div class="form-group"><label>Kod*</label><select class="form-control select2bs4" name="kod[]" id ="kod'+i+'" required><option value="" disabled="disabled" selected="selected">--Pilih Kod--</option><?php foreach($kod as $k):?><option value="<?php echo $k->kod;?>"><?php echo $k->kod;?> - <?php echo $k->keterangan;?></option><?php endforeach;?></select></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Perkara (Wajib isi ruangan pertama)*</label><input type="text" class="form-control form-control-sm" name="perkara1[]" id="perkara1'+i+'" required><input type="text" class="form-control form-control-sm" name="perkara2[]" id="perkara2'+i+'" style="margin-top:6px !important" ><input type="text" class="form-control form-control-sm" name="perkara3[]" id="perkara3'+i+'" style="margin-top:6px !important" ></div>';
html += '</div></div>';
html += '<div class="row"><div class="col-md-6">';
html += '<div class="form-group"><label>No. Rujukan*</label><input id="noruj'+i+'" type="text" class="form-control form-control-sm" name="noruj[]" required></div>';
html += '</div><div class="col-md-6">';
html += '<div class="form-group"><label>Jumlah (RM)*</label><input type="text" id="currency" class="form-control form-control-sm currency" name="jumlah[]" required></div>';
html += '</div><span>*Ruangan wajib diisi</span></div>';
html += '</div>';
$('#item').append(html);
$(function()
{
const inputs = $("input").prop('required',true);
console.log('return value:');
inputs.each(log);
console.log('');
console.log('selector:');
$("input[required]").each(log);
function log(index, element) {
console.log($(element).attr('name'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="item"></div>

how to sort select option and combine it if the option type is same

I need some help with the code here, so whenever i pick a same option and click submit order button it will display the qty>name>price of the option i choose based on the row of the select boxes.
I want to change the result so it will be when i click a same option type, it should combine the option and sum the qty in a same row at the table. Here is the image in case anyone a bit confused with my question
As you can see, i pick "pancake" twice with a different qty here and the result are the first row and second row of table which display it separately. For the output it should be like this "Qty combined (2+3=5), Pancake, Price sum of the combined qty (17000+25500=42500)".
I have tried searching for a similar question like this, but the method only works when it have same name inside a json object..
Here is the full code:
var data = {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function (option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function () {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function () {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function () {
$('.order').click(function () {
var selectMenu = {};
$("select.type").each(function (i) {
selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val())
selectMenu[i] = {
"total": price * qty,
"itemname": text,
"qty": qty
}
})
$('.result tbody').html("");
var total = 0
$.each(selectMenu, function (index, data) {
$('.result tbody').append("<tr class='orders'><td>" + data.qty + '</td><td>' + data.itemname + '</td><td>' + data.total + "</td></tr>");
total += parseInt(data.total);
})
$(".totalPrice input").val(total)
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:30%">Qty</th>
<th style="width:30%">Item name</th>
<th style="width:30%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" class="text-center" disabled>
</div>
Sorry for asking a lot, hope anyone would be kind to share some tips on the problem i had.
ihave modified your code of order click. I use selectMenu object like that
selectMenu={item:[qty,price,qty*price}, so its easier to group same item. (i avoid to display an item with qty = 0).
var data = {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function (option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function () {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function () {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function () {
$('.order').click(function () {
var selectMenu = {};
$("select.type").each(function (i) {
//selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val());
if(text in selectMenu){
selectMenu[text][0] += qty;
selectMenu[text][1] += price;
selectMenu[text][2] += qty*price;
}else{
if(qty > 0) selectMenu[text]=[qty,price,qty*price];
}
})
$('.result tbody').html("");
var total = 0
$.each(selectMenu, function (key,value) {
$('.result tbody').append("<tr class='orders'><td>" + value[0] + '</td><td>' + key + '</td><td>' + value[2] + "</td></tr>");
total += parseInt(value[2]);
});
$(".totalPrice input").val(total)
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:30%">Qty</th>
<th style="width:30%">Item name</th>
<th style="width:30%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" class="text-center" disabled>
</div>

creating new div through javascript

In the form have a one div tag in which some fields have,now i can create more fields from this one div tag,from the plus symbol with javascript and i can remove also div fields through minus symbol...
in the main or first DIV tag all categories are displayed but when i create another DIV through plus symbol so all categories are not display..
please anyone tell me how i can solve this problem...
js code
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script type="text/javascript">
$(document).ready(function(){
var addButton = $('#addButton');
var wrapper = $('#wrapper');
var x = "{{$detail_count + 1}}";
$(addButton).click(function(){
x++;
$(wrapper).append(
'<div class="form-group row">'+
'<label class="col-sm-1 col-form-label" style="text-align-last: right;">Category : </label>'+
'<div class="col-sm-2">'+
'<select class="form-control" name="cat_id" id="category '+x+'">'+
'<option value="" disabled selected>Select Category</option>'+
'foreach($category as $key){'+
'<option value="{{ $key->id }}">{{ $key->cat_nm }}</option>'+
' }' +
'</select>'+
'</div>'+
'<label class="col-sm-1 col-form-label" style="text-align-last: right;">SubCategory : </label>'+
'<div class="col-sm-2">'+
'<select class="form-control" id="subcategory '+x+'" name="sub_cat_id">'+
'<option value="" disabled selected>Subcategory from category</option>'+
'</select>'+
'</div>'+
'<label class="col-sm-1 col-form-label" style="text-align-last: right;">Product Price:</label>'+
'<div class="col-sm-2">'+
'<select class="form-control" id="productprice '+x+'" name="pro_price"> '+
'<option>Price from subcategory</option>'+
'</select>'+
'</div>'+
'<label class="col-sm-1 col-form-label" style="text-align-last: right;">Total : </label>'+
'<div class="col-sm-1">'+
'<input type="text" class="form-control" name="total[]" cat_id="total '+x+'">'+
'</div>'+
'<div class="col-sm-1">'+
'<i class="fa fa-minus"></i>'+
'</div>'+
'</div>'
);
});
$(wrapper).on('click','#remove',function(){
if(confirm("Do you want to delete this row?")){
$(this).parent().parent().remove();
}
});
});
</script>
HTML Code
<div class="col-md-12 field-wrapper" id="wrapper">
<div class="form-group row">
<label class="col-sm-1 col-form-label" style="text-align-last: right;">Category : </label>
<div class="col-sm-2">
<select class="form-control" name="cat_id" id="category">
<option value="" disabled selected>Select Category</option>
#foreach($category as $key)
<option value="{{ $key->id }}">{{ $key->cat_nm }}</option>
#endforeach
</select>
</div>
<label class="col-sm-1 col-form-label" style="text-align-last: right;">SubCategory : </label>
<div class="col-sm-2">
<select class="form-control" id="subcategory" name="sub_cat_id">
<option value="" disabled selected>Subcategory from category</option>
</select>
</div>
<label class="col-sm-1 col-form-label" style="text-align-last: right;">Product Price:</label>
<div class="col-sm-2">
<select class="form-control" id="productprice" name="pro_price">
<option>Price from subcategory</option>
</select>
</div>
<label class="col-sm-1 col-form-label" style="text-align-last: right;">Total : </label>
<div class="col-sm-1">
<input type="text" class="form-control" name="total[]">
</div>
<div class="col-sm-1">
<i class="fa fa-plus"></i>
</div>
</div>
</div>
First DIV
Another DIVs
This is is happening because your foreach loop is inside your append() and it is not appending the all option only last value is getting appended that you can see in your output.Now, to solve this put this foreach loop outside your append something like this (I don't know much about laravel so there may be syntax error ) :
var select=""
foreach($category as $key){
//appending option in select variable
select+='<option value="{{ $key->id }}">{{ $key->cat_nm }}</option>';
}
Then passed this value i.e: select in append something like below :
$(wrapper).append(
'<div class="form-group row">' +
'<label class="col-sm-1 col-form-label" style="text-align-last: right;">Category : </label>' +
'<div class="col-sm-2">' +
'<select class="form-control" name="cat_id" id="category ' + x + '">' +
'<option value="" disabled selected>Select Category</option>' +
select + //<--pass here
'</select>' + '</div>');

JavaScript: Add increasing number to name attr

I'm creating an HTML table from data pulled from an XML file using JQuery. This data is to be posted via HTTP POST somewhere else.
When the XML contains multiple items (i.e. songs), it creates the respective HTML but the name attribute of the input elements stays the same.
This is the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$.get('test.xml', function(d){
$('body').append('<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank" />');
$('#myForm').append('<div id="mySongs" />');
$('#mySongs').append('<input type="submit" value="Submit">');
$(d).find('song').each(function() {
var $song = $(this);
var title = $song.find('title').text();
var artist = $song.find('artist').text();
var price = $song.find('price').text();
var currency = $song.find('currency').text();
var html = '<div id="mySongs"> <span id="title"><input type="text" name="title" value="' + title + '" /></span>';
html += '<span id="artist"><input type="text" name="artist" value="' + artist + '" /></span>';
html += '<span id="price"><input type="text" name="price" value="' + price + '" /></span>';
html += '<span id="currency"><input type="text" name="currency" value="' + currency + '" /></span>';
html += '</div>';
$('#mySongs').append($(html));
});
});
});
</script>
The HTML code produced after pulling the XML data and running the above code looks currently this way:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price" value="25.00"></span>
<span id="currency">
<input type="text" name="currency" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price" value="30.00"></span>
<span id="currency">
<input type="text" name="currency" value="USD"></span>
</div>
</form>
I would like to add an increasing number to the name attribute so that when multiple items are pulled, the code shows the respective number to identify it (For example: name="title[1]").
I would like the HTML to look as shown below instead:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title[1]" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist[1]" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price[1]" value="25.00"></span>
<span id="currency">
<input type="text" name="currency[1]" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title[2]" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist[2]" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price[2]" value="30.00"></span>
<span id="currency">
<input type="text" name="currency[2]" value="USD"></span>
</div>
</form>
How to achieve this? Any suggestion is highly appreciated.
You can write
title[] instead title[1]
and server automaticaly set indexes.
Can use the index argument of each callback:
$(d).find('song').each(function(i) {
var html = '<div...> <span..><input name="title['+ i +']" value="' + title + '" /></span>'
});
What about this:
var idx = 0;
$(d).find('song').each(function () {
var $song = $(this);
var title = $song.find('title').text();
var artist = $song.find('artist').text();
var price = $song.find('price').text();
var currency = $song.find('currency').text();
var html = '<div id="mySongs"> <span id="title"><input type="text" name="title[' + idx + ']" value="' + title + '" /></span>';
html += '<span id="artist"><input type="text" name="artist[' + idx + ']" value="' + artist + '" /></span>';
html += '<span id="price"><input type="text" name="price[' + idx + ']" value="' + price + '" /></span>';
html += '<span id="currency"><input type="text" name="currency[' + idx + ']" value="' + currency + '" /></span>';
html += '</div>';
$('#mySongs').append($(html));
idx++;
});

Categories

Resources