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"))
Related
what is the way when add new row in table to make script connect with element in new row not only at first row? the script connect only with element "textbox" in the first row only
function GetSelectedvalues (el) {
var select = document.getElementsByClassName ('js-example-basic-multiple')[0];
var result = "";
var options = select && select.options;
var opt;
for (var i = 0; i < select.options.length; i++) {
opt = options[i];
var isSelected = select.options[i].selected;
isSelected = (isSelected)? opt.value : "0";
result += isSelected ;
}
document.getElementById ('textbox').value=result;
}
//add row
function addmaintable() {
$('#datatablereqstsched').append(
'<tbody>' +
'<tr class="parent" id="parent">' +
// here text box
'<td width="60%"><div class="input-group"> <label class="ckbox mg-t-10" title="Daily" ><input type="checkbox" id="chk1" onclick="check(\'chk1\')" ><span calss="mg-t-0">Daily</span> </label><div class="input-group-prepend" style="width:80%"><select class="js-example-basic-multiple col-md-4 form-control" name="states[]" multiple="multiple"style="width: 100%" onchange="GetSelectedvalues(event);" > <option value="1">MON</option> <option value="2">TUE</option> <option value="3">WED</option> <option value="4">THU</option><option value="5">FRI</option><option value="6">SAT</option><option value="7">SUN</option> </select></div><input type="text" class="form-control txtv" value="" placeholder="0000000" id="textbox" disabled></div> </td>' +
'</tr>' +
'</tbody>');
$('.js-example-basic-multiple').select2();
}
function check(chk) {
var checkb = document.getElementById(chk);
if (checkb.checked == true) {
document.getElementById('textbox').value = "1234567";
$(".js-example-basic-multiple").prop("disabled", true);
}
else {
document.getElementById('textbox').value = "0000000";
$(".js-example-basic-multiple").prop("disabled", false);
$(".js-example-basic-multiple").val(null).trigger('change');
}
}
You are explicitly targetting the first select each time you call the GetSelectedvalues function:
var select = document.getElementsByClassName ('js-example-basic-multiple')[0];
I think you should rather leverage the event argument to get the current changing select:
const tBody = '<tbody>'
+ '<tr class="parent" id="parent">'
+ '<td width="60%">'
+ '<div class="input-group">'
+ '<label class="ckbox mg-t-10" title="Daily">'
+ '<input type="checkbox" id="chk1" onclick="check(\chk1\)" >'
+ '<span calss="mg-t-0">Daily</span>'
+ '</label>'
+ '<div class="input-group-prepend" style="width:80%">'
+ '<select class="js-example-basic-multiple col-md-4 form-control" name="states[]" multiple="multiple" style="width: 100%" onchange="GetSelectedvalues(event);">'
+ '<option value="1">MON</option>'
+ '<option value="2">TUE</option>'
+ '<option value="3">WED</option>'
+ '<option value="4">THU</option>'
+ '<option value="5">FRI</option>'
+ '<option value="6">SAT</option>'
+ '<option value="7">SUN</option>'
+ '</select>'
+ '</div>'
+ '<input type="text" class="form-control txtv" value="" placeholder="0000000" id="textbox" disabled>'
+ '</div>'
+ '</td>'
+ '</tr>'
+'</tbody>'
function GetSelectedvalues(event) {
// Here you are selecting only the first select with the class "js-example-basic-multiple"
var select = document.getElementsByClassName('js-example-basic-multiple')[0];
// You are better off selecting the current changing select using the argument event
select = event.target;
var result = "";
var options = select && select.options;
var opt;
for (var i = 0; i < select.options.length; i++) {
opt = options[i];
var isSelected = select.options[i].selected;
isSelected = (isSelected) ? opt.value : "0";
result += isSelected;
}
document.getElementById('textbox').value = result;
}
//add row
function addmaintable() {
$('#datatablereqstsched').append(tBody);
$('.js-example-basic-multiple').select2();
}
Edit
Now you need a way to know which textbox to update, based on currently changing select. And the same thing for all other inputs, like the checkbox at the top.
One way to do that could be this:
const tBodyTemplate = '<tbody>'
+ '<tr class="parent" id="parent">'
+ '<td width="60%">'
+ '<div class="input-group">'
+ '<label class="ckbox mg-t-10" title="Daily">'
+ '<input type="checkbox" id="chk" onclick="check(chk)" >'
+ '<span calss="mg-t-0">Daily</span>'
+ '</label>'
+ '<div class="input-group-prepend" style="width:80%">'
+ '<select data-target="textbox" class="js-example-basic-multiple col-md-4 form-control" name="states[]" multiple="multiple" style="width: 100%" onchange="GetSelectedvalues(event);">'
+ '<option value="1">MON</option>'
+ '<option value="2">TUE</option>'
+ '<option value="3">WED</option>'
+ '<option value="4">THU</option>'
+ '<option value="5">FRI</option>'
+ '<option value="6">SAT</option>'
+ '<option value="7">SUN</option>'
+ '</select>'
+ '</div>'
+ '<input type="text" class="form-control txtv" value="" placeholder="0000000" id="textbox" disabled>'
+ '</div>'
+ '</td>'
+ '</tr>'
+'</tbody>'
function GetSelectedvalues(event) {
// Here you are selecting only the first select with the class "js-example-basic-multiple"
var select = document.getElementsByClassName('js-example-basic-multiple')[0];
// You are better off selecting the current changing select using the argument event
select = event.target;
var textboxId = select.dataset.target;
var result = "";
var options = select && select.options;
var opt;
for (var i = 0; i < select.options.length; i++) {
opt = options[i];
var isSelected = select.options[i].selected;
isSelected = (isSelected) ? opt.value : "0";
result += isSelected;
}
document.getElementById(textboxId).value = result;
}
let rowCount = 0;
//add row
function addmaintable() {
rowCount++;
var tBody = tBodyTemplate
.replace(/textbox/g, 'textbox' + rowCount)
.replace(/chk/g, 'chk' + rowCount);
$('#datatablereqstsched').append(tBody);
}
function check(v) {
console.log(v);
}
$('#add-row').click(addmaintable);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="datatablereqstsched"></table>
<button id="add-row">Add one row</button>
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++;
});
}
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>';
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
In the below i have a a div with employee names and ahave to assign a grade for them,my question is that i have get the empid for all the selected values in getgrade_values function.Using jquery how to get the ids of the drop down box with its value where the values are selected when on click of evaluate function
function getgrade_values(empid)
{
var ele='<select id="'+ empid +'" name="emp" style="width:40px;margin:0px 0pt;" >';
ele += '<option value=""></option>';
ele += '<option value="A">A</option>';
ele += '<option value="B">B</option>';
ele += '<option value="C">C</option>';
ele += '<option value="D">D</option>';
ele += '<option value="E">E</option>';
ele += '<option value="F">F</option>';
ele += '</select>';
return ele;
}
function sendparams(data)
{
if(data.status == 1)
{
var ele='<tr id="std"><td><b>Evaluate:</b></label> </td></tr>';
for(var l=0;l<data.emparr.length;l++)
{
ele += '<tr><td><div id="'+ data.emparr[l].id +'">' + data.emparr[l].name + "</td><td>" + getgrade_values(data.emparr[l].id) + '</div></td></tr>';
ele+= '<input type="button" value="Evaluate" onclick="evaluate();"';
}
}
var select = $('select[name="emp"]')
var empId = select.attr('id')
alert('empId = '+empId)
select.children('option:selected').each(function() {
alert('grade selected = ' + $(this).val())
})
DEMO : http://jsfiddle.net/hdTEP/
Currently, you will have 2 elements with id="<employeeId>". As ids should be unique across an entire page, you should consider appending the type of element you are representing, for example id="<employeeId>_gradeInput" for your grade dropdown. Next, for each user it seems like you have a button to submit a grade. I would call evaluate with the employee id associated with that button.
function getgrade_values(empid){
var ele='<select id="'+ empid +'_gradeInput" name="emp" style="width:40px;margin:0px 0pt;" >';
..//Remaining code
}
function sendparams(data) {
if (data.status == 1) {
var ele =
'<tr id="std">' +
'<td>' +
'<b>Evaluate:</b>' +
'</td>' +
'</tr>';
for (var l = 0; l < data.emparr.length; l++) {
var employeeId = data.emparr[l].id;
ele +=
'<tr>' +
'<td>' +
'<div id="' + employeeId + '_divContainer">' +
data.emparr[l].name +
'</div>'
'</td>' +
'<td>' +
getgrade_values(employeeId)
'</td>' +
'</tr>';
ele += '<input type="button" value="Evaluate"
onclick="evaluate(' + employeeId + ');"';
}
}
function evaluate(employeeId){
var gradeValue = $('#' + employeeId + '_gradeInput').val();
..//Your other evaluate code here
}