dynamically generate a list dropdown in javascript from JSON data - javascript

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>');
}*/
}

Related

why does my script wont append the ul in my class?

i have this script to append new message from client but it wont append to my ul list, don't know why but when i check in console it print 2 object from class chat-message one there is the ul and one not, but from this script it only append to .chat-message class one time and in the html i only have the container class and in the new .chat-message i empty my .message-user class and only add the ul tag to used it later when append new data
here is the html script
<div class="chat-message">
</div>
here is my js script.
function get_message_data(){
$(".client-message").on("click",function(){
$.ajax({
url:"msg",
method:"get",
data:{"data":this.id},
success:function(response){
data_response = JSON.parse(response)
add_data = add_data +
'<div class="header-message" value='+data_response[0].line_name+'>'+
'<div class="image-profile">'+
'<img src='+data_response[0].line_image+' alt="image-message">'+
'</div>'+
'<div class="username-profile">'+
'<label>'+data_response[0].line_name+'</label>'+
'</div>'+
'<button id="btn-exit" onclick="exit_app()">X</button>'+
'</div>'+
'<div class="message-user">'+
'<ul>'+
'</ul>'+
'</div>'+
'<div class="footer-message-send">'+
'<div class="file-send">'+
'<label for="btn-file-input"><i class="fas fa-archive"></i></label>'+
'<button id="btn-file-input" style="display:none;"></button>'+
'<input type="file" id="file-input" style="display: none;">'+
'</div>'+
'<div class="send-message">'+
'<input type="text" name="yellow" class="textinput">'+
'</div>'+
'<div class="button-send">'+
'<label for="send-message-admini"><i class="fa fa-paper-plane" aria-hidden="true"></i></label>'+
'<button id="send-message-admini" style="display:none;" type="button" value="submit"></button>'+
'</div>'+
'</div>'
$(".chat-message").empty();
$(".chat-message").append(add_data);
for(var i = 0; i < data_response.length; i++){
var add_template =
'<li class="message-send-client">'+
'<div class="client-message-send">'+
'<div class="message-header-send">'+
'<img src='+data_response[i].line_image+'>'+
'</div>'+
'<div class="user-message">'+
'<label>'+data_response[i].line_name+'</label>'+
'<p>'+data_response[i].message+'</p>'+
'</div>'+
'</div>'+
'</li>'+
$('.message-user').find('ul').append(add_template)
}
send_admin_message();
var interval = setInterval(function(){
update_message();
},3000)
}
})
id_user = this.id
})
}
here make it like this
see in ul i have added the templatedata
success:function(response){
data_response = JSON.parse(response)
var add_template = '';
for(var i = 0; i < data_response.length; i++){
// here this is creating list
add_template +=
'<li class="message-send-client">'+
'<div class="client-message-send">'+
'<div class="message-header-send">'+
'<img src='+data_response[i].line_image+'>'+
'</div>'+
'<div class="user-message">'+
'<label>'+data_response[i].line_name+'</label>'+
'<p>'+data_response[i].message+'</p>'+
'</div>'+
'</div>'+
'</li>'+
}
add_data = add_data +
'<div class="header-message" value='+data_response[0].line_name+'>'+
'<div class="image-profile">'+
'<img src='+data_response[0].line_image+' alt="image-message">'+
'</div>'+
'<div class="username-profile">'+
'<label>'+data_response[0].line_name+'</label>'+
'</div>'+
'<button id="btn-exit" onclick="exit_app()">X</button>'+
'</div>'+
'<div class="message-user">'+
'<ul>'+add_template+
'</ul>'+
'</div>'+
'<div class="footer-message-send">'+
'<div class="file-send">'+
'<label for="btn-file-input"><i class="fas fa-archive"></i></label>'+
'<button id="btn-file-input" style="display:none;"></button>'+
'<input type="file" id="file-input" style="display: none;">'+
'</div>'+
'<div class="send-message">'+
'<input type="text" name="yellow" class="textinput">'+
'</div>'+
'<div class="button-send">'+
'<label for="send-message-admini"><i class="fa fa-paper-plane" aria-hidden="true"></i></label>'+
'<button id="send-message-admini" style="display:none;" type="button" value="submit"></button>'+
'</div>'+
'</div>'
$(".chat-message").empty();
$(".chat-message").append(add_data);
}

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

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
}

Escaping Quotes does not work in JavaScript innerHTML

I have got a quite bad "quoting situation" at the moment.
I am working inside an innerHTML and inside this i want to call a function on the onClick-Event, which leaves me with the following:
modalEl.innerHTML = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="sendUpdatedGroup(id, document.getElementById("groupName").value, document.getElementById("groupDesc").value)">Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="deactivateOverlay()">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
I already tried escaping the quotes and using HTML-Quotes, but neither worked.
Instead of HTML encoding the single quotes, just JavaString escape your single quotes.
'<button type="button" class="mui-btn mui-btn--raised"
onclick="sendUpdatedGroup(id, document.getElementById(\'groupName\').value,
document.getElementById(\'groupDesc\').value)">Speichern</button>'+
If you don't want to get into escaping hell , don't use event handlers as HTML attributes (which we stopped doing about 10 years ago).
modalEl.innerHTML = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" >Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
var buttons = modalEl.querySelectorAll('.formbuttons button');
buttons[0].addEventListener('click', function() {
sendUpdatedGroup(id,
document.getElementById('groupName').value,
document.getElementById('groupDesc').value))
});
buttons[i].addEventListener('click', deactivateOverlay);
You forgot to declare desc and name look at this fiddle totally works https://jsfiddle.net/L3Lfweh9/
HTML
<div id="message">
</div>
<button id="bttn">
click here
</button>
JS
var name = "one";
var desc = "two";
var text = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="sendUpdatedGroup(id, document.getElementById("groupName").value, document.getElementById("groupDesc").value)">Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="deactivateOverlay()">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
document.getElementById("bttn").addEventListener("click", function(){
document.getElementById("message").innerHTML = text;
}, false);

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>';

jQuery getting back NaN and [object Object] from variables

I have some problems getting my script to work. My script calculates the number of orders and the weight of each order. My form is actually created by javascript when pressed the "New Line" button. I am trying to make it so whenever 3 values (number of items, number of items in a box, number of boxes per order) are filled in, it automatically gives you the total number of orders. Also, when given the weight of a single item, it gives you the total weight of the order. All this happens on keyup using jquery. I need help only in the javaScript part. I handle my form with AJAX later on and everything worked but it broke when I tried to implement this.
Whenever I use alert() to see what values my code is assigning to the updateForm() function I get for alert($totalitems) -> [object Object] and alert($weightperpal) -> NaN. Could anybody help me solve this? Heres my code:
HTML:
<button id="addLine" type="submit" class="btn red">Add Line</button>
JavaScript:
$("#addLine").click(function(e){
e.preventDefault();
lineNum++;
var cont = '<div class="control-group">'+
'<label class="control-label">Total # of items</label>'+
'<div class="controls">'+
'<input type="text" placeholder="" class="m-wrap medium orderField" name="totalitems'+lineNum+'" id="totalitF" no="'+ lineNum +'"/>'+
'<span class="help-inline" style="font-size:10px; font-style:italic;">Not mandatory</span>'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label">Items per box</label>'+
'<div class="controls">'+
'<input type="text" placeholder="0" class="m-wrap medium orderField" name="ipb'+lineNum+'" id="itemspbF" no="'+ lineNum +'"/>'+
'<span class="help-inline" style="font-size:10px; font-style:italic;">#</span>'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label">Boxes per order</label>'+
'<div class="controls">'+
'<input type="text" placeholder="0" class="m-wrap medium orderField" name="bpp'+lineNum+'" id="boxesppF" no="'+ lineNum +'"/>'+
'<span class="help-inline" style="font-size:10px; font-style:italic;">#</span>'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label">Weight per Item</label>'+
'<div class="controls">'+
'<input type="text" placeholder="0" class="m-wrap medium orderField" name="wpi'+lineNum+'" id="weightpiF" no="'+ lineNum +'"/>'+
'<span class="help-inline" style="font-size:10px; font-style:italic;">#</span>'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label">Total number of Orders</label>'+
'<div class="controls">'+
'<input type="text" placeholder="" class="m-wrap medium orderField" name="pallets'+lineNum+'" id="palletsF" no="'+ lineNum +'"/>'+
'<span class="help-inline" style="font-size:10px; font-style:italic;"># of pallets</span>'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label">Weight per order</label>'+
'<div class="controls">'+
'<input type="text" placeholder="" class="m-wrap medium orderField" name="wpp'+lineNum+'" id="weightppF" no="'+ lineNum +'"/>'+
'<span class="help-inline" style="font-size:10px; font-style:italic;">Total number of boxes</span>'+
'</div>'+
'</div>'+
'</div>';
$(document).on('keyup','.weightpiF',function(){
var valueField = $(this).attr('no');
updateFormRoe(valueField);
});
$(document).on('keyup','.weightppF',function(){
var valueField = $(this).attr('no');
updateFormRoe(valueField);
});
$(document).on('keyup','.itemspbF',function(){
var valueField = $(this).attr('no');
updateFormRoe(valueField);
});
$(document).on('keyup','.boxesppF',function(){
var valueField = $(this).attr('no');
updateFormRoe(valueField);
});
function updateFormRoe(number){
alert(number);
var $totalitems = $('#totalitF'+number);
alert($totalitems);
var $itemspb = $('#itemspbF'+number).val();
var $boxespp = $('#boxesppF'+number).val();
var $weightperitem = $('#weightpiF'+number).val();
var $itemsinpallet = $itemspb * $boxespp;
var $totalpals = $totalitems / $itemsinpallet;
var $weightperpal = ($itemsinpallet) * $weightperitem;
alert($weightperpal);
if($totalitems !== '' && $itemspb !== '' && $boxespp !== ''){
if($totalpals == Infinity){
$('#palletsF'+number).val('0');
}else{
$('#palletsF'+number).val($totalpals);
}
$('#weightppF'+number).val($weightperpal);
}
}
Thanks in advance!
None of your selectors like $('#totalitF'+number) will work, because you're not appending numbers to your IDs. Instead of:
id="totalitF" no="'+ lineNum +'"/>'
it should be:
id="totalitF'+ lineNum +'" data-no="'+ lineNum +'"/>'
You shouldn't create your own attributes. If you want to add additional attributes to an element, use data- attributes. Then in jQuery you can access this as
$(this).data('no')
to get the value. Use this in your other functions in place of $(this).attr('no').

Categories