I have a button and onclick of that button, i am running a AJAX call and getting values from another jsp page. My rows are indexed.
<%
List<DiskSheet> ds1 = new ArrayList<DiskSheet>();
if (request.getParameter("numLLP") != null && !request.getParameter("numLLP").isEmpty()) {
int numLLP = Integer.valueOf(request.getParameter("numLLP"));
for (int i=0;i<numLLP;i++) {
DiskSheet d = new DiskSheet();
d.setCH5Limiter(request.getParameter("limiter_"+i));
d.setMfrPrice(request.getParameter("diskvalues_"+i));
d.setDiskCyc(request.getParameter("diskcyc"));
ds1.add(d);
}
request.getSession().setAttribute("engine" + request.getParameter("diskid"), ds1);
}
<%
List<DiskSheet> ds = (List<DiskSheet>) request.getSession().getAttribute("engine" + request.getParameter("diskid"));
if (ds == null) {
ds = new ArrayList<DiskSheet>();
}
String disksheet = request.getParameter("disksheet");
if (disksheet != "") {
String engine = request.getParameter("Engines");
if (ds.size() == 0) {
ds = DiskSheet.getLLPEngine(engine);
}
%>
<div><input type="text" style="text-align:right;" name="limiter_<%=i%>" id="limiter" class="limiter" value="<%=airs.getCH5Limiter()%>" size="10" onblur="getDiskSheetCyc()"></div>
<div><input type="hidden" class="diskvalues" id="diskvalues" name="diskvalues_<%=i%>" size="10" value="<%=airs.getMfrPrice()%>" onblur="getDiskSheetCyc()"></div>
<div><input type="text" class="diskcyc" id="diskcyc" name="diskcyc" size="10" value="<%=airs.getDiskCyc()%>" onblur="getDiskSheetCyc()"></div>
I am trying to perform a simple calculation and print the values in the third row however, it only displays the value in one of the cells. Here's what i tried.
function showPopup(diskid){
document.getElementById("popup_win").style.display = 'block';
}
function getDiskSheet(diskid) {
var form = document.getElementById("airplaneForm");
var id = diskid;
var myAjax = new Ajax.Updater("ch5limiteroutput",
"/jsp/Ch5Limiter.jsp", {
asynchronous : true,
postBody : Form.serialize(form),
data: id,
method : 'post',
onComplete : function() {
displayLimiter();
getDiskSheetCyc();
document.getElementById("id").innerHTML = id;
}
});
}
function displayLimiter() {
var form = document.getElementById("airplaneForm");
var limiteroutput = document.getElementById("ch5limiteroutput").innerHTML;
document.getElementById("limiter").innerHTML = limiteroutput;
}
function getDiskSheetCyc(){
var diskvalues = document.getElementsByClassName("diskvalues");
var limiter = document.getElementsByClassName("limiter");
for (var i = 0; i < diskvalues.length; i++) {
var diskval = parseInt(diskvalues[i].value);
var limiter = parseInt(limiter[i].value);
diskcyc = diskval/limiter;
}
document.getElementById('diskcyc').value = diskcyc;
}
<td class="trigger_popup" ><input type="button" id="1" value="Disk Sheet" name="disksheet" class="disksheet" onclick="showPopup(this.id);getDiskSheet(this.id);">
</td>
<div class="popup_win" id="popup_win">
<span class="helper"></span>
<div>
<br>
<div id="TableBox" class="TableBox" style="width: 110%;">
<div>
<div><span class="id" id="id"></span></div>
<div><span class="limiter" id="limiter"></span></div>
</div>
</div>
</div>
</div>
<div id="ch5limiteroutput" style="display: none"></div>
Also tried doing it through jQuery but it doesn't seem to go inside the loop. I am not sure what i am doing wrong here. Any help is greatly appreciated. Thank you.
function getDiskSheetCyc(){
const jQuerytable = jQuery('#TableBox');
const jQueryrow = jQuerytable.find('> div');
jQuery(".jQueryrow").each(function() {
const jQuerythis = jQuery(this);
const diskvalues = parseInt(jQuerythis.find('.diskvalues').val());
const limiter = parseInt(jQuerythis.find('.limiter').val());
const diskcyc = diskvalues/limiter;
if (!isNaN(diskcyc)) jQuerythis.find('.diskcyc').val(diskcyc);
});
}
Your code at present does not make a lot of sense. For a jQuery solution, consider the following code example.
$(function() {
function showPopup() {
$("#popup_win").show();
}
function displayLimiter() {
var limiteroutput = $("#ch5limiteroutput").html();
$("#limiter").html(limiteroutput);
}
function getDiskSheetCyc() {
var diskvalues = $(".diskvalues");
var limiter = $(".limiter");
var diskcyc = 0;
diskvalues.each(function(i, el) {
var diskval = $(el).val() == "" ? parseInt($(el).val()) : 0;
var limiter = $(el).val() == "" ? parseInt($(el).val()) : 0;
if (diskval > limiter) {
diskcyc = diskval / limiter;
}
});
$('#diskcyc').val(diskcyc);
}
function getDiskSheet(diskid) {
var form = $("#airplaneForm");
var id = diskid;
$.post("/jsp/Ch5Limiter.jsp", {
postBody: form.serialize(),
data: id
}, function(results) {
displayLimiter();
getDiskSheetCyc();
$("#id").val(id);
});
}
$("[type='button']").click(function() {
showPopup();
getDiskSheet($(this).attr("id"));
});
});
.popup {
border: 1px solid #ccc;
border-radius: 6px;
width: 340px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="trigger_popup">
<input type="button" id="1" value="Disk Sheet" name="disksheet" class="disksheet">
</td>
</tr>
</table>
<div class="popup window" id="popup_win" style="display: none;">
<span class="helper"></span>
<div>
<br>
<div id="TableBox" class="TableBox" style="width: 110%;">
<div>
<div><span class="id" id="id"></span></div>
<div><span class="limiter" id="limiter"></span></div>
</div>
</div>
</div>
</div>
<div id="ch5limiteroutput" style="display: none"></div>
So this encounters issues all over due to a number of missing elements that were not provided. The basic idea is you want to show a popup, post some data, and then update some content. I don't see where you do anything with data returned from the AJAX call... I am guessing it's just updating the DB with no feedback.
It would be helpful to provide an example of the data that is retuened if you need more help there.
In regards to the calculation, you're on the right path. You just need to make sure the proper fields get populated with the right details. I am assuming this is where the data from the POST gets to be used.
Examine your Network tab in development tools. You should see the POST action, the Headers, and the Response. This should help you identify if you're getting an error in your AJAX or maybe getting different data back than expected.
Related
I'm trying to transform something like this:
firstnameA,lastnameA,emailA
firstnameB,lastnameB,emailB
into a js/jquery variable that I can then post to my php script to insert row by row in a table.
So far I have managed to do this: it splits the input by new line and then by comma, creates a table to make it easy for the user to check their input and in parralel builds an array that I will post to my script for further treatment. The second part is not working at all (building the table works). I have looked at plenty of posts here on how to create multi-dimensional arrays in js but they all require that I know the exact dimensions of the array. However it could be 1,2 or 50 lines.
Here's my code:
(function($) {
$(document).ready(function() {
$('#new_coll').submit(function(e) {
e.preventDefault();
if($("#names").val() != "") {
var table = '<table class="table mt-4"><thead><th>First name</th><th>Last name</th><th>Email address</th></thead><tbody>';
var i = 0;
var j = 0;
var data;
$.each($("#names").val().split(/\r?\n/), function(e, elements) {
table = table+'<tr>';
$.each(elements.split(","), function(e, element) {
table = table+'<td>'+element+'</td>';
data[i][j] = element;
j++;
});
var j = 0;
table = table+'</tr>';
i++;
});
table = table+'</tbody></table>';
var posting = $.post("Connections/colleagues_add.php", data);
$('#results').empty().html(table);
posting.done(function( data ) {
$( "#results" ).append( data );
});
}
});
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="new_coll">
<textarea class="form-control" id="names" placeholder="Event description*" rows="3" required>
firstnameA,lastnameA,emailA
firstnameB,lastnameB,emailB
</textarea>
<button type="submit" id="verify" class="btn btn-primary btn-block">Verify</button>
</form>
<div class="col" id="results"></div>
If you comment out line 16 it works with the table, however creating the array isnt working. My file where it gets posted to is just a $_POST dump.
I'd appreciate any pointers!
Just turn your data into a multi-dimensional array like below, stringify it with JSON.stringify and post it to your php file. In php use json_decode to turn it into an php-array and then go from there with your database stuff.
// SPLIT YOUR DATA BY NEWLINE
const data = document.getElementById("data").value.split("\n");
// BUILD NEW ARRAY
let json = [];
for (let i in data) {
// SPLIT EACH LINE INTO ARRAY
// AND PUSH IT TO NEW ARRAY
json.push(data[i].split(","));
}
// STRINGIFY YOUR NEW ARRAY
console.log(JSON.stringify(json));
<textarea id="data" cols="50">
firstnameA,lastnameA,emailA
firstnameB,lastnameB,emailB</textarea>
I kinda solved it, happy to get more input though!
(function($) {
$(document).ready(function() {
$('#add').hide();
$('#new_coll').submit(function(e) {
e.preventDefault();
if($("#names").val() != "") {
var table = '<table class="table mt-4"><thead><th>First name</th><th>Last name</th><th>Email address</th></thead><tbody>';
var i = 0;
var data = new Array()
$.each($("#names").val().split(/\r?\n/), function(e, elements) {
table = table+'<tr>';
data[i] = new Array();
var j = 0;
$.each(elements.split(","), function(e, element) {
table = table+'<td>'+element+'</td>';
data[i][j] = element;
j++;
});
table = table+'</tr>';
i++;
});
table = table+'</tbody></table>';
$('#results').empty().html(table);
console.log(data);
$('#add').show();
$('#add').click(function(e) {
$('#add').empty().html('<i class="fa fa-spin fa-spinner"></i>');
var posting = $.ajax({ url : 'https://httpbin.org/post',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
posting.done(function( response ) {
$( "#step2" ).append( response );
$('#add').empty().html('Done');
});
posting.fail(function( response ) {
$('#add').empty().html('Error');
});
});
}
});
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="new_coll">
<div class="form-row mb-2">
<div class="col">
<textarea class="form-control" id="names" placeholder="Event description*" rows="3" required>a1,a2,emaila
b1,b2,emailb</textarea>
</div>
</div>
<div class="form-row mt-4">
<div class="col">
<button type="submit" id="verify" class="btn btn-primary btn-block">Verify</button>
</div>
</div>
</form>
<div class="form-row mb-2">
<div class="col" id="results">
</div>
<div class="col mt-2" id="step2">
<button id="add" class="btn btn-primary btn-block">Add</button>
</div>
</div>
For some reason the PHP part isnt working here but that works too!
Happy for any improvements!
I'm trying to submit multiple rows of data with an attachment from an input field at the end of each row. I am using a Google App-Script Webapp for this. I am successful in creating an array of objects with the text data (such as date, name, last, etc.), but cannot seem to send the attachment as part of the object. What am I doing wrong?
I should also clarify that this code won't work with either one or multiple attachments. I would hope that I could send multiple groupings of attachments (hence the array of objects) at one time.
Here is my code on the HTML/Javascript client-side:
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("tripPost").addEventListener("click", addLine);
document.getElementById("submitAll").addEventListener("click", addRecord);
});
//global variables for next functions
var submit = document.getElementById("tripPost");
var submittedTable = document.getElementById("submitted-data");
var mainEntry = document.getElementById("entry-table");
var submitAll = document.getElementById("submitAll");
submittedTable.addEventListener("click", addLine);
submittedTable.addEventListener("change", fileUpload);
function addLine() {
document.getElementById("table-container").style.display = "block";
var date = document.getElementById("date1").value;
var efirst = document.getElementById("efirst").value;
var elast = document.getElementById("elast").value;
var row = document.createElement("tr");
var col1 = document.createElement("td");
col1.appendChild(document.createTextNode(date));
col1.className = "postDateClass";
var col2 = document.createElement("td");
col2.appendChild(document.createTextNode(efirst));
col2.className = "postEfirstClass";
var col3 = document.createElement("td");
col3.appendChild(document.createTextNode(elast));
col3.className = "postElastClass";
var col4 = document.createElement("td");
row.appendChild(col1);
row.appendChild(col2);
row.appendChild(col3);
row.appendChild(col4);
submittedTable.appendChild(row);
var uniqueID = "id" + new Date().getTime();
var upload = document.createElement("input");
upload.type = "file";
upload.id = uniqueID;
upload.name = "myReceipt";
upload.className = "uploadClass";
var label = document.createElement("label");
label.innerHTML = "upload me please!";
label.htmlFor = uniqueID;
label.className = "custom-file-upload";
var form = document.createElement("form");
form.appendChild(upload);
form.appendChild(label);
col4.appendChild(form);
}
function fileUpload(e) {
if (e.target.className === "uploadClass") {
if (e.target.value) {
var span = document.createElement("span");
span.className = "uploadSpanText";
span.innerHTML = e.target.value.match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[1];
e.target.parentElement.appendChild(span);
e.target.nextElementSibling.innerHTML = "uploaded!";
e.target.nextElementSibling.style.border = "1px solid #a8e0b4";
e.target.nextElementSibling.style.color = "#8bca9e";
}
}
}
function getFile(file) {
return new Promise(resolve => {
const fr = new FileReader();
fr.onload = e => {
const data = e.target.result.split(",");
const obj = {
fileName: file.name,
mimeType: data[0].match(/:(\w.+);/)[1],
data: data[1]
};
resolve(obj);
};
if (file) {
fr.readAsDataURL(file);
} else {
reject("No File");
}
});
}
//gathers inputs and stores values in an object and runs the "addLine" function
async function addRecord(e) {
var dateLines = document.querySelectorAll(".postDateClass");
var eFirstLines = document.querySelectorAll(".postEfirstClass");
var eLastLines = document.querySelectorAll(".postElastClass");
var attachmentLines = document.querySelectorAll(".uploadClass");
var mileageData = [];
for (var i = 0; i < dateLines.length; i++) {
var mileageLines = {};
mileageLines.travelDate = dateLines[i].textContent;
mileageLines.firstName = eFirstLines[i].textContent;
mileageLines.lastName = eLastLines[i].textContent;
mileageLines.receipt = await getFile(attachmentLines[i].parentNode);
mileageData.push(mileageLines);
}
//send object to google. resets input elements
google.script.run.userMileageSubmit(mileageData);
}
Here is the HTML for the code that I'm working with.
<div id="entry-table">
<table>
<h3 style="text-align:left"><u><b>Enter mileage information below.</b></u><br></h3>
<thead>
<tr>
<th >Date</th>
<th >First:</th>
<th >Last:</th>
</tr>
</thead>
<tbody id="table-data">
<tr>
<td>
<div class="disabled-results" id="date">
<input placeholder="Start Date" id="date1" type="text" class="datekeeper" required>
<label for="date1" class="active">Date:</label>
</div>
<td>
<div class="disabled-results">
<input id ="efirst" type="text" class="validate" >
<label for="efirst" class="active">First:</label>
</div>
</td>
<td>
<div class="disabled-results">
<input id ="elast" type="text" class="validate" >
<label for="elast" class="active">Last:</label>
</div>
</td>
<td>
<div id="status">
<button id="tripPost" class="waves-effect waves-light btn-small blue darken-3">Add Trip</button>
</div>
</td>
</tr>
</tbody>
</table>
</div><!---CLOSE ROW --->
<div class="autocomplete" id="table-container" style=display:none>
<table>
<thead>
<tr id="header-titles">
<th >Date</th>
<th >First:</th>
<th >Last:</th>
<th >Receipt </th>
</tr>
</thead>
<form>
<tbody class="form" id="submitted-data">
<div>
<p>Thank you!</p>
</div>
</form>
</tbody>
</table>
<br><br>
</div>
<center>
<div class="row">
<button id="submitAll" class="waves-effect waves-light btn btn-large blue darken-3"><i class="material-icons left">directions_car</i>Submit All Mileage!</button>
</div>
</center>
Here is the CSS
body {
background-color: lightblue;
margin-top: 80px;
margin-bottom: 80px;
margin-right: 80px;
margin-left: 80px;
}
h1{
color: black;
text-align: center;
}
div.disabled-results{
width: 175px;
height: 80px;
padding: 5px;
margin: 5px;
display: inline-table;
box-sizing: border-box;
text-align: center;
}
input[type="file"]{
display: none;
}
.custom-file-upload{
border: 2px solid #000;
width: 85px;
display: inline-block;
padding: 2px 1px;
cursor: pointer;
text-align: center;
}
div.autocomplete{
width: 55px;
height: 80px;
padding: 5px;
margin: 5px;
display: inline-table;
box-sizing: border-box;
text-align: center;
}
I got everything else to work, except sending the attachment (if any) in each line as part of the object.
I am sure that it can be done. I tried to implement the solution from this video which shows you how to upload a file, but I don't use the onclick or this.parentNode since I'm not uploading immediately after selecting a file and instead doing a bulk upload when a user has made numerous entries.
Any help in understanding how this should work would be greatly appreciated.
Thank you.
How about this modification? Please think of this as jut one of several possible answers.
Unfortunately, in this case, the file object from HTML side cannot be directly sent to Google Apps Script as a blob. So as one of several workarounds, in this modification, the retrieved files are encoded to the base64 data and send it to Google Apps Script. Then, at Google Apps Script side, the data is decoded and save them as the files.
Please modify your script as follows.
HTML and Javascript side:
Please modify addRecord() and add getFile() as follows.
// Added
function getFile(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = e => {
const data = e.target.result.split(",");
const obj = {fileName: file.name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]};
resolve(obj);
}
if (file) {
fr.readAsDataURL(file);
} else {
reject("No file");
}
});
}
async function addRecord(e) { // Modified
var dateLines = document.querySelectorAll('.postDateClass');
var attachmentLines = document.querySelectorAll('.uploadClass');
var mileageData = [];
for (var i=0; i<dateLines.length; i++){
var mileageLines = {};
mileageLines.firstName = document.getElementById("efirst").value;
mileageLines.lastName = document.getElementById("elast").value;
mileageLines.date = dateLines[i].textContent;
mileageLines.receipt = await getFile(attachmentLines[i].files[0]).catch(e => console.log(e)); // Modified
mileageData.push(mileageLines);
};
google.script.run.userMileageSubmit(mileageData);
};
Google Apps Script side:
Please modify userMileageSubmit() as follows.
function userMileageSubmit(responses){
responses.forEach(function(e) {
var file = e.receipt;
if (file) {
var blob = Utilities.newBlob(Utilities.base64Decode(file.data), file.mimeType, file.fileName);
var mainFolder = DriveApp.getFolderById('real-drive-link');
var createFile = mainFolder.createFile(blob);
var fileUrl = createFile.getUrl();
Logger.log(fileUrl)
}
});
// row.appendChild(col4)
// submittedTable.appendChild(row)
}
I cannot understand about row.appendChild(col4) and submittedTable.appendChild(row).
Unfortunately, I couldn't understand about your goal at userMileageSubmit(). So in this modification, the retrieved files are saved to Google Drive. And the URL of the created file can be seen at the log.
Here, please modify this for your actual situation.
I'm not sure about real-drive-link. In this case, please set the folder ID that you want to save the file.
Note:
In this modification, it supposes that your current addRecord() works.
In this modification, the maximum file size is 50 MB, because the maximum blob size of Google Apps Script is 50 MB. Please be careful this.
When a lot of files are uploaded, the process time will increase. Please be careful this.
References:
FileReader
Class Utilities
I have a live search function that parses information from a JSON file using AJAX and jQuery, and then is clickable. What I'm struggling to figure out is how to have the value (in this case, "happy" or "fat") populate a multiselect, and then once that's accomplished, capture the rest of the data in that JSON array to be utilized later.
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('coretype.json', function(data) {
$.each(data, function(key, value){
if (value.identifier.search(expression) != -1)
{
$('#result').append('<li class="list-group-item link-class"> '+value.identifier+'</li>');
}
});
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
I have gotten all the way to having the value be clickable, and have been unsuccessful figuring out the rest from there.
Here's the JSON file:
[
{
"identifier":"Happy",
"progressbar1": 3,
"progressbar2": 2,
"progressbar3": -2
},
{
"identifier":"Fat",
"progressbar1": -3,
"progressbar2": -2,
"progressbar3": 2
}
]
Ideally I'd like javascript to be able to capture the "progressbarX" values when someone types in the identifier, although I figure there's a much easier way to accomplish this...
<!-- Search -->
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">EnneaTest</h2>
<br /><br />
<div align="center">
<input type="text" name="search" id="search" placeholder="trait type" class="form-control" />
</div>
<ul class="list-group" id="result"></ul>
<br />
</div>
</div>
</div>
Here's the Plunker file
I created a kind of autocomplete drop down for search from json. And once one of the options from that dropdown is selected, I add that to the result list. At that time the whole object is pushed into searchObjects object. When the item from the list is clicked, that text is used to search the object associated with it. Hope this helps..
<!-- Search -->
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">EnneaTest</h2>
<br /><br />
<div align="center">
<input type="text" name="search" id="search" placeholder="trait type" class="form-control" />
</div>
<div id="searchResult"></div>
<div>
<ul class="list" id="result" style="color: red;"></ul>
</div>
<br />
</div>
<script>
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
var searchField = $('#search').val();
var regex = new RegExp(searchField, "i");
var output = '<div class="row">';
$.getJSON('coretype.json', function(data) {
$.each(data, function(key, val){
if (val.identifier.search(regex) !== -1) {
console.log(val);
var thisVal = JSON.stringify(val);
output += "<h5 onclick='addToList("+thisVal+")'>" + val.identifier + "</h5>";
}
});
output += '</div>';
$('#searchResult').html(output);
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text();
console.log(click_text);
var thisObj = [];
thisObj = findObject(click_text);
console.log(thisObj);
});
});
var searchObjs = [];
function addToList(obj) {
//console.log(obj);
$('#result').append('<li class="list-group-item link-class">'+obj.identifier+'</li>');
$('#searchResult').html('');
var item = {};
item ["identifier"] = obj.identifier;
item ["progressbar1"] = obj.progressbar1;
item ["progressbar2"] = obj.progressbar2;
item ["progressbar3"] = obj.progressbar3;
searchObjs.push(item);
console.log(searchObjs);
}
function findObject(identifier) {
var found = 0;
for (var i = 0, len = searchObjs.length; i < len; i++) {
if (searchObjs[i].identifier === identifier) {
return searchObjs[i]; // Return as soon as the object is found
found = 1;
}
}
if(found === 0) {
return null; // The object was not found
}
} ;
</script>
This is the code I have written in View :
<div class="col-lg-12" style="margin-bottom: 20px;">
<div class="form-group">
<label class="col-sm-3 control-label" style=" margin-top: 14px; ">Domains <font size="3" color="red">*</font></label>
<br />
<div class="col-sm-4" style="width:50%;">
#Html.ListBoxFor(m => m.SelectedDomains, Model.AllDomains,
new { #class = "chosen", multiple = "multiple", id = "drpDomains", style = "width: 350px;",onchange="FillDomain();" })
</div>
</div>
</div>
<div class="col-lg-12" style="margin-bottom: 20px;">
<div class="form-group">
<label class="col-sm-3 control-label" style=" margin-top: 14px; ">Domains new categories <font size="3" color="red">*</font></label>
<br />
<div class="col-sm-4" style="width:50%;">
#Html.ListBoxFor(m => m.SelectedDomainCategories, Enumerable.Empty<SelectListItem>(),
new { #class = "select2", multiple = "multiple", id = "multidomaincategory", style = "width: 350px;" })
</div>
</div>
</div>
<link href="~/Scripts/MultiSelect/chosen.css" rel="stylesheet" />
For Domains, I have used Chosen plugin, and for categories, i have used select2 plugin
<script type="text/javascript">
$(".chosen-deselect").chosen({ allow_single_deselect: true });
$(".chosen").chosen().change();
$(".chosen").trigger('liszt:updated');
</script>
<script>
function FillDomain() {
$("#drpDomains option[value='']").removeAttr("selected");
var selectArr = [];
$('#drpDomains').each(function () {
selectArr.push($(this).val());
});
var a = JSON.stringify(selectArr);
var reference = this;
$.ajax({
url: #Url.Content("~/MyTemplate2/FillIndustry1"), //FillIndustry1 is a method in Controller
type: "POST",
dataType: "JSON",
data: { Domain: a },
success: function (DomainCategories) {
$("#multidomaincategory").html("");
$("#multidomaincategory").removeAttr("selected");
var s = JSON.stringify(DomainCategories);
var t = JSON.parse(s);
for (var key in t) {
$("#multidomaincategory").append("<option value=" + t[key]["Value"] + ">" + t[key]["Text"] + "</option>");
}
},
error: function (data) {
alert("failure error" + data);
var t = window.JSON.parse(data.d);
alert("failueee" + t);
}
});
//I'm trying to remove all the selected items from dependent dropdown (#multidomaincategory) when all items from Domains(#drpDomains) are cleared
if ($("#drpDomains").val() == null || $("#drpDomains").val() == "") {
$("#multidomaincategory").removeAttr("selected");
$("#multidomaincategory").css('display', 'none');
}
}
</script>
Controller :
[HttpPost]
public ActionResult FillIndustry1(string Domain)
{
JArray jsonMembersArr = (JArray)JsonConvert.DeserializeObject(Domain);//convert SymptomString from json string to array
ProfessionalTrans objprofessionaltrans = new ProfessionalTrans();
string listdomains = "";
foreach (var a in jsonMembersArr)
{
listdomains = string.Join(",", a);
}
var DomainCategories = objprofessionaltrans.GetDepCategories(listdomains);
return Json(DomainCategories.ToList());
}
Data Access Layer(Transaction):
public IEnumerable<SelectListItem> GetDepCategories(string domains)
{
//GetDepCategories method - To get categories based on Domains
PTS_CommonEntities objentity = new PTS_CommonEntities();
List<SelectListItem> allskills = new List<SelectListItem>();
List<GetCatListbasedDomain> catnames = objentity.usp_GetCatListBasedOnDomains(domains).ToList();
foreach (var it in catnames)
{
allskills.Add(new SelectListItem { Value = it.CategoryID.ToString(), Text = it.CategoryName });
}
return allskills.AsEnumerable();
}
When I am clearing(closing) the selected items in Domains, the respective Categories are cleared from list, but not in the text box
Image Before Clearing
Image After Clearing the Domains
As you can see, the list is being cleared, but the selected items are still being shown in the UI.
Can someone please find out why the items are being displayed even after clearing them???
Because you are trying to clear the wrong element. #multidomaincategory is the select2 list that holds all of the values, there is a dynamic span class that gets rendered to the page right after this element, look at the html that select2 produces in your browser. Try:
$('#multidomaincategory').next().find('li').html('');
They are cleared from the list because $("#multidomaincategory").html(""); clears the html of the list of categories, not the rendered text elements in the text box.
Although a better way: $('#multidomaincategory').select2('data', null)
I've got an a list of checkboxes on my MVC4 webpage that are generated like this:
<div style="float: left; padding-left: 5px; padding-right: 5px">
<br />
<h3>#Html.Label("Type de service")</h3>
#foreach (var serviceType in Model.ServiceTypeList)
{
<label>#Html.CheckBox(serviceType.ServiceTypeId.ToString(CultureInfo.InvariantCulture)) #serviceType.Description</label><br />
}
<br />
<h3>#Html.Label("Type d'application")</h3>
#foreach (var appType in Model.ApplicationTypeList)
{
<label>#Html.CheckBox(appType.ApplicationId.ToString()) #appType.ApplicationName</label><br />
}
<br />
</div>
What I want to do now is to send a dictionary for each one of the two lists of checkboxes back to the server when a button is clicked, containing a key/value pair with the ID of the checkbox and a boolean as it's value:
<div style="float: left; padding-left: 15px; padding-right: 5px;">
#using (Html.BeginForm("Filter", "Customer", FormMethod.Post, new Dictionary<string, bool>
{}))
{
<input id="btnFilter" type="submit" value="Filter" />
}
</div>
What is the best way to obtain dynamically the values of both of the lists and send them to the server ?
Something like this should work, it will create 2 array(one for each list) stuctured as
[id-boolean,id-boolean,id-boolean,id-boolean,]:
<script>
$(function() {
$("#button").click(function() {
var listOneArray = [];
var listTwoArray = [];
$("#listOne input[type='checkbox']").each(function() {
var a1 = $(this).attr("id");
var b1 = $(this).prop("checked");
listOneArray.push(a1 + "-" + b1.toString());
});
$("#listtwo input[type='checkbox']").each(function () {
var a2 = $(this).attr("id");
var b2 = $(this).prop("checked");
listTwoArray.push(a2 + "-" + b2.toString());
});
$.post("Yourcontroller/YourAction", { list1: listOneArray, list2: listTwoArray }, function (data) {
//do whatever with the response
});
});
});
</script>