JQuery chosen not closing on select - javascript

I am using a JQuery chosen control. It remains open after item selection, also before clicking on it, it is displaying the search textbox. I don't want either of these things to be happening.
Here's the code for the dropdown in MVC using EF:
<div class="form-group">
#Html.LabelFor(model => model.Field, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Field, null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Field, "", new { #class = "text-danger" })
</div>
</div>
Here's the script:
<script type="text/javascript">
$("#Field").chosen();
</script>
what am I missing here. I thought this behaviour was there by default?
Edit: To anyone else having this problem - I forgot to link the chosen.css

Try this;
<script type="text/javascript">
$("#Field").chosen({
max_selected_options: 1,
allow_single_deselect: true, // check out what happens when you remove this option
disable_search: true, // if you dont want to show search box
}).removeAttr("multiple");
$("#Field").on("chosen:maxselected",function(evt, params){
$('#Field').trigger('chosen:close');
});
</script>

Related

Bootstrap 3 DateTimePicker in EditorTemplate

Created an Editor Template to dynamically create time slots. Now I am unable to select the time with datetimepicker. Code below. The following code works when apart of the main view. Is it possible to use datetimepicker in an editortemplate?
#model Testing.Models.TimeSlot
<div class="form-group row">
#Html.LabelFor(model => model.StartTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-2">
#Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { #Value = DateTime.Now.ToString("hh:mm tt"), #class = "form-control", #style = "width: 100px"} })
#Html.ValidationMessageFor(model => model.StartTime, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.EndTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-2">
#Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { #Value = DateTime.Now.AddMinutes(15).ToString("hh:mm tt"), #class = "form-control", #style = "width: 100px" } })
#Html.ValidationMessageFor(model => model.EndTime, "", new { #class = "text-danger" })
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$('#StartTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
});
$(function () {
$('#EndTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15
});
});
$('#StartTime').removeAttr("data-val-date");
$('#EndTime').removeAttr("data-val-date");
</script>
Sections are not supported in partials, and your scripts are never included in the html returned to the client. In any case, scripts should never be in partials (which is what an EditorTemplate is) - you are generating inline scripts, making it harder to debug and risk including multiple instances of the scripts.
Delete the #section Scripts{ ... } code from your EditorTemplate and move it to the main view or its layout. To make this a bit more flexible, I recommend you give the inputs a class name, and use that as a jQuery selector, rather that referring to each individual id (and therefore only one script is required).
In addition, you should never set the value attribute when using the HtmlHelper methods. The methods correctly generate the value from ModelState, ViewData and finally the model property in that order, and by setting the value attribute, you are screwing up model binding. Instead, set the values in the GET method before you pass the model to the view.
Your code to generate the datepicker should be just
#Html.EditorFor(m => m.StartTime, new { htmlAttributes = new { #class = "form-control datetimepicker" } })
or more simply
#Html.TextBoxFor(m => m.StartTime, new { #class = "form-control datetimepicker" })
and you can then style the width
.datetimepicker {
width: 100px;
}
and the the script in the view or layout will be just
$('.datetimepicker').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
Its also not clear why you want to attempt to remove client side validation using .removeAttr("data-val-date"), and doing so suggests a problem with your design. It also appears that you want to select a time only, in which case your property should be TimeSpan.

How to produce 'n' no. of text boxes having different Names with respect to no. of drop down items selected? [duplicate]

This question already has an answer here:
Submit same Partial View called multiple times data to controller?
(1 answer)
Closed 5 years ago.
I have a drop-down list (where multiple options can be selected) and two input boxes inside another div with id 'showInvestmentForm'.Upon selection of drop-down items,I want to produce those text boxes with respect to the number of drop-down items selected.
I want these text boxes to have different Names but I cant find a way to provide them different Names in such a way that their input values get passed to the controller.
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>
If I understood correctly your problem is that input texts are not posted to your Controller.
Would be usefult if you write the Controller's code to check the full scenario.
Anyway a common mistake, that could be your case, when using Mvc helpers is that when you point to a nested property, the generated name of the input is not the final property name but a path to that property.
#Html.EditorFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, ..)
In your case that code produce an input with name FounderInvestmentViewModel_InstallmentPeriod, and not just InstallmentPeriod.
If in your controller you expect a parameter named "InstallmentPeriod" that would not be received, because the page posts a parameter named "FounderInvestmentViewModel_InstallmentPeriod"

Bootstrap selectpicker MVC dropdown livesearch

I am quite sure my problem is something to do with the script reference.
I have added it to my bundles
bundles.Add(new ScriptBundle("~/bundles/bootstrap-select").Include(
"~/Scripts/bootstrap-select.js",
"~/Scripts/bootstrap-select.min.js"));
here is my views code:
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
});
Html form:
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.SagId, "SagId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.SagId,(IEnumerable<SelectListItem>)ViewBag.SagId,
new
{
#class = "form-control selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})
#Html.ValidationMessageFor(model => model.SagId, "", new { #class = "text-danger" })
</div>
</div>
I get the list from my view bag, that works fine. But I cannot seem to fix this problem.
Update:
tried to manually add referrences in the view. now the dropbox is completly gone and i get theese errors:
Uncaught TypeError: Cannot read property 'valHooks' of undefined
at bootstrap-select.min.js:7
at bootstrap-select.min.js:8
at bootstrap-select.min.js:7
at bootstrap-select.min.js:7
Create:78 Uncaught ReferenceError: $ is not defined
at Create:78
First, you only want to add one of the references; start with just the JS; when built in release mode, it will find the min.js.
bundles.Add(new ScriptBundle("~/bundles/bootstrap-select").Include(
"~/Scripts/bootstrap-select.js"));
This was registering the same script, which will have these sorts of problems.
Secondly, it looks like this bundle is defined before wherever you have JQuery defined. So the $ is not defined is likely because bootstrap select script, and usage, has to be after the JQuery initialization.

If checkbox is checked then enable EditorFor

I would like my Checkbox to disable EditorsFor if it is unchecked and enable them if it is checked. I know I have to use JavaScript, I found some codes in net, but it seems that they don't work.
Here is my View code:
#{Html.RenderPartial("_PartialError");}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
(...)
<div class="form-group">
#Html.LabelFor(model => model.Czy_zuzywalny, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Czy_zuzywalny)
#Html.ValidationMessageFor(model => model.Czy_zuzywalny, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_minimalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_minimalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_minimalna, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_optymalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_optymalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_optymalna, "", new { #class = "text-danger" })
</div>
</div>
(...)
}
And I wrote something like this and put in js file (ofc at the end of this code is ), but it doesn't work...
$(document).ready(function ()
{
$("#Czy_zuzywalny").click(function ()
{
if ($("#Ilosc_minimalna").attr("disabled") == "")
{
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
else
{
$("#Ilosc_minimalna").attr("disabled", "");
$("#Ilosc_optymalna").attr("disabled", "");
}
});
});
Nothing happens even if I check or uncheck my checkbox. Can anyone help me with that?
Change your jQuery code to:
$(document).ready(function () {
$("#Czy_zuzywalny").click(function () {
if ($("#Ilosc_minimalna").is('[disabled=disabled]')) {
$("#Ilosc_minimalna").removeAttr("disabled");
$("#Ilosc_optymalna").removeAttr("disabled");
}
else {
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
});
});
The if condition on your code never actually evaluates to true because in an enabled input, the 'disabled' attribute doesn't have a value of an empty string. it just doesn't exist (thus the use of removeAttr("disabled")).
UPDATE: Working JSFiddle here
UPDATE 2:
In order to add the script in the Create view and have it show after the jQuery script tag in the rendered HTML do this:
First add a call to RenderSection in your Layout file just before the closing </body> tag like this:
#RenderSection("scripts", required: false)
This will give you the ability to include a 'scripts' section in your views, the contents of which, will appear instead of the RenderSection call in the final HTML. Note that the required: false parameter specifies that you don't have to include this section in every view.
Then in your Create view, outside of any section add this:
#section scripts {
<script src="/scripts/CheckBoxItemCreate.js"></script>
}
Hope this helps!

jquery ui datepicker error

This is the error message I get when try to implement the datepicker:
Unhandled exception at line 133, column 9 - JavaScript runtime error: Object doesn't support property or method 'datepicker'
This is the code I have added to the View:
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>`
Here is the script:
<script>
$(function () {
$("#model.Date").datepicker();
});
This is my first jQuery element so I don't know what I am doing wrong. I don't understand the entire jQuery element process.
datepicker() is not a method in plain jQuery. It is part of the jQueryUI library, which you will also need to include in your page:
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jqueryui.js"></script>
<script type="text/javascript">
$(function () {
$("#model.Date").datepicker();
});
</script>
</head>
The jQueryUI library can be downloaded from http://jqueryui.com

Categories

Resources