I have a problem with selected option value for different row. I succeed to get value for first row. What i want to do is different row item have different price.
My previous question about "JQuery Get Selected Option Value for Add Row" has been solved : Here
Now, i come out with another issues which is to get different value for different row. The picture sample is like below
My problem sample screenshot
Here's the code for my JS :
var i=$('table tr').length;
$(".tambah_sofa").on('click',function(){
/* add new row function start here */
html = '<tr id="row_'+i+'">';
html += '<td><button type="button" id="delete-button" data-row-delete="row_'+i+'">X</button></td>';
html += '<td><select id="sofa_'+i+'"><option value="10">hai</option><option value="20">20</option> <option value="50">50</option></select></td>';
html += '<td>X</td>';
html += '<td><input type="number" name="quantity[]" id="quantity_'+i+'" value="1" disabled="disabled"></td>';
html += '</tr>';
sidebar = '<tr id="row_'+i+'">';
sidebar += '<td><input style="width:50%;" name="sofa'+i+'" type="text" id="price_sofa'+i+'" value="" disabled="disabled"></td>';
sidebar += '</tr>';
$('#table_item').append(html);
$('#table_sidebar').append(sidebar);
/* Get selected option value start here */
$('body').on('change', '#sofa_'+i+'', function () {
$('#price_sofa'+i+'').val($(this).find('option:selected').val());
});
/* Get selected option value end here */
i++;
});
var i = $('table tr').length;
$(".tambah_sofa").on('click', function() {
/* add new row function start here */
html = '<tr id="row_' + i + '">';
html += '<td><button type="button" id="delete-button" data-row-delete="row_' + i + '">X</button></td>';
html += '<td><select id="sofa_' + i + '"><option value="10">hai</option><option value="20">20</option> <option value="50">50</option></select></td>';
html += '<td>X</td>';
html += '<td><input type="number" name="quantity[]" id="quantity_' + i + '" value="1" disabled="disabled"></td>';
html += '</tr>';
sidebar = '<tr id="row_' + i + '">';
sidebar += '<td><input style="width:50%;" name="sofa' + i + '" type="text" id="price_sofa' + i + '" value="" disabled="disabled"></td>';
sidebar += '</tr>';
$('#table_item').append(html);
$('#table_sidebar').append(sidebar);
/* Get selected option value start here */
(function(index){
$('#sofa_' + index).on('change', function () {
$('#price_sofa' + index).val($(this).val());
});
})(i);
/* Get selected option value end here */
i++;
});
Related
I'm trying to set a select button which gets the options from an ajax call.
The ajax call is working. The problem is when I try to create the variable which contains the html. I don't know the way to iterate and create multiple option inside the variable.
This is the ajax call:
$.ajax({
url: '/facturas/data',
type: 'GET',
success: function(s) {
var currency = s.currency;
var rendiciones = s.rendiciones;
var tipo_comprobante = s.tipo_comprobante;
var tipo_gasto = s.tipo_gasto;
var fm_table_row = '<td>'+
'<div class="inputfield"><select name="fm_tipo_comp_select"><option value="" disabled="" selected="">Comprobante</option>'+
tipo_comprobante.forEach(row){
'<option value="id">nombre</option>'+
}
'</select><label>Tipo comprobante</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><select name="fm_tipo_gasto"><option value="" disabled="" selected="">Tipo gasto</option>'+
'<option value="id">nombre </option>'+
'</select><label>Tipo gasto</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_serie" type="text" name="fm_serie" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_ndoc" type="text" name="fm_ndoc" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_ruc" type="text" name="fm_ruc" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate right-align" id="fm_rs" type="text" name="fm_rs" disabled="disabled" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="datepicker validate" id="fm_fecha" type="text" name="fm_fecha" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><select name="fm_moneda"><option value="" disabled="" selected="">Moneda</option>'+
'<option value="id">nombre </option>'+
'</select><label>Moneda</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><input class="validate" id="fm_monto" type="number" /></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><select name="fm_retencion"><option value="" disabled="" selected="">RetenciĆ³n</option>'+
'<option value="id">nombre </option>'+
'</select><label>RetenciĆ³n</label></div>'+
'</td>'+
'<td>'+
'<div class="inputfield"><a class="btn-floating btn-small waves-effect waves-light red delete-btn"><i class="material-icons">delete</i></a></div>'+
'</td>';
}
});
I added the tipo_comprobante.forEach(row){} to show what I want to do.
With reduce and ES6 String templates
var options = ['cat', 'dog', 'fish'].reduce((acc, value) =>
acc + `<option value="${value}">${value}</option>`, '');
var result = `<select>${options}</select>`;
Inside the ajax call, you can create a string variable and use whatever loop (for loop) you like to set it, and then use the variable inside the ajax call in the desired location within the html.
var myOptionsValues = ['cat', 'dog', 'fish'];
var myOptionsHtml = '';
myOptions.forEach(function (optionValue) {
myOptionsHtml+='<option value="' + optionValue + '">' + optionValue + '</option>';
});
var myHtmlForAjax = '<select>' + myOptions + '</select>';
Yes. Just add it to a DOM element, then use .children to get it in Array form:
/* a string with HTML text */
const someString = `
<p>Paragraph1</p>
<p>Paragraph2</p>
<p>Paragraph3</p>
`;
/* create a temporary element */
const temp = document.createElement("div");
/* add the HTML text to that element */
temp.innerHTML = someString;
/* create the array */
const array = Array.from(temp.children);
/* loop */
for(let i = 0; i < array.length; i++){
const p = array[i];
alert(p); // or do whatever
}
I have a running code snippet that dynamically adds input boxes to a form that is working so fine, however, am trying to get totals of the values from the input boxes but nothing seem to be working. The total area is only showing 0 but not giving me correct results.
Here is my code:
JAVASCRIPT TO DISPLAY THE TABLE WITH FORM
$(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><input class="qty" type="text" value="0" data-cubics="500"/></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td width="33%"><span class="cubics"></span>';
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);
});
JAVASCRIPT TO DO THE MATH
<script>
function total() {
var total1 = 0;
$('span.cubics').each(function () {
var n = parseFloat($(this).text());
total1 += isNaN(n) ? 0 : n;
});
$('.totalcubics').text(total1.toFixed(2));
}
$('input.qty').keyup(function () {
var val = parseFloat($(this).val());
val = (val ? val * $(this).data('cubics') : '');
$(this).closest('td').next().find('span.cubics').text(val);
total();
});
var $form = $('#insert_form'),
$summands = $form.find('input.qty'),
$sumDisplay = $('span#totalquantity');
$form.keyup(function () {
var sum = 0;
$summands.each(function () {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.text(sum);
});
$('input').on({
focus: function () {
if (this.value == '0') this.value = '';
},
blur: function () {
if (this.value === '') this.value = '0';
}
});
</script>
HTML CODE TO DISPLAY TOTALS
<tr class="bg">
<td width="33%">TOTAL</td>
<td width="33%"><span id="totalquantity"></span>
</td>
<td width="33%"><span class="totalcubics"></span>
</td>
</tr>
Any assistance to my problem is highly appreciated
I think your problem in
$(this).closest('td').next().find('span.cubics').text(val);
this mean go to the next td and find the span and there is no span in the next td .. you can use
$(this).closest('tr').find('span.cubics').text(val);
or
$(this).closest('td').next().next().find('span.cubics').text(val);
and while you append the row dynamically you need to use
$(document).on('keyup' , 'input.qty' , function () {
instead of
$('input.qty').keyup(function () {
You need to recreate $summands each time you add a row to the table. Insert the line to do so after adding the row.
$(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><input class="qty" type="text" value="0" data-cubics="500"/></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td width="33%"><span class="cubics"></span>';
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);
$summands = $form.find('input.qty'); //*************** add this line
});
function total() {
var total1 = 0;
$('span.cubics').each(function () {
var n = parseFloat($(this).text());
total1 += isNaN(n) ? 0 : n;
});
$('.totalcubics').text(total1.toFixed(2));
}
$('input.qty').keyup(function () {
var val = parseFloat($(this).val());
val = (val ? val * $(this).data('cubics') : '');
$(this).closest('td').next().find('span.cubics').text(val);
total();
});
var $form = $('#insert_form'),
$summands = $form.find('input.qty'),
$sumDisplay = $('span#totalquantity');
$form.keyup(function () {
var sum = 0;
$summands.each(function () {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.text(sum);
});
$('input').on(
{
focus: function () {
if (this.value == '0') this.value = '';
},
blur: function () {
if (this.value === '') this.value = '0';
}
});
}); // end of document ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="insert_form" onsubmit="return false">
<table>
<tr class="bg">
<td width="33%">TOTAL</td>
<td width="33%"><span id="totalquantity"></span></td>
<td width="33%"><span class="totalcubics"></span></td>
</tr>
</table>
<button type="button" class="add">add</button>
<table id="item_table">
</table>
</form>
At the moment you are creating summands collection with no elements, before any rows have been added.
With the help of #tracktor53, i managed to get a fix for my problem, below is my updated code;
$(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"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><input class="qty" type="text" value="0"/></td>';
html += '<td width="33%"><span class="cubics"></span>';
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);
$summands = $form.find('input.qty'); //*************** added this line
});
And with #mohamed's help, this line $(this).closest('td').next().find('span.cubics').text(val); was looking for the next <td> which in actual sense, the next <td> was an input field but not the one with <span id='cubics'></span> so, i had to adjust that to this;
html += '<td><input class="qty" type="text" value="0"/></td>';
html += '<td width="33%"><span class="cubics"></span>';
Then after i had to use
$(document).on('keyup' , 'input.qty' , function () {
instead of
$('input.qty').keyup(function () {
Now everything is working fine only that i want to multiply select option values with qty input from this line;
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>'
Any further assistance about this is highly welcome
I'm trying to create a questions with answer or
multiple choice in CodeIgniter, I create the choice using jQuery and now I don't know how to get all value from text input.
can someone help me for this case??
This code:
var choices = [{
id_soal: 'choice1'
}, {
id_soal: 'choice2'
}, {
id_soal: 'choice3'
}];
var html = '';
var i;
for (i = 0; i < choices.length; i++) {
html += '<div class="row">',
html += '<div class="col-xs-8 col-md-4>',
html += '<div class="input-group">',
html += '<span class="input-group-addon" style="background:green"><i class="fa fa-question-circle"></i> Soal' + (i + 1) + '</span>',
html += '<input type="text" name="Question' + i + '" id="Question' + i + '" class="Question form-control" placeholder="Question" required>',
html += '</div></div></div></br>',
html += '<div class="row">',
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon">A</span>',
html += '<input type="text" name="A_jawaban' + i + '" id="A_jawaban' + i + '" class="form-control A_jawaban" placeholder="Result" required>',
html += '</div></div>'
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> B</span>',
html += '<input type="text" name="B_jawaban' + i + '" id="B_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div>',
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> C</span>',
html += '<input type="text" name="C_jawaban' + i + '" id="C_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div></div><br>';
html += '<div class="row">',
html += '<div class="col-xs-4 col-md-6">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> D</span>',
html += '<input type="text" name="D_jawaban' + i + '" id="D_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div>'
html += '<div class="col-xs-4 col-md-6">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> E</span>',
html += '<input type="text" name="E_jawaban' + i + '" id="E_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div></div><br>';
}
$('.judul').html(html);
$('#tambah').click(function(event) {
console.log('THIS CHOICES',choices)
var results = $('.Question').serializeArray();
console.log('FOR QUESTIONS',results)
var resultsAnswearA = $('.A_jawaban').serializeArray();
console.log('FOR QUESTIONS',resultsAnswearA)
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div name="judul" class="judul"></div>
<button id="tambah" name="tambah" class="btn btn-warning"><i class="icon-pencil5"></i> Tambah</button>
UPDATE
wow sorry for my question above, I forgot and just realized I got the answer to use query selector. just check the code
Try:
var allInputsValue = {};
$(".judul input").each(function(){
//Add each input value to all inputs
allInputsValue[allInputsValue.length] = {
"name":$(this).attr("name"),
"value":$(this).val()
};
});
console.log(allInputsValue);
i have trouble using autocomplete with dynamic created input. I can't get autocomplete to bind to the new inputs.
This code autocomplete I used on the first input
$(function() {
$( '#nama-0').autocomplete({
source: "get_barang.php",
minLength: 2,
select: function( event, ui ) {
$('#kode-0').val(ui.item.kode);
$('#harga-0').val(ui.item.harga);
}
});
});
and this new table row with input:
$('#tambah').click(function() {
var i = $('input').size() + 1,
input = '<tr id="box' + i + '">';
input += '<td><input id="nama-' + i + '" name="nama_input[]" autocomplete="off" class="nama form-control" /></td>';
input += '<td><input id="kode-' + i + '" name="kode_input[]" readonly="readonly" class="form-control" /></td>';
input += '<td><input id="harga-' + i + '" name="harga_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="jumlah-' + i + '" name="jumlah_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="total-' + i + '" name="total_input[]" class="total form-control" readonly="readonly" /></td>';
input += '<td><button id="hapus" class="btn btn-default"><b>Hapus</b></button></td>'
input += '</tr>';
$('#box').append(input);
i++;
return false;
});
i think the problem I guess the problem is in the use of dynamic input id attribute. how to write id of dynamic input, and apply them in autocomplete? any help appreciated.
Your issue is because the #nama-N element doesn't exist in the DOM when you try to initialise the autocomplete function on it.
To fix this, move your first block of code inside the click handler, after append() has been called. Try this:
$('#tambah').click(function(e) {
e.preventDefault();
var i = $('input').size() + 1;
var input = '<tr id="box' + i + '">';
input += '<td><input id="nama-' + i + '" name="nama_input[]" autocomplete="off" class="nama form-control" /></td>';
input += '<td><input id="kode-' + i + '" name="kode_input[]" readonly="readonly" class="form-control" /></td>';
input += '<td><input id="harga-' + i + '" name="harga_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="jumlah-' + i + '" name="jumlah_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="total-' + i + '" name="total_input[]" class="total form-control" readonly="readonly" /></td>';
input += '<td><button id="hapus" class="btn btn-default"><b>Hapus</b></button></td>'
input += '</tr>';
$('#box').append(input);
// attach autocomplete here as the element now exists in the DOM
$('#nama-' + i).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$('#kode-0').val(ui.item.kode);
$('#harga-0').val(ui.item.harga);
}
});
});
JS Fiddle of nonworking code :
https://jsfiddle.net/8fo28ccL/
With the code below, I have items that are dynamically added to my html body whenever a user clicks a button to add a line. The top line works just fine(its a checkbox), but I cannot get the select input lines to work....
var addNewRow = function(id){
html = '<tr id="tr_'+i+'">';
html += '<td><input class="case" id="caseNo_'+i+'" type="checkbox"/></td>';
html += '<td class="prod_c"><input type="text" data-type="productCode" name="data[InvoiceDetail]['+i+'][product_id]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off">';
html +='<span class="add_icon hide" id="add_icon_'+i+'"> <i class="fa fa-plus-circle"></i></span>';
html +='</td>';
html += '<td><input type="text" data-type="productName" name="data[InvoiceDetail]['+i+'][productName]" id="itemName_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" name="data[InvoiceDetail]['+i+'][price]" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[InvoiceDetail]['+i+'][quantity]" id="quantity_'+i+'" class="form-control changesNo quanyityChange" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">';
html += '<input type="hidden" id="stock_'+i+'"/>';
html += '<input type="hidden" id="stockMaintainer_'+i+'" name="data[InvoiceDetail]['+i+'][stockMaintainer]" />';
html += '<input type="hidden" id="previousQuantity_'+i+'"/>';
html += '<input type="hidden" id="invoiceDetailId_'+i+'"/>';
html += '</td>';
html += '<td><input type="text" id="total_'+i+'" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail][0][staged]" id="staged_1'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><select value="" name="data[InvoiceDetail][0][location]" id="location_1'+i+'" class="form-control autocomplete_txt" autocomplete="off">';
html += '<option value="Used">Used</option>';
html += '<option value="RTS">RTS</option>';
html += '<option value="LAJ">LAJ</option>';
html += '</select></td>';
html += '</tr>';
if( typeof id !== "undefined"){
$('#tr_'+id).after(html);
}else{
$('table').append(html);
}
Edit : Sorry, added an old revision of code, updated with the proper TD elements. The select box will appear on the page, but if you try to select values, nothing saves...
Edit 2 : Guys/Gals, the issue is not whether the html appears in my body(it does via the append function, the issue is AFTER it is added. After the text is added, a checkbox appears, and a form select field. If you select a different option in the form select, and save the form, that option is NOT saved.
Try adding var before html , adjusting += to = at first html variable reference
var i = 0;
var html = '<td><input type="checkbox" name="data[InvoiceDetail][0][staged]" id="staged_1'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><select value="" name="data[InvoiceDetail][0][location]" id="location_1'+i+'" class="form-control autocomplete_txt" autocomplete="off">';
html += '<option value="Used">Used</option>';
html += '<option value="RTS">RTS</option>';
html += '<option value="LAJ">LAJ</option>';
html += '</select></td>';
document.body.innerHTML = html
From those stuff you provided i can suggest only this things. You should try once.
var html = "";
html += "<td><input type='checkbox' name='data[InvoiceDetail][0][staged]' id='staged_1'" + i + " class='form-control autocomplete_txt' autocomplete='off'></td>";
html += "<td><select value='' name='data[InvoiceDetail][0][location]' id='location_1'" + i + "'class='form-control autocomplete_txt' autocomplete='off'>";
html += "<option value='Used'>Used</option>";
html += "<option value='RTS'>RTS</option>";
html += "<option value='LAJ'>LAJ</option>";
html += "</select></td>";
$(html).appendTo(WhereYouwanttoappend);
Hope it may work for you.
your html wasn't initialised (probably)
var html = ''
check out this running code: http://codepen.io/anon/pen/zvOaqj
Remove the "value" attribute from your select element.