I want to move items from one listbox to another, I have a jQuery but it is not behaving properly.
When i click left in background it causes all items to move from list2 to list1 but in front end it shows that list2 have value.
when i click submit then it causes error.
List1 is source and List2 is destination
$(document).ready(function () {
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').on('click', function () {
moveItems('#SelectedPanelList', '#AllPanelList');
});
$('#right').on('click', function () {
moveItems('#AllPanelList', '#SelectedPanelList');
});
$('#leftall').on('click', function () {
moveAllItems('#SelectedPanelList', '#AllPanelList');
});
$('#rightall').on('click', function () {
moveAllItems('#AllPanelList', '#SelectedPanelList');
});
});
Example Image
Suppose I have 4 items in List2--a,b,c,d but only c,d are selected then in db only c,d is getting updated but i want all items which are in list2 i.e. a,b,c,d should get updated in db. Please suggest.
Htmls:
for List 1
#Html.DropDownListFor(model => model.AllPanelList, Model.AllPanelList, new { #id = "AllPanelList", #class = "form-control", multiple = "multiple" })
For list 2
#Html.DropDownListFor(model => model.SelectedPanelListArray, Model.SelectedPanelList, new { #id = "SelectedPanelList", SelectListItem="true", #class = "form-control", multiple = "multiple" })
$('button').click(function(){
var $options = $("#selection > option").clone();
$('#copy').append($options);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selection">
<option>select</option>
<option>option1</option>
<option>option2</option>
</select>
<select id="copy">
</select>
<button>copy</button>
Related
In my main page I have Dropdownlist of Cars. And it works fine.
And When I select one car from Dropdownlist I want to get back all car modells who belongs to the selected Car from Dropdownlist in the same view, let say under Dropdownlist. DropDownlist with Cars and Models of the selected cars in the same View (in Main view). I tried with PartialView but I'am not so good when it comes PartielView and html code
This is my action to get CarModels, and I think this must be as PartialView
[HttpGet]
public ActionResult GetCarModel(int? carId)
{
List<CarModelVW> listOfCarModel;
using (Db db = new Db())
{
listOfCarModel = db.CarModel.ToArray()
.Where(x => carId == null || carId == 0 || x.carId == carId)
.Select(x => new CarModelVW(x))
.ToList();
}
return View(listOfCarModel);
}
In my Main View with DropDownlist
<div class="form-group">
<label class="control-label col-md-2" for="HasSidebar"> Car </label>
<div class="col-md-10">
#Html.DropDownListFor(model => model.CarId, Model.Cars, "---Select car---", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CarId, "", new { #class = "text-danger" })
</div>
</div>
And here below Dropdownlist I want to get all carmodels of selected car
But I think I have to create <div> </div> with Id or span .. but I'am not sure how to do here.
And here is javascript I'am trying to use
$("#CarId").change(function () {
var carId = $(this).val();
if (carId) {
window.location = "/an/GetCarModel?carId=" + carId;
}
return false;
});
How do I get this action GetCarModel below Dropdownlist view? Thank you in advance.
Just like Roman said, instead of navigating to the url, you should send an ajax call to the control.
First of all, add an id to your dropdownlist.
Secondly, in the Onchange function add an ajax call to get cars:
var dropdownval = $("#//Id of dropdown").val();
var json = '{Id: ' + dropdownval + '}';
$.ajax({
url:'#Url.Action("GetCarModel", "//The controller")',
type:'POST',
data: json,
contentType:'Application/json',
success:function(result){
//Do whatever
}
})
You can then do whatever with the result you pass back to the ajax call
If you want to view results on the same page then you need to use Ajax.
add this div tag Main view where you want to display results:
<div id="carmodels"></div>
Change your jquery function as below:
$("#CarId").change(function () {
var carId = $(this).val();
if (carId)
{
$.get("/an/GetCarModel?carId=" + carId, function(data){
$("#carmodels").html(data);
});
}
});
How can make the autocomplete form return value in two different textbox? for example when select apple by using autocomplete form it will display "Apple" in textboxA and quantity "1" in textbox B.
I have tried the following code and succeeded to build the autocomplete form. But it show name in the selection and when select the item from list it will display value.
<script type="text/javascript">
$(document).ready(function () {
$("#CardName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/CardHolderDetails/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CardName, value: item.CardId };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<div class="form-group">
#Html.EditorFor(model => model.CardName, new { htmlAttributes = new { #class = "form-control", id = "CardName" } })
</div>
<div class="form-group">
#Html.EditorFor(model => model.CardId, new { htmlAttributes = new { #class = "form-control", id = "CardId" } })
</div>
[HttpPost]
public JsonResult Index(string Prefix)
{
List<CardHolderDetails> getCardList = new List<CardHolderDetails>();
getCardList = _service.getCardList();
List<CardHolderDetails> ObjList = new List<CardHolderDetails>();
foreach (var value in getCardList)
{
ObjList.Add(new CardHolderDetails { CardId = value.CardId, CardName = value.CardName });
}
//Searching records from list using LINQ query
var CardName= (from N in ObjList
where N.CardName.StartsWith(Prefix)
select new { N.CardName, N.CardId });
return Json(CardName, JsonRequestBehavior.AllowGet);
}
i expected when select the output from autocomplete form, the output CardName will be in textbox A and CardId in textbox B.
I tried to understand what the issue is exactly, but it's not clear - did you, or did you NOT get the autocomplete to work? Is it returning any meaningful value back to the client?
Anyways, with what we have here, it seems that there might be an issue with the Razor usage, probably with the way you're using the returned object:
<div class="form-group">
#Html.EditorFor(model => model.CardName, new { htmlAttributes = new { #class = "form-control", id = "CardName" } })
</div>
<div class="form-group">
#Html.EditorFor(model => model.CardId, new { htmlAttributes = new { #class = "form-control", id = "CardId" } })
</div>
From the model you're returning to the client and the Ajax script piece, I'd expect for the usage of the result 'model' object to look like this:
model => model.label and model => model.value.
I have few drop-down list here as shown in , based on this drop-down selection next drop-down to it should be populated..
i tried to use this keyword to get value of current drop-down but i am unable to get it.
<td class="border-top-0 border-left-0 border-right-0 align-middle form-group">
#{
SelectList newSelectList = new SelectList((from s in Model.UserMasterList
.ToList()
select new
{
userId = s.userId,
userName = (s.userFirstName +' '+ s.userLastName)
}).Distinct()
,
"userId",
"userName",
string.IsNullOrEmpty(item.JobConstructionManagerId.ToString()) ? 0 : item.JobConstructionManagerId);
}
#Html.DropDownListFor(model => item.JobConstructionManagerId, (SelectList)newSelectList, new { #class = "form-control js-select js-noFilter hidden DDConstructionManager", size = "2", #value = 0, Id = "JobConstructionManager" + t ,#OnChange="fill();"}) //first dropdown
</td>
<td class="border-top-0 border-left-0 border-right-0 text-center text-align-center">
#{
SelectList newSelectStaffList = new SelectList((from s in Model.UserMasterStaffList //.UserConstructionManagersDetailList
.ToList()
select new
{
SuserId = s.userId, //s.conUserId,
SuserName = (s.userFirstName + ' ' + s.userLastName) //(s.mqUserMaster.userFirstName +' '+ s.mqUserMaster.userLastName)
}).Distinct()
,
"SuserId",
"SuserName",
string.IsNullOrEmpty(item.JobStaffId.ToString()) ? 0 : item.JobStaffId);
}
#Html.DropDownListFor(model => item.JobStaffId, (SelectList)newSelectStaffList, new { #class = "form-control js-select js-noFilter hidden DDStaff", size = "2", #value = 0, Id = "JobStaff" + t }) //second dropdown
</td>
main problem is that how to get just next drop-down to some particular drop-down
You must give an id attribute to your first dropdownlist then handle change event of dropdown with jquery to populate second dropdown.
<script type="text/javascript">
$('#firstDropDownId').change(function () {
$(function () {
$.ajax({
url: '#Url.Action("GetSecondData", "YourController")',
type: 'POST',
dataType: 'json',
data: { 'firstData': $("#firstDropDownId").val() },
success: function (data) {
var options = $('#secondDropDownId');
options.empty();
$.each(data, function (i, item) {
options.append($('<option />').val(item.Id).text(item.Display));
});
},
error: function (response) {
}
});
});
});
});
</script>
and then create an action method in your controller to populate second dropdown and return in json format.
[HttpPost]
public JsonResult GetSecondData(int firstId)
{
var result = ...; //populate result
return new JsonResult { Data = result };
}
In your first dropdown list, add another data-* attribute "cascade-list-id".
#Html.DropDownListFor(model => item.JobConstructionManagerId, (SelectList)newSelectList, new { #class = "form-control js-select js-noFilter hidden DDConstructionManager", size = "2", #value = 0, Id = "JobConstructionManager" + t ,#OnChange="fill();" "data-cascade-list-id"="newSelectStaffList" + t}) //first dropdown
In fill method, get the cascase list id, bind the new data with the id reference.
// pseudo code
function fill() {
var _that = this;
var cascadeId = $(_that).attr("data-cascade-list-id") // or use .data("cascadeListId");
// code to get the new data and binding, omitted for brevity
}
Hope this helps you..
I am giving you the country state example you can use this concept
<select name="country" id="country" onchange="states('state')">
<option value="">Select Country</option>
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
</select>
<select name="state" id="state">
<option value="">Select State</option>
function states(target){
var country = $("#country option:selected").val();
$.ajax({
type: "GET",
url: "url/"+country,
dataType: "text",
success: function(data){
if(data !=''){
$('#'+).html(data);
}
}
});
}
I am attempting to create a cascading dropdown with MVC3. The parent dropdown is called "Category", when the user selects a Category, a child dropdown is then populated with a list of pictures that belong to that Category. I've got some code in place right now, and I am able to call the controller from the View when the user selects a category. Here is my code:
Controller:
public ActionResult Pictures(int catId)
{
var k = ((List<Picture>) ViewBag.AllPictures)
.FindAll(x => x.CategoryId == catId)
.Select(x => new
{
Value = x.PictureId,
Text = x.Title
});
return Json(k, JsonRequestBehavior.AllowGet);
}
View:
<div class="editor-field">
#Html.DropDownListFor(model => model.Picture.PictureId, Enumerable.Empty<SelectListItem>(), new { #id = "pictureFilter" })
#Html.ValidationMessageFor(model => model.Picture.PictureId)
</div>
Javascript:
<script type="text/javascript">
$('#ddlFilter').on("change", function() {
var selectedCat = $(this).val();
$.getJSON("/StoreManager/Pictures", { catId: selectedCat }, function(pictures) {
var picturesSelect = $('#pictureFilter');
picturesSelect.empty();
$.each(pictures, function(index, picture) {
picturesSelect.append($('<option/>', {
value: picture.val,
text: picture.text
}));
});
});
});
</script>
When I take a look at variable 'k', that my controller is returning. It does contain all the correct collection items for the pictures, with their respective 'value' and 'text' fields assigned. When it returns the JSON back to the View, it creates a dropdown menu with the exact number of fields that should be there, but they all contain empty data. When I inspect the element in Chrome, here is the HTML afterwards:
<option><option/>
<option><option/>
<option><option/>
<option><option/>
All help is appreciated. Any further code requested will be linked to in pastebin posts.
You have return JSON then you need to used same variables as you send from Pictures controller.
try this:
<script type="text/javascript">
$('#ddlFilter').on("change", function() {
var selectedCat = $(this).val();
$.getJSON("/StoreManager/Pictures", { catId: selectedCat }, function(pictures) {
var picturesSelect = $('#pictureFilter');
picturesSelect.empty();
$.each(pictures, function(index, picture) {
picturesSelect.append($('<option/>', {
value: picture.Value,
text: picture.Text
}));
});
});
});
</script>
or you can also check the response variable get from your Action method by using firebug console tab.
I have a WebGrid full of lots of products, and I want to be able to edit the quantity for each row in the web grid and update the Cart table in the database when the textChanged event is raised on the corresponding textbox.
But is this even possible with WebGrid? I have not found anything that would suggest it's possible. I would really appreciate any help at all.
It's possible to attach a change event to the textboxes.
I set my grid up like the following:
#grid.GetHtml(
htmlAttributes: new { cellspacing = "2px", cellpadding = "2px" },
columns: grid.Columns(
grid.Column("Id"),
grid.Column("Description"),
grid.Column("PacketQuantity"),
grid.Column("ThickCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThickCover, new { #class = "thickCoverInput", #data_value = p.Id });
}),
grid.Column("ThinCover", format: (item) => {
var p = item.Value as MvcApplication1.Models.Product;
return Html.TextBox("ThickCover", p.ThinCover);
})
)
)
Then I had the following script to wire up the changes:
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$('.thickCoverInput').change(function(event) {
alert(event.currentTarget.attributes["data-value"].value);
alert(event.currentTarget.value);
// Here you can post data to an action to update your table
});
});
</script>
When I changed the value in the textbox, I was able to get two alerts. One for the Id of the Product and the other is the new value.
Hope this is what you were looking for.