MVC4: Sending checkbox values as HtmlAttributes when button is clicked - javascript

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>

Related

How to add/remove element in list on the basis of selection of 2 dropdown list in multi select bootstrap dropdown jquery?

Hope all of you fine and doing well.
I am using multi select bootstrap drop down jquery. I am using asp.net core to populdate Listbox, its working fine for selection,select all etc.
But i want that when i select element from Dropdown A then this element must be removed from dropdown B and if i unselect element from dropdown A then it must added/show in dropdownB. And vice virsa as well, if element selected in dropdown B then this element removed from dropdownA, also if select all from dropdownA then all elements removed from dropdownB and vice virsa as well.
Hope you understand guys.
For example: If A,B,C,D values in dropdownlistA and if i select A then it must be disable or hide from dropdownB,if i select all then must remove all from dropdownB, and also vice virsa for dropdownB as well,
Note: DropdownA and DropdownB both have same number of values/elements,same text ,same value,
View
#section AddToHead{
<link rel="stylesheet" href="~/css1/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="~/css1/bootstrap-multiselect.css" type="text/css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="~/js1/bootstrap-2.3.2.min.js"></script>
<script type="text/javascript" src="~/js1/bootstrap-multiselect.js"></script>
}
<form class="column" asp-controller="group" asp-action="createresult" style="height:100%;" method="post">
<span class="column" style="height:50px;">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamA", onChange = "getSelectedOptions(this)", multiple = "multiple" })
#Html.ValidationMessageFor(model => model.TeamOnePlayers)
</span>
<span class="column">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamB", onChange = "getSelectedOptions(this)", multiple = "multiple" })
#Html.ValidationMessageFor(model => model.TeamTwoPlayers)
</span>
</form>
</div>
#section Scripts {
<script type="text/javascript">
$(function () {
$('#PlayersTeamA').multiselect({
includeSelectAllOption: true
});
$('#PlayersTeamB').multiselect({
includeSelectAllOption: true
});
});
function getSelectedOptions(sel) {
var idddl = sel.id;
var opts = [],
opt;
var len = sel.options.length;
for (var i = 0; i < len; i++) {
opt = sel.options[i];
if (opt.selected) {
opts.push(opt);
var idul = sel.id;
alert(idul);
var ul = document.getElementById(idul);
ul.removeChild(ul.childNodes[1]);
}
}
return opts;
}
Here is a working demo like below:
#model Players
<form class="column" asp-controller="group" asp-action="createresult" style="height:100%;" method="post">
<div id="A">
<span class="column" style="height:50px;">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamA", multiple = "multiple" })
</span>
</div>
<div id="B">
<span class="column">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamB", multiple = "multiple" })
</span>
</div>
</form>
#section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css"/>
<script>
$(function () {
$('#PlayersTeamA').multiselect({
includeSelectAllOption: true
});
$('#PlayersTeamB').multiselect({
includeSelectAllOption: true
});
});
var data = [];
$('#B option').each(function (index, item) {
data.push({ label: this.label, value: this.value });
});
$("#PlayersTeamA").change(function () {
var selectedText = $('#PlayersTeamA').val();
var newData = data;
selectedText.forEach(function (element, index, array) {
newData = newData.filter(function (el) { return el.value != element; });
});
$("#PlayersTeamB").multiselect('dataprovider', newData);
});
</script>
}
My testing model:
public class Players
{
public SelectList AvailablePlayers { get; set; }
}
public class AvailablePlayer
{
public int Id { get; set; }
public string Name { get; set; }
}
My testing controller:
[HttpGet]
public async Task<IActionResult> Index()
{
var player = new List<AvailablePlayer>()
{
new AvailablePlayer(){ Id=1,Name="aa"},
new AvailablePlayer(){ Id=2,Name="bb"},
new AvailablePlayer(){ Id=3,Name="cc"}
};
var model = new Players()
{
AvailablePlayers = new SelectList(player, "Id", "Name")
};
return View(model);
}
Result:
It appears you are using bootstrap's multiselect. In the documentation, we can see that you can configure data as follows (after executing .multiselect on particular input, as you do in your sample):
var data = [
{label: "Messi", value: "Messi"},
{label: "Ronaldo", value: "Ronaldo"}
];
$("#PlayersTeamA").multiselect('dataprovider', data);
Now, attach to 'onchange' event of #PlayersTeamA and update the available data for #PlayersTeamB, for example like this:
$("#PlayersTeamA").change(function () {
var selectedText = $(this).find("option:selected").text();
var newData = data.filter(function(el) { return el.value == selectedText; });
$("#PlayersTeamB").multiselect('dataprovider', newData);
});
You have to attach to onchange of #PlayersTeamB as well, I believe (so that it works in both directions).

Getting values on particular index in javascript

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.

Issues with using AJAX and JQuery to multiselect and capture information from JSON file

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>

Disable the first previous button on dynamic page numbers

I've a pop-up to display the user list which would display 10 results per page, which is working fine.
I'm getting the page nos. from the java servlet in the JSON.
How do I disable the previous button, when it is the first page?
Likewise, how do I disable the last button, when it is the last page?
Here's my code.
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
$(document).on('click', '.next-btn', function(){
var next = 10+pageNo;
userList(next);
});
$(document).on('click', '.prev-btn', function(){
var previ = pageNo - 10;
userList(previ);
});
}
function createTable(resType, pageNo) {
$.getJSON("https://api.randomuser.me/?results="+pageNo, function(data) {
$('#datatable tr:has(td)').remove();
data.results.forEach(function (record) {
var json = JSON.stringify(record);
$('#datatable').append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json)
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
})
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
table, th, td {
border: 1px solid #ddd;
border-collapse: collapse;
padding: 10px;
}
.parent {
height: 25%;
width: 90%;
padding: 1%;
margin-left: 1%;
margin-top: 1%;
border: 1px solid black;
}
.parent:nth-child(odd){
background: skyblue;
}
.parent:nth-child(even){
background: green;
}
label {
float: left;
width: 80px;
}
input {
width: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="userList(0)">Create Table</button>
<table id="datatable">
<tr><th>Select</th><th>Name</th><th>DOB</th></tr>
</table>
<button onclick="saveData()">Save Selected</button>
<br />
<div class="container"></div>
<button onclick="logSavedData()">Get Saved Data</button>
<button id="showExtForm-btn">Open External Form</button>
<div id="extUser" style="display:none">
<form id="extUserForm">
<p>
<label for="name">Name:</label>
<input type="text" id="name" required>
</p>
<br />
<p>
<label for="myImg">Image:</label>
<input type="url" id="myImg" required>
</p>
<br />
<p>
<label for="dob">DOB:</label>
<input type="date" id="dob" required>
</p>
<br />
<button>Submit</button>
</form>
</div>
You should add the prev/next buttons to your HTML as hidden, and then reference them by ID instead of class (as you will only have one of each).
Keep track of the current page number in a global variable.
Show the "prev" button only when the page number is greater than 0. For the "next" button you could apply this trick:
Instead of loading 10 records, load one more, but not for display: if it exists, then the "next" button should be visible.
Here is a snippet with those changes (all changes are in HTML and top part of the script):
var currentPageNo = 0; // Keep track of currently displayed page
$('#next-btn').click(function(){ // Give buttons an ID (include them in HTML as hidden)
userList(currentPageNo+10);
});
$('#prev-btn').click(function(){
userList(currentPageNo-10);
});
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
}
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the "prev" button:
$('#prev-btn').toggle(pageNo > 0);
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&start="+pageNo, function(data) {
$('#datatable tr:has(td)').remove();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#next-btn').toggle(data.results.length > 10);
// Slice results, so 11th record is not included:
data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
var json = JSON.stringify(record);
$('#datatable').append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json),
(i+1+pageNo) // display row number
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
});
// Show the prev and/or buttons
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
table, th, td {
border: 1px solid #ddd;
border-collapse: collapse;
padding: 10px;
}
.parent {
height: 25%;
width: 90%;
padding: 1%;
margin-left: 1%;
margin-top: 1%;
border: 1px solid black;
}
.parent:nth-child(odd){
background: skyblue;
}
.parent:nth-child(even){
background: green;
}
label {
float: left;
width: 80px;
}
input {
width: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="userList(0)">Load First Page</button>
<button id="next-btn" style="display:none">Next Page</button>
<button id="prev-btn" style="display:none">Previous Page</button>
<table id="datatable">
<tr><th>Select</th><th>Name</th><th>DOB</th></tr>
</table>
<button onclick="saveData()">Save Selected</button>
<br />
<div class="container"></div>
<button onclick="logSavedData()">Get Saved Data</button>
<button id="showExtForm-btn">Open External Form</button>
<div id="extUser" style="display:none">
<form id="extUserForm">
<p>
<label for="name">Name:</label>
<input type="text" id="name" required>
</p>
<br />
<p>
<label for="myImg">Image:</label>
<input type="url" id="myImg" required>
</p>
<br />
<p>
<label for="dob">DOB:</label>
<input type="date" id="dob" required>
</p>
<br />
<button>Submit</button>
</form>
</div>
As this URL provides random data, the pages will not show the same data when you revisit them. Also, there is apparently no last page in this random data set. I have guessed the URL parameter for specifying the first record (start), since the results parameter is for specifying the page size, not the first record number. Adapt as needed.
Check previ value is less or equal to 10 if so hide it. Same reverse logic apply for next button. And on next button you can show prev-btn .
$(document).on('click', '.prev-btn', function(){
var previ = pageNo - 10;
if(previ < = 10)
$(this).hide();
UserList(previ);
});

Dependent multiselect dropdown using chosen and select2 plugins

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)

Categories

Resources