Undefined value; include var value into table cell - javascript

function stateChanged() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
var showdata = xmlHttp.responseText;
// var showdata = "test\ntest2"
var res = showdata.split(",");
var html = ' <table border="1" width="80%" class ="bordered"> <tr><th></th><th>Taught by</th></tr>';
for (var i = 0; i < res.length - 1; i++) {
// window.alert("value gotten " + res[i]);
var test = res[i];
// document.cookie= "teacher"= test;
// html += '<tr><td><input type="radio" name="vList" value="'+ "122222" + '"><br></td><td>' + test + '</td></tr>';
html += '<tr><td><input type="radio" name="vList" value="'+ test.value + '"><br></td><td>' + test + '</td></tr>';
}
I am trying to put the value of res[i] into my radio button so that the user can select, but I seem to always get undefined value. What am I doing wrongly here?
Test has a value and I can print out into another cell but not as a value for the radio button.
Still unresolved, please kindly assist.
Edit: using test will result in the table looking like these.

What is test?
if test is a string then:
html += '<tr><td><input type="radio" name="vList" value="'+ test + '"><br></td><td>' + test + '</td></tr>';
if test is an object with a property called value and label then:
html += '<tr><td><input type="radio" name="vList" value="'+ test.value + '"><br></td><td>' + test.label + '</td></tr>';
if test is a array then with index 0 containing the value and 1 containing the label:
html += '<tr><td><input type="radio" name="vList" value="'+ test[0] + '"><br></td><td>' + test[1] + '</td></tr>';
In Short do this:
html += '<tr><td><input type="radio" name="vList" value="'+ test + '"><br></td><td>' + test + '</td></tr>';

Related

JS variable not working in AJAX success

Fetched data from database with php and ajax, Everything is ok except note variable is empty.Can somebody find out the issue why note value is not going to display. How can i fix it.
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
var note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
This is the output
database table
JSON output
{"groupData":{"id":"23","group_name":"Group B"},"results":
[{"id":"2","team_id":"4","team":"Team
B","player":"Deno","result":"14","note":"Lost"},
{"id":"3","team_id":"4","team":"Team
B","player":"Niob","result":"26","note":"Lost"},
{"id":"4","team_id":"4","team":"Team
B","player":"Skion","result":"76","note":"lost"},
{"id":"5","team_id":"5","team":"Team
C","player":"Bela","result":"47","note":"won"},
{"id":"6","team_id":"5","team":"Team
C","player":"yomi","result":"57","note":"won"}]}
You should set note value infront of cats[team].forEach(function(element) {}). Hope to help, my friend :))
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
var note;
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}

Binding Dropdown in ASP.NET

I have problem binding data in dropdown for adding data in grid. I want to pass airline name in the agent column. The dropdown value can't be changed How do I change the value of dropdown. Only the first index airline is shown in the dropdown.
Controller:
public ActionResult Create()
{
ViewBag.AID = db.Airlines.ToList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection frmcoll, ICollection<string> hddrowpindex)
{
foreach (var row in hddrowpindex)
{
InternationalArrival stock = new InternationalArrival();
stock.AgentName = How to take selected textvalue Name from dropdown???;
stock.AgentCode = (frmcoll["AgentCode-" + row]).ToString();
stock.ArrivalDate = DateTime.ParseExact(frmcoll["ArrivalDate-" + row], "yyyy-MM-dd", null);
stock.ForPAX = Convert.ToInt32(frmcoll["ForPAX-" + row]);
stock.IndPAX = Convert.ToInt32(frmcoll["IndPAX-" + row]);
db.InternationalArrivals.Add(stock);
db.SaveChanges();
}
return RedirectToAction("Index");
}
View:
var sectorlist=(List<CompetitorAnalysis.Models.Airline>) ViewBag.AID;
string sectorddl= "";
foreach(var sector in sectorlist)
{
sectorddl = "<option value='"+sector.Name+"'>"+sector.Name+"</option>";
<input type="hidden" id="hddsector" value="#sectorddl" />
}
<script>
var d = new Date();
var rowindex = 1;
function addItem() {
msg = '<tr><input type="hidden" name="hddrowpindex" value="' + rowindex + '" class="rowcount"/>';
//added for bringing dropdown
msg += '<td class="center-fix" >';
msg += '<select>';
msg += document.getElementById("hddsector").value;
msg += '</select>'
msg += '</td>';
msg += '<td class="nocap-col-sm-2">';
msg += '<input type="text" class="form-control" style="text-transform:uppercase" name="AgentCode-' + rowindex + '" id="AgentCode-' + rowindex + '" placeholder="Code"/>';
msg += '</td>';
msg += '<td class="nocap-col-sm-2">';
msg += '<input type="text" class="form-control datepicker" name="ArrivalDate-' + rowindex + '" id="ArrivalDate-' + rowindex + '" placeholder="YYYY/MM/DD"/>';
msg += '</td>';
msg += '<td class="nocap-col-sm-2">';
msg += '<input type="text" class="form-control" name="ForPAX-' + rowindex + '" id="ForPAX-' + rowindex + '" placeholder="ForPAX" value="0" />';
msg += '</td>';
msg += '<td class="nocap-col-sm-2 center-fix">';
msg += '<input type="text" class="form-control" name="IndPAX-' + rowindex + '" id="IndPAX-' + rowindex + '" placeholder="IndPAX" value="0" />';
msg += '</td>';
msg += '<td class="nocap-col-sm-2 center-fix" style="text-align:center;"><i class="fa fa-trash"></i>Remove</span>';
msg += ' <span id="perror-' + rowindex + '" style="display:none"><i class="fa fa-exclamation-triangle faa-exclamation-triangle animated"></i></span></td>';
msg += '</tr>';
$('table#portfolio tbody').append(msg);
rowindex++;
}
</script>
How do I make the dropdown populated. In this case the first data of Airline table is shown in the dropdown. And how do i get the selected value in the Post method of controller.
Your immediate problem is inside of your loop:
var sectorlist=(List<CompetitorAnalysis.Models.Airline>) ViewBag.AID;
string sectorddl= "";
foreach(var sector in sectorlist)
{
sectorddl = "<option value='"+sector.Name+"'>"+sector.Name+"</option>";
<input type="hidden" id="hddsector" value="#sectorddl" />
}
It appears to me that you are attempting to build an html string for a select list dropdown. However, on each pass of the loop, you are overwriting the value in sectorddl by using sectorddl = "some value" Perhaps you mean sectorddl += "some value"?
As an aside, this really isn't a good way to build a dropdown in ASP.NET MVC.
You can simplify your code by doing something like this:
Controller
var items = from aid in db.Airlines
select new SelectListItem
{
Text = aid.Name, //or whatever the field names are
Value = aid.Id
};
ViewBag.AID = items.ToList();
View
#Html.DropDownList(model => model.SelectedAirlineId,
new SelectList(ViewBag.AID, "Value", "Text"))

JS to generate HTML table, but one first row cell won't get value, comes up as 'undefined'

So I have a function that's below (I broke the lines after innerHTML so it's easier to see) and the forloop generates a table, with id's for each tags. I'm wanting to calculate the total of each item(quantity * price).
The function works fine after the first row, but first row's total returns an undefined value, which i'm assuming is because the variables are declared later on.
How could i possible solve this issue, and work out the total?
The relevant JS:
function load() {
for (var i = 0; i <= localStorage.length - 1; i++) {
var key = localStorage.key(i);
document.getElementById(key).setAttribute('checked', 'checked');
document.getElementById("content").innerHTML += "<tr>
<td><input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled /></td>
<td id='quantity-" + i + "'>
<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button></td>
<td id='price-" + i + "'></td><td>" + totalPrice + "</td>
<td><button class='delete' id='delete-" + i + "'>Delete</button></td></tr>";
var name = $('#name-' + i).val();
var id = $('#' + name);
var price = id.data('price');
var quantity = document.getElementById('input-' + i);
var quantityValue = quantity.value;
var total = price * quantityValue;
document.getElementById('price-' + i).innerHTML = '£' + price;
var getQuantity = $('#input-' + i).val();
var totalPrice = price * getQuantity;
}
}
Local storage's data:
key: photo2, value: checked
key: photo6, value: checked
key: photo7, value: checked
You are updating total after appending dom. you need to calculate everything before updating it to DOM.
function load() {
for (var i = 0; i <= localStorage.length - 1; i++) {
var key = localStorage.key(i);
var id = $('#' + key);
var price = id.data('price'); // assuming this will be there in dom
var quantityValue = 1; // adding this 1 in table
var total = price * quantityValue;
document.getElementById('price-' + i).innerHTML = '£' + price;
var getQuantity = 1;
var totalPrice = price * getQuantity;
document.getElementById(key).setAttribute('checked', 'checked');
document.getElementById("content").innerHTML += "<tr>
<td><input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled /></td>
<td id='quantity-" + i + "'>
<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button></td>
<td id='price-" + i + "'>£" + price + "</td><td>" + totalPrice + "</td>
<td><button class='delete' id='delete-" + i + "'>Delete</button></td></tr>";
}
}

how to use image tag

Can someone help me out in inserting an image in the below function. I've used a json object that returns values for campaignid and campaignname.
<script>function searchedCampaigns(data) {
if (data[0].length > 0) {
var searchcmp = "";
for (var j = 0; j < data[0].length; j++) {
var input = document.createElement("input");
console.log(input.name);
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '/>' +
**// image to be inserted here**
+ data[0][j].campaignName + '<br/>'; // value
}
$("#newcamp").html(searchcmp);
}}</script>
output should be this
I'm getting the checkbox as well as the campaign name. I want the image in between these two.
As simple as this..
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '/>' +
'<img src="'+yourimageurlfromdata+'"/>'+
'data[0][j].campaignName + '<br/>';
I suggest you a code like this one:
<input type="checkbox"><img src="Image.PNG">Test</img></input>
Also, based on your code, it can be updated like this:
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '><img src=' + YOUR_URL_LOCATION + ' />' + data[0][j].campaignName + '</input><br/>';
Where YOUR_URL_LOCATION, can be in the JSON or somewhere else.
It's going to display something like this:

passing value to a dynamic created function in javascript

I am having some problems while creating a dynamic webpage in javascript.
My idea is to read a list of events and people signed up on them. I create a page with all events (each event is a button) and clicking on one of them, see the list of users.
This works fine. But now, I am adding a button to export some of these users to an excel file. And I want to add a button with an onClick function like this:
...onclick=functionÇ(id_Event, numberOfUsers, listOfUsers)...
Inside of the html code generated by javascript. I found some problems also doing like this so I changed so:
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
I created a global array called arrayNumberUSersInEvents in which I am adding in each possition, people subscribed. i, is the id counter for each position.
But even this, I am getting an undefined while reading the value of the firsdt parameter. I think it is a problem of dynamic data, I am not executing the function I want to each time I click the button. Do you know how to do something like this?
To sum up: My problem is that I want to pass some arguments to a function in a dynamic created page. I don't know how to pass the data and read the correct parameters inside.
I added my code because one user asked for it:
for(i = 0; i < element.length; i++){
$(".eventsControl").append(
'<li id="listControl'+ element[i].id_Event +'">'+
'<a href="#EventControl' + element[i].id_Event + '"' + 'data-transition="slidedown">'+
'<img class="crop" src= "' + element[i].image + '" />'+
'<h2>' + element[i].name + '</h2>'+
'<p>' + "Desc: " + element[i].description +'</p>'+
'</a>'+
'</li>'
).listview('refresh');
//console.log(response);
//BUCLE for setting all users in each event. Better use some string and after, join all of them
header = ' <div width="100%" data-theme = "e" data-role="page" id='+ element[i].id_Event +
' data-url="EventControl' + element[i].id_Event + '"> ' +
' <div data-theme = "a" data-role="header"><h1>Lista de Asistencia</h1> ' +
' </div>'+
' <div data-role="content"> ' +
' <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center">' +
' <div style="width: 500px; margin: 0 auto;">';
//header = header + '<input data-theme = "c" onclick="saveExcelFunctionControl(this)" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
eval('var numberUsers' +element[i].id_Event + "=1");
arrayNumberUsersInEvents[i] = 0;
if(response.length>0){
bucle = ' <table width="100%" border="1" align="left"><tr>'+
' <th>Nombre</th>'+
' <th>Primer apellido</th>'+
' <th>Segundo apellido</th>'+
' <th>NIF</th>'+
' <th>Asistencia</th>'+
' </tr>';
for(iData = 0; iData < response.length; iData++){
if(element[i].id_Event == response[iData].id_Event){
//console.log(response[iData].name);
bucle = bucle + '<tr><td>'+ eval('numberUsers' +element[i].id_Event) +'</td><td>'+ response[iData].name +'</td><td>'+
response[iData].surname1 +'</td><td>'+
response[iData].surname2 +'</td><td>'+
response[iData].NIF + '</td>'+
'<td> '+
'<input type="checkbox" id="checkBox'+element[i].id_Event+'_'+iData+'" name="option'+iData+'" value="'+iData+'"> '+
'</td>'+
'</tr>';
eval('numberUsers' +element[i].id_Event + "++");
arrayNumberUsersInEvents[i] = arrayNumberUsersInEvents[i]+1;
}
}
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(\""element[i].id_Event "\","" + numberUsers + "\",\"" + response+ "\"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(""+numberUsers+"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
bucle = bucle + '</table>';
$("#controlList").after(header + bucle + '<div id=added'+element[i].id_Event+'></div>');
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
}
}
},
error: function(xhr, status, message) { alert("Status: " + status + "\nControlGetEventsRegister: " + message); }
});
You can use closure to pass parameters to dynamically created onclick handler:
input.onclick = (function() {
var arr = arrayNumberUsersInEvents[i];
var resp = response;
return function() {
saveExcelFunctionControl(arr, resp);
}
})();
How do JavaScript closures work?
var td = document.createElement("td");
var input = "<input type='button' value='Exportar a Excel CSV'";
input+= "onclick='saveExcelFunctionControl(""" +arrayNumberUsersInEvents[i]+""","""+ response+""");' />";
};
td.textContent=input;
document.getElementById("added"+element[i].id_Event).appendChild(td);
try this way

Categories