Clear multi select dropdown using JavaScript - javascript

I am trying to clear a multi-select dropdown using javascript as shown by the image below
Class
[MultiSelect("GetLookUps", 6)]
public int[] HoldItemsArr { get; set; }
Chtlm
<div class="row form-group">
#Html.RequiredLabelFor(model => model.HoldItemsArr, new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.EditorFor(model => model.HoldItemsArr, new { htmlAttributes = new { #class = "form-control", multiple = "multiple" } })
#Html.ValidationMessageFor(model => model.HoldItemsArr, "", new { #class = "text-danger" })
</div>
</div>
JavaScript
if (($("#ReasonForLeaving").val() == 15)) {
$("#ResignationInfo").show();
}
else {
// I tried all the option below
$('#HoldItemsArr').length = 0;
$("#HoldItemsArr option:selected").prop("selected", false);
$("#HoldItemsArr").val('')
$("#HoldItemsArr").multiSelect("clearSelection");
}

The link below help with what I was looking for
How do I reset a jquery-chosen select option with jQuery?
I needed to add the code below to my JavaScript
$('#HoldItemsArr').val('').trigger('chosen:updated');

Option 1:
$("#HoldItemsArr").multiselect("clearSelection");
Option 2:
$("#HoldItemsArr option:selected").removeAttr("selected");
$("#HoldItemsArr").multiselect('refresh');
Please take a look at the link: https://www.py4u.net/discuss/911129

Related

To Show/Hide <div> tag depending on the selection from previous drop down box

I have read many tutorials and many answers on stack overflow as well but it still does not work for me.Upon selecting an option (Yes)from drop down -> it should show the <div> tag otherwise <div> should be hidden.
Below is my code:
<h4>1. Does your school participate in the sponsored CAT4 scoring initiative?</h4>
#{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Yes",
Value = "True"
});
listItems.Add(new SelectListItem
{
Text = "No",
Value = "False"
});
}
<div class="form-group" id="PickOption">
<div class="col-md-10">
#Html.DropDownListFor(model => model.ParticipateInCAT4Scoring, listItems, "<----Select Yes or No---->", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ParticipateInCAT4Scoring, "", new { #class = "text-danger" })
</div>
</div>
<div id="OnYes" class="form-group" style="display:none">
#Html.Label("For what Grade levels?", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(m => m.GradeLevelsCAT4, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.GradeLevelsCAT4, "", new { #class = "text-danger" })
</div>
</div>
Below is the Script file which I am placing at bottom of View page:
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#PickOption').on('change', function () {
if ($(this).val() == 'True') {
document.getElementById('OnYes').style.display = "";
}
else {
document.getElementById('OnYes').style.display = "none";
}
});
});
</script>
}
Your selector is not right, please make sure that you bind event on dropdown so add a class on dropdown
#Html.DropDownListFor(model => model.ParticipateInCAT4Scoring, listItems, "<----Select Yes or No---->", new { #class = "form-control pickerDropdown" })
Now bind the event on added class like this:
$('.pickerDropdown').on('change', function () {
PickOption is the ID of the wrapping div.
Replace #PickOption on this line with the ID or selector of the select box (usually auto-generated but you can specify.
$('#PickOption').on('change', function () {
Also since you're using jQuery, you can just do $('#OnYes').show();
https://api.jquery.com/show/

Set selected index in Razor drop down list using Java Script

In my project I have three objects: Invoice, InvoiceItem and PaymentMethod. Invoice contains lists of InvoiceItems and PaymentMethods (Master with 2 Details). For InvoiceItem and Payament method I have 2 partial view that are loading on Create, Edit and Details page. When I am reading data from database, all the data is as expected expect for DropDowns. I am not able to set SelectedIndex in drop downs as expected. InvoiceItems partial view has 2 drop downs (Customer and Transport). PaymentMethod partial view has one drop down (PaymentMethodDetails). Note: When I read data into EditorFor instead of DropDown, everything is as expected. But when I try to set selected values from model into database, values are set correctly only for the first dropdown (Customer), other two drop downs have first item as selected (value is not selected).
InvoiceItem partial view
<div class="form-group" style="margin-left: 1px">
#Html.LabelFor(model => model.CustomerId, "CustomerId", htmlAttributes: new { #class = "control-label col-lg-2" })
<div class="col-lg-2" style="margin-left: 30px">
#Html.DropDownList("CustomerId", null, htmlAttributes: new { #class = "form-control", #id = Model.RbrStavke, #style = "width: 140px" })
</div>
</div>
<div class="form-group" style="margin-left: 1px">
#Html.LabelFor(model => model.TransportId, "TransportId", htmlAttributes: new { #class = "control-label col-lg-2" })
<div class="col-lg-2" style="margin-left: 30px">
#Html.DropDownList("TransportId", null, htmlAttributes: new { #class = "form-control", #id = Model.RbrStavke, #style = "width: 100px" })
</div>
</div>
PaymentMethod partial view
<div class="form-group" style="margin-left: 1px">
#Html.LabelFor(model => model.PaymentMethodId, "PaymentMethodId", htmlAttributes: new { #class = "control-label col-lg-2" })
<div class="col-lg-2" style="margin-left: 40px">
#Html.DropDownList("PaymentMethodId", null, htmlAttributes: new { #class = "form-control", #id = Model.IDNacinaPlacanja, #style = "width: 200px" })
</div>
</div>
Edit Invoice view (loads two partial views)
<ul class="list-group" id="ii">
#for (int i = 0; i < Model.InvoiceItems.Count(); i++)
{
#Html.EditorFor(model => Model.InvoiceItems[i], "InvoiceItems")
}
</ul>
<ul class="list-group" id="pm">
#for (int i = 0; i < Model.PaymentMethods.Count(); i++)
{
#Html.EditorFor(model => Model.PaymentMethods[i], "PaymentMethods")
}
</ul>
Java Script in Edit Invoice view
document.addEventListener('DOMContentLoaded', function() {
var invoiceItem = #Html.Raw(Json.Encode(Model.InvoiceItems.Select(x => new
{
ItemId = x.ItemId,
CustomerId = x.CustomerId,
TransportId = x.TransportId
})));
var paymentMethod = #Html.Raw(Json.Encode(Model.PaymentMethods.Select(x => new
{
PaymentMethodId = x.PaymentMethodId
})));
for (var i = 0; i < invoiceItem.length; i++)
{
var id = invoiceItem[i].ItemId;
var c = invoiceItem[i].CustomerId;
var t = invoiceItem[i].TransportId;
document.getElementById(id).selectedIndex = c - 1;
//todo: set selected paymentmethod
}
for (var i = 0; i < paymentMethod.length; i++)
{
var idPm = paymentMethod[i].PaymentMethodId;
//todo: set selected paymentmethod
}
}, false);
This works for CustomerId selected item in the dropdown. When I do the same for Transport and PaymentMethod (document.getElementById) it does not work.
How can I change this so that other two drop downs have correct selected value from the model?
If you want to set selected item for dropdownlist in js.You can try to use like:
$("#{idOfDropDown}").val("selectedvalue");
id should be unique,so don't use #id = Model.RbrStavke for different dropdowns,and {idOfDropDown} should be the id value of the dropdown which you want to set.

When using HTML and CSS, how can I apply a class to a field that is already read-only?

Here's my dilemma: I have jQuery code with an if-statement that applies a specific class to an element based on the value selected on a page where the user is filling out a form. I also built another form where a user can view the details of a form that has already been filled out. When the details page is displayed, most of the class is applied, but the grey "read-only" background overwrites the background color from the original class. I don't really want to go into the bootstrap files and adjust the read-only background color code if I can avoid it. How can I apply the full class (including the background color) to an element that is read-only?
Snippet of code from the "Create" page:
<div class="col-md-12">
<div class="col-md-10">
#Html.LabelFor(model => model.Question1, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-2">
#Html.DropDownListFor(model => model.Question1, new[] { new SelectListItem() { Text = "Pass", Value = "Pass" }, new SelectListItem() { Text = "Fail", Value = "Fail" }, new SelectListItem() { Text = "NA", Value = "NA" } }, "Select an option", htmlAttributes: new { #class = "form-control text-box centerline", #onchange = "updateEscalationsListeningScore()", id = "question1Answer" })
#Html.ValidationMessageFor(model => model.Question1, "", new { #class = "text-danger" })
</div>
</div>
jQuery from the "Create" page:
if (Q1Answer === "Pass") {
$('#question1Answer').addClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
Q1Score = 3;
Q1PotentialPoints = 3;
}
else if (Q1Answer === "Fail") {
$('#question1Answer').addClass("incorrectListeningAnswer").removeClass("correctListeningAnswer").removeClass("naListeningAnswer");
Q1Score = 0;
Q1PotentialPoints = 3;
}
else if (Q1Answer === "NA") {
$('#question1Answer').addClass("naListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("correctListeningAnswer");
Q1Score = 0;
Q1PotentialPoints = 0;
}
else {
$('#question1Answer').removeClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
Q1Score = 3;
Q1PotentialPoints = 3;
}
Snippet of code from the "Details" page:
<div class="col-md-12">
<div class="col-md-10">
#Html.LabelFor(model => model.Question1, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-2">
#Html.EditorFor(model => model.Question1, new { htmlAttributes = new { #class = "form-control text-box centerline", id = "question1Answer", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Question1, "", new { #class = "text-danger" })
</div>
</div>
jQuery from the "Details" page:
if (Q1Answer === "Pass") {
$('#question1Answer').addClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
Q1Score = 3;
Q1PotentialPoints = 3;
}
else if (Q1Answer === "Fail") {
$('#question1Answer').addClass("incorrectListeningAnswer").removeClass("correctListeningAnswer").removeClass("naListeningAnswer");
Q1Score = 0;
Q1PotentialPoints = 3;
}
else if (Q1Answer === "NA") {
$('#question1Answer').addClass("naListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("correctListeningAnswer");
Q1Score = 0;
Q1PotentialPoints = 0;
}
else {
$('#question1Answer').removeClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
Q1Score = 3;
Q1PotentialPoints = 3;
}
CSS
.correctListeningAnswer {
background-color: #c6efce;
color: #006100;}
.incorrectListeningAnswer {
background-color: #ffc7ce;
color: #9c0006;}
.naListeningAnswer {
background-color: #ffeb9c;
color: #9c5700;}
Thank you in advance for your help.
Cory
Thank you, everyone, for the information. I researched a few things that you guys all suggested and it looks like I was able to get it to work. What's frustrating is that the answer was really simple, and the way I was able to get there was by using CBroe's method. I just had to add this to my CSS file:
.correctListeningAnswer[readonly] {
background-color: #c6efce;
color: #006100;
}
.incorrectListeningAnswer[readonly] {
background-color: #ffc7ce;
color: #9c0006;
}
.naListeningAnswer[readonly] {
background-color: #ffeb9c;
color: #9c5700;
}
I appreciate all of your help!
Don't make the field readonly, make it disabled. Then your background will work.
Here's an example:
input {
background-color:#ffc;
}
<input type="text" disabled>
Or (and I personally think this is the better approach), don't use a form field to display information. Grab the data from the initial form and then display it in more semantically correct elements, like span, which aren't editable in the first place.
document.querySelector("button").addEventListener("click", function(){
document.getElementById("dataOut").textContent = document.getElementById("dataIn").value;
});
<input id="dataIn">
<button type="button">Simulate a submit</button>
<span id="dataOut"></span>
As a last resort, you could always make your class selector more specific than the Bootstrap selectors, so that yours will take precedence.

How to pass the values of the textboxes(which are IN LOOP) from view to the controller with respect to the item id selected in the dropdown box?

I would like to pass the values of the multiple textboxes from view to the controller with respect to the item id selected in the dropdown box.
NOTE:-Multiple textboxes are produced because user can select multiple items from dropdown.
This is a part of my Controller:-
foreach(var data in propertyViewModel.PropertyInvestors)
{
FounderInvestment founderInvestment = new FounderInvestment
{
Id = propertyViewModel.FounderInvestmentViewModel.Id ?? 0,
InstallmentPeriod = propertyViewModel.FounderInvestmentViewModel.InstallmentPeriod,
InvestorId = Convert.ToInt32(data),
PropertyId = property.Id,
Investment = propertyViewModel.FounderInvestmentViewModel.Investment
};
_founderInvestmentQueryProcessor.Create(founderInvestment);
}
This is my dropdown:-
<div class="form-group">
#Html.LabelFor(model => model.PropertyInvestors, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.PropertyInvestors, (IEnumerable<SelectListItem>)#ViewBag.Investors, "Select", htmlAttributes: new {#id="dropdown", #class = "form-control",#multiple="multiple" })
#Html.ValidationMessageFor(model => model.PropertyInvestors, "", new { #class = "text-danger" })
</div>
</div>
These are the textboxes:-
<div id="showInvestmentForm" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.FounderInvestmentViewModel.Investment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FounderInvestmentViewModel.Investment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FounderInvestmentViewModel.Investment, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FounderInvestmentViewModel.Investment, "", new { #class = "text-danger" })
</div>
</div>
</div>
This is the JS that produces the textboxes with respect to the number of dropdown items selected:-
<script type="text/javascript">
$(function () {
$("#dropdown").change(function () {
var value = $(this).val();
var form1 = $('#showInvestmentForm').html();
if (value.length == 1) {
$('#showInvestmentForm').show();
}
else if (value.length > 1) {
for (var i = value.length; i <= value.length ; i++) {
$(form1).appendTo('#field1');
}
}
else {
$('#showInvestmentForm').hide();
}
});
});
</script>
PROBLEM:---- The problem that I am getting here is that the value of the first 'form-group' textboxes is being repeated for all the textboxes.i.e first entry is being repeated and passed to the controller.How do I solve this issue?
This is how it gets saved in Founder Investment Database Table because of repeat
In order to Post back the values of those textboxes,You need indexing. In order to do that, first create a 'Dummy' code for those two input text boxes like this:--->
<div id="showInvestmentForm" style="display:none">
<div class="form-group">
<label for="FounderInvestments.Investment" class="control-label col-md-2">Investment</label>
<div class="col-md-10">
<input type="number" name="FounderInvestments[#].Investment" value="" class="form-control" />
<input type="hidden" name="FounderInvestments[#].Index" value="" />
</div>
</div>
<div class="form-group">
<label for="FounderInvestments.InstallmentPeriod" class="control-label col-md-2">Installment Period</label>
<div class="col-md-10">
<input type="number" name="FounderInvestments[#].InstallmentPeriod" value="" class="form-control" />
</div>
</div>
</div>
The hidden input is also necessary.
Now the JS code has to look something like this:-
$(function () {
$('#dropdown').change(function () {
var value = $('#dropdown').val();
alert(value.length);
var index = (new Date()).getTime();
var clone = $('#showInvestmentForm').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
$('#field1').append(clone.html());
});
DateTime is for producing random index numbers. The [#] is replaced by those randomly generated DateTime values.
Unfortunately I cannot comment yet, so I'll post this as an answer (which it might actually be).
The problem you described occurs when "value.length" of the dropdown selection is greater than 1 (thus multiple textboxes were being created).
Taking this snippet out of your code:
else if (value.length > 1) {
for (var i = value.length; i <= value.length ; i++) {
$(form1).appendTo('#field1');
}
}
..we can see that there's an unwanted behavior regarding DOM manipulation - essentially, creating multiple elements with the same ID.
I am guessing since you are probably listening to those textboxes changes using an ID, you will experience exactly the problem you described.
A little snippet that might help:
else if (value.length > 1) {
for (var i = value.length; i <= value.length ; i++) {
var newTextBox = document.createElement('div');
newTextBox.innerHTML = form1.innerHTML;
newTextBox.setAttribute('id', 'textbox'+i);
$(newTextBox).appendTo('#field1');
}
}
(Not sure this will actually work since I don't have enough info, but the idea should fix the problem)

Selecting dropdown value shows a Textbox, but doesn't stores a value passed in it

my view contains
<div class="col-md-3 ">
#{
List<SelectListItem> deformitylevel = new List<SelectListItem>();
deformitylevel.Add(new SelectListItem { Value = "hip", Text = "Hip" });
deformitylevel.Add(new SelectListItem { Value = "knee", Text = "Knee" });
deformitylevel.Add(new SelectListItem { Value = "ankle", Text = "Ankle" });
deformitylevel.Add(new SelectListItem { Value = "other", Text = "Other" });
}
#Html.DropDownListFor(model => model.DeformityLevel, deformitylevel, "--Select Level -", new { #class = "form-control", #onchange = "showdeformitytextbox()", id = "deformitydropdown" })
#Html.ValidationMessageFor(model => model.DeformityLevel, "", new { #class = "text-danger" })
</div>
<div class="col-md-3">
#Html.EditorFor(model => model.DeformityLevel, new { htmlattributes = new { #class = "form-control", id = "deformitytextbox" ,style= "display:none"} })
</div>
My function is
function showdeformitytextbox() {
if ($("#deformitydropdown option:selected").text() == 'Other') {
$("#deformitytextbox").show();
}
else {
$("#deformitytextbox").hide();
}
}
When I select "Other" in dropdownlist it stores 'other' in the database instead of storing a value which is entered in #Html.EditorFor.
What I'm forgetting Help!!
As mentioned by others, to make this cleaner, it would be best if you separated the model fields for the drop down and the textbox. Even if you get it to work using the below code, it will lead to more work if you have to return to the page with the other value selected. That said, the following does properly submit the expected value in the textbox. The key concept is to set the dropdown to disabled as you submit.
Assuming your form has an id of submitForm specified as follows:
#using (Html.BeginForm("someActionName", "someControllerName", FormMethod.Post, new { #id="submitForm"}))
Then the following code will ensure that the drop down doesn't submit its value by intercepting the form submission:
$("#submitForm").submit(function () {
if ($("#deformitydropdown option:selected").text() === "Other") {
$("#deformitydropdown").attr("disabled", true);
} else {
$("#deformitydropdown").removeAttr("disabled");
}
});
I would change the names of your current controls and make a hidden form element for DeformityLevel. Then set its value in javascript based on DropdownList and textbox change events.
***Something like this (jq not verified, just for illustration)
<select id="DeformityLevel_DDL">
<option></option>
<option></option>
<option></option>
</select>
<input type="text" id="DeformityLevel_TB" />
<input type="hidden" id="DeformityLevel" name="DeformityLevel" />
<script>
$(document).ready(function () {
$('#DeformityLevel_DDL').change(function () {
if ($(this).val() != 'other') {
$('#DeformityLevel').val(this.val());
}
});
$('#DeformityLevel_TB').on('change', function () {
$('#DeformityLevel').val($(this).val());
});
});
</script>
Well, your function only display the #deformitytextbox input, when the value entered there changes you should also update the model property.
If the form submits automatically on select change you should use preventDefault.
Try now with TextBox, your parameter for htmlAttributes is incorrect. Try:
<div class="col-md-3 ">
#Html.DropDownList("DeformityLevel", deformitylevel, "--Select Level -", new { #class = "form-control", #onchange = "showdeformitytextbox()", id = "deformitydropdown" })
#Html.ValidationMessage("DeformityLevel", "", new { #class = "text-danger" })
</div>
<div class="col-md-3">
#Html.TextBox("DeformityLevel", null, new { #class = "form-control", id = "deformitytextbox", style = "display:none;" })
</div>
<script>
function showdeformitytextbox() {
if ($("#deformitydropdown option:selected").text() == 'Other') {
$("#deformitytextbox").show();
}
else {
$("#deformitytextbox").hide();
}
}
</script>

Categories