Read model value and disable certain textbox when page load - javascript

I wanna to ask how can I achieve disable textbox by condition. Example, When dropdown list selected "Card". Commission text field will be appear. If model value is "Cash" the Commission text field will be hide.
<div class="k-edit-field">
#(Html.Kendo().DropDownListFor(model => model.PAY_TYPE)
.DataTextField("NAME")
.DataValueField("CODE")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetPayType", "Payment");
});
})
.HtmlAttributes(new { style = "width: 100%", #id = "payType"})
)
</div>
<div class="k-edit-field" id="ASD">
#Html.EditorFor(model => model.PAY_COMM)
#Html.ValidationMessageFor(model => model.PAY_COMM)
</div>
JavaScript
jQuery(document).ready(function () {
$("#payType").on("change", function () {
if ($(this).val() == "C") {
$('#Comm').show();
} else {
$('#Comm').hide();
}
});
$("#payType").trigger("change");
});

You need to check the value when page load and when dropdown change.
function changeComm() {
if ($("#payType").val() == "C") {
$('#Comm').show();
} else {
$('#Comm').hide();
}
}
jQuery(document).ready(function () {
changeComm();
$("#payType").on("change", function () {
changeComm();
});
$("#payType").trigger("change");
});

Related

Jquery doesnt find input textbox value

I have the following code to populate KendoGrid, I used Jquery to get text-box value. text-box display the right value but Jquery is not returning what's in the textbox instead it return nothing.
<input asp-for="InvoiceID" name="InvoiceID" id="iid" />
<script>
function additionalInfo() {
return {
invoiceID: $("#iid").val()
}
}
</script>
#(Html.Kendo().Grid<....WebUI.ViewModels.Project.BillingDocuments>()
.Name("BillingDocuments")
.Columns(columns =>
{
columns.Bound(p => p.ID).Hidden().Width(50);
columns.Bound(p => p.PrintSequence).Title("Seg").Width(50);
columns.Bound(p => p.DocumentType).Width(100);
columns.Bound(m => m.Actions).ClientTemplate("<a class='text-primary' href='#= DocumentLocation #'>View</a>").Width(50);
})
.HtmlAttributes(new { style = "height:250px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Read(read => read.Action("BillingDocumentsRead", "Billing", new { Area = "Project"}).Data("additionalInfo")
.Type(HttpVerbs.Get))
)
)
I tried by setting the invoice ID value as
<script>
function additionalInfo() {
return {
invoiceID:55
}
}
</script>
and this works fine but jquery doesnt pick textbox value of <input asp-for="InvoiceID" name="InvoiceID" id="iid" />.

Remove rules required from an input date

Hello i have an input of type date and i'am doing validation for it.
This input is only required when a checkbox is checked, so i did a function with jquery to add rules required and now i want to remove this rules if my checkbox is not checked.
Here my Html :
<div class="col-md-3 d-inline-block">
<label class="mdc-text-field">
#Html.TextBoxFor(model => model.DateDebutZFU, new { #Value = Model.DateDebutZFU != new DateTime() ? Model.DateDebutZFU.Value.ToString("dd/MM/yyyy") : "", #data_val_date = "La valeur doit ĂȘtre une date", #class = "mdc-text-field__input dataDate" })
<span class="mdc-floating-label">Date Debut ZFU</span>
<div class="mdc-text-field__bottom-line"></div>
</label>
#Html.ValidationMessageFor(model => model.DateDebutZFU, "", new { #class = "text-danger" })
</div>
<div class="mdc-switch align-top mt-1 mr-5">
<div class="mdc-switch__track"></div>
<div class="mdc-switch__thumb-underlay">
<div class="mdc-switch__thumb">
#Html.CheckBoxFor(m => m.ZFU, new { #class = "mdc-switch__native-control", #role = "switch" })
</div>
</div>
</div>
And Here the function to add rules if i click to the button submit :
function btnclicked() {
if ($("#btnedit").data('clicked', true)) {
if (($("#ZFU").is(':checked'))) {
$("#DateDebutZFU").rules("add", {
required: true,
messages: {
required: "Date Debut ZFU est obligatoire"
}
});
}
}
}
And here what i try to do if the checkbox is not checked then i must remove rules of required that was displayed in the input:
$(document).ready(function () {
$("#ZFU").click(function () {
var rules = $("#DateDebutZFU").rules();
if (rules) {
$("#DateDebutZFU").rules("remove", "required");
}
});
});
Now my problem that the message required is always displayed despite that the checkbox is not checked so what is the problem in my code ?
If you need to evaluate your date input based on checkbox - just do it
function btnclicked() {
if ($("#btnedit").data('clicked', true)) {
var isChecked = $("#ZFU").is(':checked');
var $dateDeutZFU = $("#DateDebutZFU");
if (isChecked) {
$dateDeutZFU.rules("add", {
required: true,
messages: {
required: "Date Debut ZFU est obligatoire"
}
});
}else{
$dateDeutZFU.rules("remove", "required");
}
}
}
Using your example I am checking if checkbox.is(':checked') and based on this condition add/remove 'required' rule. ope this will help you.

Div class show after refresh page

I have a radio button which has option to show or hide div content defending of radiobutton state, but after i fill the form and I press F5 the previous state stay, but div class is dissapear.
$(document).ready(function () {
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
HTML
<div class="form-group">
#Html.LabelFor(model => model.Chapel, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "Yes", new { #class = "styled", htmlAttributes = new { #checked = "true", #name = "Chapel"} }) Yes
</label>
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "No", new { #class = "styled", htmlAttributes = new { #checked = "true" , #name = "Chapel" } })
No
</label>
#Html.ValidationMessageFor(model => model.Chapel, "", new { #class = "text-danger" })
</div>
</div>
Any comment, where It should be problem ?
After page refresh if you want to show a div then you need to add that code outside click function.
$(document).ready(function () {
// Add logic when to show this div
$("div#hideChapel").show(); // Here you go
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});

search kendo multiselect without adding values to multiselect

Background: I have a kendo multiselect that gets populated with emails based on the values of a kendo dropdown. I also need to use the multiselect to 'search' for additional emails through our employee api. Then as i search and select new values to be added to the 'selected values' portion of the multiselect i want to be able to go back and see the initial populated values without the searched values.
Disclaimer: I can get all of this to work except the searched values get 'added' to the datasource which I dont want. Think of a temporary datasource when searching. So when i go to look through the initial populated values, the returned search vales are appended to the datasource values. Again, I do not want this.
CODE:
<div class="row display-row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<h4>Location Group:</h4>
#(Html.Kendo().DropDownList()
.Name("weatherLocGroupNameDropDown")
.HtmlAttributes(new { style = "width:100%" })
.OptionLabel("Select location group...")
.DataTextField("LocationGroupName")
.DataValueField("LocationGroupId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getLocationGroupNames", "Base");
});
})
)
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<h4>Location:</h4>
#(Html.Kendo().DropDownList()
.Name("weatherLocNameDropDown")
.HtmlAttributes(new { style = "width:100%" })
.OptionLabel("Select location...")
.DataTextField("LocationName")
.DataValueField("LocationId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getLocationNamesFilteredByLocationGroup", "Base")
.Data("filterLocation");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.Events(ev => ev.Change("populateLocGrpEmails"))
.CascadeFrom("weatherLocGroupNameDropDown")
)
</div>
<div class="row display-row">
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
#(Html.Kendo().MultiSelect()
.Name("recipientMultilist")
.Placeholder("Recipient(s)")
.AutoBind(false)
.Enable(false)
.HtmlAttributes(new { style = "width:100%" })
.DataTextField("EmailName")
.DataValueField("EmailId")
.Events(ev => ev.Filtering("searchEmails"))
)
</div>
</div>
function searchEmails() {
var searchText = $("#recipientMultilist").data('kendoMultiSelect').input.val();
searchText = searchText.trim();
if (searchText.length >= 3 && searchText != undefined && searchText != "") {
$.ajax(
{
url: "#Url.Action("getRecipientEmails", "Base")",
data: { searchTerm: searchText },
type: "GET",
dataType: "json",
async: false,
success: function (searchEmail) {
if (searchEmail.length > 0) {
for (var i = 0; i < searchEmail.length; i++) {
$('#recipientMultilist').data("kendoMultiSelect").dataSource.add({
EmailName: searchEmail[i].EmailName,
EmailId: searchEmail[i].EmailId
});
}
}
}, error: function (searchEmailErr) { console.log('searchEmailErr: ', searchEmailErr); }
})
}
}
function getLocationGroupEmails() {
return {
LocationGroupId: $("#weatherLocGroupNameDropDown").data("kendoDropDownList").value()
}
}
function filterLocation() {
return {
LocationGroupId: $("#weatherLocGroupNameDropDown").data("kendoDropDownList").value()
};
}
function populateLocGrpEmails() {
$("#recipientMultilist").data("kendoMultiSelect").enable();
tempMultiListStorage = [];
var locationText = $("#weatherLocNameDropDown").data('kendoDropDownList').text();
var locationGroupId = $("#weatherLocGroupNameDropDown").data('kendoDropDownList').value()
//get all emails associated with the location group and inserts into the recipientMultilist
$.ajax(
{
url: "#Url.Action("getEmailFilteredByLocationGroup", "Base")",
data: { LocationName: locationText, LocationGroupId: locationGroupId },
type: "GET",
dataType: "json",
async: false,
success: function (filteredEmail) {
if (filteredEmail.length > 0) {
for (var i = 0; i < filteredEmail.length; i++) {
$('#recipientMultilist').data("kendoMultiSelect").dataSource.add({
EmailName: filteredEmail[i].EmailName,
EmailId: filteredEmail[i].EmailId
});
tempMultiListStorage.push({
EmailName: filteredEmail[i].EmailName,
EmailId: filteredEmail[i].EmailId })
}
}
}, error: function (filteredEmailErr) { console.log('filteredEmailErr: ', filteredEmailErr); }
})
var multiselect = tempMultiListStorage
//"selects" the record that matches the location
var dropdownlist = $("#recipientMultilist").getKendoMultiSelect();
dropdownlist.value(locationText)
dropdownlist.trigger("change");
}
I do know that this code in searchEmails
$('#recipientMultilist').data("kendoMultiSelect").dataSource.add({
EmailName: searchEmail[i].EmailName,
EmailId: searchEmail[i].EmailId
});
is adding the values to the multiselect but thats there so i can at least test a few other things. Again, i am looking to 'see' the searched values, select the search values but not make them part of the 'datasource' by adding them.
I hope this was clear haha.
Can you give this a try and see if it works:
$("#multiselect").kendoMultiSelect({
select: function(e) {
e.preventDefault();
}
});

ASP.NET Custom Control, Two Grids.. Need some advice

I need some advice designing a custom control which uses two grids and an Add and Remove button in between.
The Add button takes the selected item from left and add it to the right and then it removes it from the left.
The Remove button does the vice versa.
To have a fluid experience, I understand that Javascript will probably have to be involved.
Currently I'm creating a control inheriting CompositeControl with two grids and two sources. I could use a UpdatePanel so I don't have to do do a full post back on Add/Remove.
Any suggestions on the best way to approach this?
I did this sample using Kendo. I write some parts .I hope it would be helpful
I add and remove some paths to supervisors in my sample:
you need a main Action like this:
public ActionResult AddPathToSupervisor()
{
return View();
}
My sample is a bit more complete because in the view at first you choose a superviser and after that you add some paths to him.
within the view you need 2 Grids and 2 buttons between for Add/Remove
like this:
<div class="row">
<div class="col large">
#(Html.Kendo().ComboBox()
.Name("supervisor")
.BindTo(SupervisorsSelectList)//var DocumetTypesSelectList = ViewBag.DocumetTypesSelectList as List<SelectListItem> ?? new List<SelectListItem>();
.Events(e => e.Change("changeSupervisor"))
)
</div>
</div>
<div class="row">
<div class="col medium">
<p>New Paths</p>
</div>
<div class="col medium">
<p></p>
</div>
<div class="col medium">
<p>Supervisor Paths</p>
</div>
</div>
<div class="row">
<div class="col medium">
#(Html.Kendo().Grid<Distribution.Models.Path>()
.Name("newPathsGrid")
.Columns(columns =>
{
columns.Bound(p => p.PathId).Visible(false);
columns.Bound(p => p.Title).Title(PathResource.Paths);
})
.Sortable()
.Scrollable()
.Navigatable()
.Filterable(filterable => filterable.Extra(false))
//.HtmlAttributes(new { style = "height:480px;" })
.Resizable(resize => resize.Columns(true))
.Selectable(s => s.Mode(GridSelectionMode.Multiple))
.DataSource(dataSource => dataSource
.Ajax()
//.PageSize(15)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.PathId);
model.Field(p => p.PathId).DefaultValue(new Guid());
})
.Read(read => read.Action("FillNewSupervisorPathsGrid", "Paths"))
)
)
</div>
<div class="col medium">
<input type="button" id="addPathToSupervisor" value=">>Add>>" />
<input type="button" id="removePathFromSupervisor" value="<<Remove<<" />
</div>
<div class="col medium k-rtl">
#(Html.Kendo().Grid<Distribution.Models.Path>()
.Name("supervisorPathGrid")
.Columns(columns =>
{
columns.Bound(p => p.PathId).Visible(false);
columns.Bound(p => p.Title).Title(PathResource.Paths);
})
//.Pageable()
.Sortable()
.Scrollable()
.Navigatable()
.Filterable(filterable => filterable.Extra(false))
//.HtmlAttributes(new { style = "height:480px;" })
.Resizable(resize => resize.Columns(true))
.Selectable(s => s.Mode(GridSelectionMode.Multiple))
.DataSource(dataSource => dataSource
.Ajax()
//.PageSize(15)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.PathId);
model.Field(p => p.PathId).DefaultValue(new Guid());
})
.Read(read => read.Action("FillSupervisorPathsGrid", "Paths", new { id = ViewBag.SupervisorId }))
)
)
</div>
</div>
this javascript code is to select Supervisor`s ID:
<script type="text/javascript">
function changeSupervisor(e) {
var id = this.value();
var supervisorPathGrid = $("#supervisorPathGrid").data("kendoGrid");
supervisorPathGrid.dataSource.read({ id: id });
}
and here is the javascript code to add and remove paths:
<script type="text/javascript">
var supervisorPathGrid = $("#supervisorPathGrid").data("kendoGrid");
var newPathsGrid = $("#newPathsGrid").data("kendoGrid");
var selectedItem = $("#supervisor").data("kendoComboBox");
$(document).on('click', '#addPathToSupervisor', function (e) {
e.preventDefault();
var supervisorId = selectedItem.value();
if (hasManyRowSelected(newPathsGrid)) {
var values = [];
values.push({
name: "supervisorId",
value: supervisorId
});
newPathsGrid.select().each(function () {
values.push({
name: "ids",
value: newPathsGrid.dataItem(this).PathId
});
});
$.ajax({
url: '#Url.Action("AddPathToSupervisor")',
type: 'POST',
datatype: "json",
traditional: true,
data: values,
success: function () {
newPathsGrid.select().each(function () {
var $this = $(this);
var data = newPathsGrid.dataItem($this);
supervisorPathGrid.dataSource.insert(0, data);
});
newPathsGrid.select().each(function () {
var $this = $(this);
var data = newPathsGrid.dataItem($this);
newPathsGrid.removeRow($this);
});
},
beforeSend: function () {
$('#addPathToSupervisor').attr("disabled", true);
$('#addPathToSupervisor').addClass("ajax-load");
},
error: function (event, request, settings) {
ajax_exception(event);
},
complete: function () {
$('#addPathToSupervisor').attr("disabled", false);
$('#addPathToSupervisor').removeClass("ajax-load");
grid.dataSource.read();
},
timeout: 50000
});
}
});
$(document).on('click', '#removePathFromSupervisor', function (e) {
e.preventDefault();
var supervisorId = selectedItem.value();
if (hasManyRowSelected(supervisorPathGrid)) {
var values = [];
supervisorPathGrid.select().each(function () {
values.push({
name: "ids",
value: supervisorPathGrid.dataItem(this).PathId
});
});
$.ajax({
url: '#Url.Action("RemovePathFromSupervisor")',
type: 'POST',
datatype: "json",
traditional: true,
data: values,
success: function () {
supervisorPathGrid.select().each(function () {
var $this = $(this);
var data = supervisorPathGrid.dataItem($this);
newPathsGrid.dataSource.insert(0, data);
});
supervisorPathGrid.select().each(function () {
var $this = $(this);
var data = supervisorPathGrid.dataItem($this);
supervisorPathGrid.removeRow($this);
});
},
beforeSend: function () {
$('#removePathFromSupervisor').attr("disabled", true);
$('#removePathFromSupervisor').addClass("ajax-load");
},
error: function (event, request, settings) {
ajax_exception(event);
},
complete: function () {
$('#removePathFromSupervisor').attr("disabled", false);
$('#removePathFromSupervisor').removeClass("ajax-load");
grid.dataSource.read();
},
timeout: 50000
});
}
});
now you need 2 Post methods to add and remove paths like this :
[HttpPost]
public ActionResult AddPathToSupervisor(string[] ids, string supervisorId)
{
try
{
PathsBll.AddPathsToSupervisor(ids, supervisorId);
}
catch (Exception ex)
{
throw ex;
}
return Json(ModelState.ToDataSourceResult());
}
[HttpPost]
public ActionResult RemovePathFromSupervisor(string[] ids)
{
try
{
PathsBll.RemovePathsFromSupervisor(ids);
}
catch (Exception ex)
{
throw ex;
}
return Json(ModelState.ToDataSourceResult());
}
in which you can write linq to add or remove paths through ids.
if you are familiar with kendo you know that you have 2 methods to fill each grid.
if you need more info add comment.
good lick

Categories