Is there a way to loop inside a variable which contains html - javascript

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
}

Related

dynamically generate a list dropdown in javascript from JSON data

I have generated a form and storing it into a JS variable but the problem is I want to generate a dropdown list. Data for that dropdown is present in an array into JSON. I tried to concat values using a for loop but that didn't work
function(resp){
resp = JSON.parse(resp);
console.log(resp);
let dispData = '<form>'+
'<div class="form-group">'+
'<label>Item</label>'+
'<input type="text" class="form-control reas-item" id="'+resp["item_details"].master_id+'" value="'+resp["item_details"].item_name+'" disabled>'+
'</div>'+
'<div class="form-group">'+
'<label>Date</label>'+
'<input type="date" class="form-control reas-date">'+
'</div>'+
'<div class="form-group">'+
'<label>Quantity</label>'+
'<input type="number" class="form-control reas-quantity" min="1" max="'+resp["item_details"].quantity+'" value="'+resp["item_details"].quantity+'" >'+
'</div>'+
'<div class="form-group">'+
'<label>Reassign To:</label>'+
'<select class="form-control reas-staff">'
for (var i = 0; i < resp['trachers_list'].length; i++) {
var staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
+'<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>'
}
'</select>'+
'</div>'+
'</form>';
/*for (var i = 0; i < resp['trachers_list'].length; i++) {
let staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
$(".reas-staff").html('<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>');
}*/
}
See Commented for loop I've tried that as well but that is also not working.
This is how my json looks like
Please do code like below:
function(resp){
resp = JSON.parse(resp);
console.log(resp);
let dispData = '<form>'+
'<div class="form-group">'+
'<label>Item</label>'+
'<input type="text" class="form-control reas-item" id="'+resp["item_details"].master_id+'" value="'+resp["item_details"].item_name+'" disabled>'+
'</div>'+
'<div class="form-group">'+
'<label>Date</label>'+
'<input type="date" class="form-control reas-date">'+
'</div>'+
'<div class="form-group">'+
'<label>Quantity</label>'+
'<input type="number" class="form-control reas-quantity" min="1" max="'+resp["item_details"].quantity+'" value="'+resp["item_details"].quantity+'" >'+
'</div>'+
'<div class="form-group">'+
'<label>Reassign To:</label>'+
'<select class="form-control reas-staff">';
for (var i = 0; i < resp['trachers_list'].length; i++) {
var staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name;
dispData += '<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>';
}
dispData += '</select>'+
'</div>'+
'</form>';
/*for (var i = 0; i < resp['trachers_list'].length; i++) {
let staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
$(".reas-staff").html('<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>');
}*/
}

JQuery get selected option value for different row

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++;
});

How to make autocomplete for form dynamic

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);
}
});
});

jQuery undefined value of an existing html element

I have a jQuery code to check whether a html element with particular id exists or not. I have written the if and else clause of existing and non existing html element. But when the element exists why jQuery returns the value as undefined ?
You can see the jQuery code below. The variable start_time is defined, because it enters the clause condition but the value is detected as undefined. What is wrong with the code?
var count = 0;
for(i=1; i<=n_day; i++){
count = count + 1 ;
var start_time = jQuery("#txtStartTime_detail"+i);
var end_time = jQuery("#txtEndTime_detail"+i);
var start_location = jQuery("#txtStartLocation_detail"+i);
var end_location = jQuery("#txtEndLocation_detail"+i);
var start_location_coor = jQuery('#txtStartLocation_Coordinates_detail'+i);
var end_location_coor = jQuery('#txtEndLocation_Coordinates_detail'+i);
//var day = jQuery('#txtDay'+i);
if(typeof start_time == 'undefined'){
start_time = '';
}else{
start_time = jQuery("#txtStartTime_detail"+i).val();
alert(start_time);
}
if(typeof end_time == 'undefined'){
end_time = '';
}else{
end_time = jQuery("#txtEndTime_detail"+i).val();
}
if(typeof start_location == 'undefined'){
start_location = '';
}else{
start_location = jQuery("#txtStartLocation_detail"+i).val();
}
if(typeof end_location == 'undefined'){
end_location = '';
}else{
end_location = jQuery("#txtEndLocation_detail"+i).val();
}
if(typeof start_location_coor == 'undefined'){
start_location_coor = '';
}else{
start_location_coor = jQuery('#txtStartLocation_Coordinates_detail'+i).val();
}
if(typeof end_location_coor == 'undefined'){
end_location_coor = '';
}else{
end_location_coor = jQuery('#txtEndLocation_Coordinates_detail'+i).val();
}
requestdetail += '<div class="yellow" id="txtDay'+count+'">Day - '+count+' : '+travel_date+'</div>'
+'<div class="table-responsive table-condensed">'
+'<table class="table borderless">'
+'<tbody>'
+'<tr>'
+'<td class="col-left">Travel time</td>'
+'<td class="col-middle"><input type="text" name="txtStartTime_detail[]" id="txtStartTime_detail"'+count+'" class="timepicker" value="'+start_time+'"/></td>'
+'<td class="col-middle"><input type="text" name="txtEndTime_detail[]" id="txtEndTime_detail'+count+'" class="timepicker" value="'+end_time+'" /></td>'
+'<td class="col-right"><div class="error" id="error_time'+count+'"> </div></td>'
+'</tr>'
+'<tr>'
+'<td class="col-left">Location</td>'
+'<td class="col-middle-2"><input type="text" size="100" name="txtStartLocation_detail[]" id="txtStartLocation_detail'+count+'" class="inputWithImge" value="'+start_location+'" onmouseover="display_text(this)" />'
+ '<img src="'+base_url+'" class="location-icon" alt="Click to search the location" name="location-icon" value="StartLocation_detail'+count+'" title="Click to show map"/>'
+ '</td>'
+'<td class="col-middle-2"><input type="text" name="txtEndLocation_detail[]" id="txtEndLocation_detail'+count+'" class="inputWithImge" value="'+end_location+'" onmouseover="display_text(this)"/>'
+ '<img src="'+base_url+'" class="location-icon" alt="Click to search the location" name="location-icon" value="EndLocation_detail'+count+'" title="Click to show map"/>'
+ '</td>'
+'<td class="col-right"><div class="error" id="error_location'+count+'"> </div></td>'
+'</tr>'
+'</tbody>'
+'<input type="hidden" name="txtStartLocation_Coordinates_detail[]" id="txtStartLocation_Coordinates_detail'+count+'" value="'+start_location_coor+'">'
+'<input type="hidden" name="txtEndLocation_Coordinates_detail[]" id="txtEndLocation_Coordinates_detail'+count+'" value="'+end_location_coor+'">'
+'</table>'
+'</div>';
travel_date = new Date(jQuery("#txtStartDate").val());
travel_date.setDate(startDate.getDate() + i);
travel_date = jQuery.datepicker.formatDate("DD, MM d, yy", new Date(travel_date));
}
the html elements are populated dynamically in codeigniter and returns to browsers as a html String.
here is how I display the html string :
<form name="frm_RRequest" action="#" method="post">
<?php
if(strlen($current_request)>0 || $current_request!=null){
echo $current_request;
echo '<div><input type="button" name="btn_Update" class="button" value="Update" /></div>';
}else{
$site_url = site_url("user/recommendation_request");
echo '<div class="yellow">you have no current request, you can make a new request here >> Recommendation Request</div>';
}
?>
</form>
and here is how the elements are created in codeigniter
'<div class="yellow" id="txtDay'.$count.'">Day - '.$count.' : '.$travel_date.'</div>'
.'<div class="table-responsive table-condensed">'
.'<table class="table borderless">'
.'<tbody>'
.'<tr>'
.'<td class="col-left">Travel time</td>'
.'<td class="col-middle"><input type="text" name="txtStartTime_detail[]" id="txtStartTime_detail"'.$count.'" class="timepicker" value="'.$start_time.'"/></td>'
.'<td class="col-middle"><input type="text" name="txtEndTime_detail[]" id="txtEndTime_detail'.$count.'" class="timepicker" value="'.$end_time.'" /></td>'
.'<td class="col-right"><div class="error" id="error_time'.$count.'"> </div></td>'
.'</tr>'
.'<tr>'
.'<td class="col-left">Location</td>'
.'<td class="col-middle-2"><input type="text" size="100" name="txtStartLocation_detail[]" id="txtStartLocation_detail'.$count.'" class="inputWithImge" value="'.$row->start_location.'" onmouseover="display_text(this)" />'
. '<img src="'.$base_url.'" class="location-icon" alt="Click to search the location" name="location-icon" value="StartLocation_detail'.$count.'" title="Click to show map"/>'
. '</td>'
.'<td class="col-middle-2"><input type="text" name="txtEndLocation_detail[]" id="txtEndLocation_detail'.$count.'" class="inputWithImge" value="'.$row->end_location.'" onmouseover="display_text(this)"/>'
. '<img src="'.$base_url.'" class="location-icon" alt="Click to search the location" name="location-icon" value="EndLocation_detail'.$count.'" title="Click to show map"/>'
. '</td>'
.'<td class="col-right"><div class="error" id="error_location'.$count.'"> </div></td>'
.'</tr>'
.'</tbody>'
.'<input type="hidden" name="txtStartLocation_Coordinates_detail[]" id="txtStartLocation_Coordinates_detail'.$count.'" value="'.$start_location_coor.'">'
.'<input type="hidden" name="txtEndLocation_Coordinates_detail[]" id="txtEndLocation_Coordinates_detail'.$count.'" value="'.$end_location_coor.'">'
.'</table>'
.'</div>';
Your problem is in the strings that you use to create the content.
You have
... id="txtStartTime_detail"'+count+'".....
which will create the ID
...id = "txtStartTime_detail"1"...
You just have to remove the extra double quotes "'+count"' should be '+count+'"

Symfony Redirect for some action

I use this dashboard and when I pushed button "Add New" create dynamics button save, I find this button in js file this dasboard:
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[0] + '">';
jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[1] + '">';
jqTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[2] + '">';
jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[3] + '">';
jqTds[4].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[4] + '">';
jqTds[5].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[5] + '">';
jqTds[6].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[6] + '">';
jqTds[7].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[7] + '">';
jqTds[8].innerHTML = '<a class="edit" href="??????????">Save</a>';
jqTds[9].innerHTML = '<a class="cancel" href="?????????">Cancel</a>';
}
and my question
I have routing for add new developer how I put my routing this "href=" or maybe redirect for my creatAction ????
If you want use that way,
put hidden input and then get value via jQuery
HTML
<input type="hidden" id="form-url" val="{{ path('my_route') }}">
in edit row fundtion
jqTds[9].innerHTML = '<a class="cancel" href="'+$('#form-url').val();+'">Cancel</a>';

Categories