My editorfor onChangeEvent isn't working and I can't figure out why.
here is my javascript function
<script type="text/javascript">
function OnChangeEvent() {
alert("value is changed");
var compQty = $('#compQTY').val();
//do other functions here also like change button
//if decrease add below
if (compQty < #Model.comp_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
<script>
and here is my editorFor
<div class="form-group">
#Html.LabelFor(model => model.comp_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.comp_qty, new { disabled = "disabled", #Value = Model.comp_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.comp_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id = "compQTY" } })
#Html.ValidationMessageFor(model => model.comp_qty, "", new { #class = "text-danger" })
}
</div>
</div>
from what I have googled this should work but it is not. Can anybody help me figure out what I'm missing or what the possible solution is?
Related
My cascading drop down box work fine from within visual studio 2015 and iisexpress. But when hosting on IIS or selecting IIS as server in visual studio the controller action to populate the second drop drown box is not called!
I'm new to Javascript and and not very firm with asp.net mcv with I use here.
I use VS2015, ASP.NET Mvc
Create.cshtml:
#model Bethesda2017.Models.AuftragEditViewModel
#{
ViewBag.Title = "Neuer Reparaturauftrag";
}
<style>
body {
background: url(/Bilder/Bethesda4Web.jpg);
background-position: right top;
background-size: 12%;
background-repeat: no-repeat;
}
</style>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal body">
<h4>Neuer Reparaturauftrag</h4>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
-- Some irrelavant controls extracted here ----
<div class="form-group">
#Html.LabelFor(model => model.STORT_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor( model => model.STORT_ID, Model.StandortListe, "Bitte wählen!", new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DropDownListFor(model => model.STORT_ID, Model.StandortListe, "Bitte wählen!", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.STORT_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TRAKT_ID, htmlAttributes: new { #class = "control-label col-md-2" })
#*#Html.DropDownListFor(model => model.TRAKT_ID, Model.TraktListe, "", new { #class = "form-control col-md-2" } )*#
<div class="col-md-10">
#Html.DropDownListFor(model => model.TRAKT_ID, Model.TraktListe, "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TRAKT_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ETAGE_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ETAGE_ID, Model.EtageListe, "", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.ETAGE_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RAUM_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.RAUM_ID, Model.RaumListe, "", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.RAUM_ID, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.DerAuftrag.FHD_KOMPLETT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DerAuftrag.FHD_KOMPLETT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DerAuftrag.FHD_KOMPLETT, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Speichern" class="btn btn-default" />
</div>
</div>
</div>
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
var trakt_idUrl = '#Url.Action("FetchTrakte", "Auftrag")';
var trakte = $('#TRAKT_ID');
var etage_idUrl = '#Url.Action("FetchEtagen", "Auftrag")';
var etagen = $('#ETAGE_ID');
var raume = $('#RAUM_ID');
var raum_idUrl = '#Url.Action("FetchRaume", "Auftrag")';
$('#STORT_ID').change(function () {
trakte.empty();
etagen.empty();
raume.empty();
$.getJSON(trakt_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
trakte.append($('<option></option>').val('').text('Bitte Trakt wählen!'));
$.each(data, function (index, item) {
trakte.append($('<option></option>').val(item.TRAKT_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
$('#TRAKT_ID').change(function () {
etagen.empty();
raume.empty();
$.getJSON(etage_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
etagen.append($('<option></option>').val('').text('Bitte Etage wählen!'));
$.each(data, function (index, item) {
etagen.append($('<option></option>').val(item.ETAGE_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
$('#ETAGE_ID').change(function () {
raume.empty();
$.getJSON(raum_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
raume.append($('<option></option>').val('').text('Bitte Raum wählen!'));
$.each(data, function (index, item) {
raume.append($('<option></option>').val(item.RAUM_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
</script>
When selecting an entry in the first drop down box the java script
$('#STORT_ID').change(function () ...
gets called and trakte, etagen and raume are set empty but the next step:
$.getJSON(trakt_idUrl, { STORT: $(this).val() }, function (data) {...
which should call the method
public JsonResult FetchTrakte(string STORT )
{
List<Trakt> _l = FetchTrakteList(STORT);
if ( _l.Count<1 )
{
Trakt _s0 = new Trakt() { TRAKT_ID = "00", BEZEICHNUNG = "keine Daten" };
_l.Add(_s0);
}
return Json(_l, JsonRequestBehavior.AllowGet);
}
is only called when using iisexpress but not with IIS!
Where is the problem or how to examine what is going on here?
I have simple form a dropdown list and a textbox. When the page is loaded textbox is disabled. If 'Other' is selected from dropdown list, then textbox is enabled and I add 'required' rule to textbox as I don't want user to enter something in the text box. When 'Other' is selected and if Create button is clicked, I can see validation error message but I cannot remove that message after user has typed something in the empty textbox. Here is how it looks:
Here is my model:
using System.ComponentModel.DataAnnotations;
namespace validatetextbox.Models
{
public class Manager
{
public int Id { get; set; }
[Required]
public string City { get; set; }
[Display(Name = "Other City")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string OtherCity { get; set; }
}
}
My Controller method is
// GET: Managers/Create
public ActionResult Create()
{
//populate Gender dropdown
List<SelectListItem> c = new List<SelectListItem>();
c.Add(new SelectListItem { Text = "-- Please Select --", Value = "" });
c.Add(new SelectListItem { Text = "New York", Value = "New York" });
c.Add(new SelectListItem { Text = "Miami", Value = "Miami" });
c.Add(new SelectListItem { Text = "Other", Value = "Other" });
ViewBag.Cities = c;
return View();
}
My view is as follows:
#model validatetextbox.Models.Manager
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Manager</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, ViewBag.Cities as List<SelectListItem>, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OtherCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OtherCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OtherCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$('#OtherCity').prop('disabled', true);
$('#City').change(function () {
if ($('#City option:selected').text() != 'Other') {
$("#OtherCity").rules("remove", "required");
$('#OtherCity').prop('disabled', true);
} else {
$('#OtherCity').prop('disabled', false)
$("#OtherCity").rules("add", "required");
}
});
});
</script>
}
To keep your existing code - you can remove the rules from the text box on document ready. Also - side note - keep quotation marks consistent.
<script type="text/javascript">
$(document).ready(function () {
$('#OtherCity').prop('disabled', true);
// Remove any rules
$('#OtherCity').rules("remove");
$('#City').change(function () {
if ($('#City option:selected').text() != 'Other') {
//Also tidy up `"` to `'`
$('#OtherCity').rules("remove", "required");
$('#OtherCity').prop('disabled', true);
} else {
$('#OtherCity').prop('disabled', false)
//Also tidy up `"` to `'`
$('#OtherCity').rules("add", "required");
}
});
});
</script>
Another thing you could try is - add the class optional to the editor - the label will display and the visibility and validation requirement will be controlled by the JS:
<div class="form-group">
#Html.LabelFor(model => model.OtherCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10 optional">
#Html.EditorFor(model => model.OtherCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OtherCity, "", new { #class = "text-danger" })
</div>
</div>
$(document).ready(function () {
// This will hide the field
$('.optional').hide();
// This makes the value optional
$('#OtherCity').attr("data-val", "false");
$('#City').change(function () {
if ($('#City option:selected').text() == 'Other') {
// Show the text editor
$('.optional').show();
// This makes the value required
$('#OtherCity').attr("data-val", "true");
} else {
$('.optional').hide();
$('#OtherCity').attr("data-val", "false");
}
});
});
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!
Here is my View:
#using (Html.BeginForm("SaveNewCustomer", "Dealer", FormMethod.Post, new { id = "myForm" }))
{
<div class="form-horizontal">
<div class="row">
<div class="form-group-1">
#Html.LabelFor(model => model.device.MotorType, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.MotorType, new { htmlAttributes = new { #class = "form-control required", placeholder = "Motor Type", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.PowerRating, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.PowerRating, new { htmlAttributes = new { #class = "form-control required", placeholder = "Power Rating", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.InstallationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.InstallationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Installation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.ActivationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.ActivationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Activation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.DataReceiveInterval, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.DataReceiveInterval, new { htmlAttributes = new { #class = "form-control required", placeholder = "Data receive Interval", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.HasAMC, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.HasAMC, new { htmlAttributes = new { #class = "form-control required", #onchange = "OnChange();" } })
</div>
<div class="form-group-1" id="HasDate">
#Html.LabelFor(model => model.device.AMCExpiredDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.AMCExpiredDate, new { htmlAttributes = new { #class = "form-control required", placeholder = "AMCExpireDate(MM/dd/yyyy)", required = "required", title = "Enter AMC Expire Date" } })
</div>
<button style="margin-left:33%;" id="action" class="btn btn-sm btn-primary col-lg-2 " type="button" name="action" value="SaveDeviceInfo"><strong>Save</strong></button>
</div>
</div>
}
My javascript script is
<script type="text/javascript">
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
}
});
$("#action").click(function () {
if (!$("#myForm").validate()) { // Not Valid
return false;
} else {
Save();
}
});
function Save() {
var frm = $("#myForm").serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
}
</script>
Problem is Validation not fire. In If else condition it is showing false and direct store the value in database. Could you please help me?
Is anything wrong in my code? Give me suggestions please.
Thanks in advance.
.validate() is only the initialization method.
.valid() is the method used for testing the form.
if (!$("#myForm").valid()) { ....
It's a moot point because your .ajax() function belongs inside the submitHandler option of the plugin anyway. The submitHandler callback only fires when the form is valid, thereby you can entirely eliminate your whole if/then click handler function (however you must change the button element into a type="submit").
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
},
submitHandler: function(form) { // only fires when form is valid
var frm = $(form).serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
return false;
}
});
});
NOTE: If you happen to be using the unobtrusive-validation plugin as included within your ASP framework, then the .validate() method is constructed and called automatically. If that's the case, then your call to .validate() will be ignored, and you would put any plugin options only within jQuery.validator.setDefaults().
You are missing your form tags from your html. Also, you dont have anything with the id of myform. So your trying to validate #myform in your jquery but there is no myform. You would need to add your form tags and give it an id of myform.
My ASP.NET MVC 5 application's razor view uses two checkboxes:
<div class="form-group">
#Html.LabelFor(model => model.BoolField1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
#Html.ValidationMessageFor(model => model.BoolField1, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BoolField2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField2, new { htmlAttributes = new { #class = "form-control", #id = "bool2" } })
#Html.ValidationMessageFor(model => model.BoolField2, "", new { #class = "text-danger" })
</div>
</div>
</div>
I'm trying implement the rule that BoolField2 cannot be true unless BoolField1 is also true. My jquery code:
function applyRule() {
var bool1Status = document.getElementById('bool1').checked;
var bool2Status = document.getElementById('bool2').checked;
if (bool2Status == true && bool1Status == false) {
// This is the sole error.
// Generate a suitable error message and display (how?)
}
}
The custom error generated at this code must be displayed into Html.ValidationMessageFor. How can I achieve this?
First you need to correct syntax for EditorFor () it should be like following
#Html.EditorFor(model => model.BoolField1, new { #class = "form-control", #id = "bool1" })
instead of
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
Now after having this correction you may write custom jQuery logic to achieve same. Here is the code.
$(function () {
$('#bool2').on('click', function (e) {
//Get the state of 1st checkbox
var isFirstCheck = $('#bool1').is(":checked");
if (isFirstCheck==false) {
//dispay message if you need. Below line of code will prevent user to select 2nd checkbox
e.preventDefault();
}
})
});