how to show and hide validation message using Javascript - javascript

In following code if I select only MonthDropdown value and not YearDropdown it should show a validation message.
If I select YearDropdown value and not MonthDropdown value, it should show a validation message.
If I select both dropdown value, the message should be hidden.
I tried myself but I couldn't get the correct result.
<div class="field field--with-dropdown clearfix" style="height: 50px;">
<label for="field-country" >Expiry date</label>
<div class="select--half" style="padding-top: 10px;">
#Html.Kendo().DropDownListFor(x=>x.ExpiryMonth).BindTo(months).Events(x => x.Change("checkout.onMonthYearDDlChange")).DataValueField("Value").DataTextField("Text").OptionLabel("Valid Till Month").HtmlAttributes(new{ required = "required", data_required_msg = " Expiry Month is Required",#class="expmonth" })
#Html.Kendo().DropDownListFor(x => x.ExpiryYear).BindTo(years).Events(x=>x.Change("checkout.onMonthYearDDlChange")).DataValueField("Value").DataTextField("Text").OptionLabel("Valid Till Year").HtmlAttributes(new { required = "required", data_required_msg = " Expiry date is Required", #class = "expyear"})
#Html.ValidationMessageFor(x=>x.ExpiryMonth, "", new { #class = "text-danger expmonth",id="expirymonth" })
#Html.ValidationMessageFor(x => x.ExpiryYear, "", new { #class = "text-danger", id = "expiryyear" })
</div>
</div>
CSS
<style>
span#expirymonth {
display: none !important;
}
</style>
Javascript
var expMonth = $("#Billing_ExpiryMonth").val();
var expYear = $("#Billing_ExpiryYear").val();
if (expMonth !== "" && expYear !== "") {
$("#expiryyear").hide();
} else {
$("#expiryyear").show();
}

Related

To set value written by user as value of dropdown in asp.net

I have a Remarks div
If user choose option of Other then user need to fill box for reasons.
This is inside webpage(.cshtml)
#model MNepalWeb.Models.CustomerSRInfo
#{
List<SelectListItem> Remarks = new List<SelectListItem>();
Remarks.Add(new SelectListItem { Text = "Your name does not match", Value = "Your name does not match" });
Remarks.Add(new SelectListItem { Text = "Your date of birth does not match", Value = "Your date of birth does not match" });
Remarks.Add(new SelectListItem { Text = "Others", Value = "Others" });
}
//For remarks
<div class="form-group">
<label class="control-label col-md-2">Reject Remarks <b style="color:red;">*</b></label>
<div class="col-md-5">
#Html.DropDownListFor(model => model.Remarks, new SelectList(Remarks, "Value", "Text"), new { #class = "form-control", #style = "width: 100%;", #id = "txtRemarks" })
<br />
<textarea name="OthersRemarks" id="txtOthersRemarks" placeholder="Please Insert Remarks to Reject, maxlength- 200" maxlength="200" rows="4" cols="50" style=" display:none; min-height:50px;min-width:200px;max-height:100px;max-width:422px;" class="form-control" #*oninput="checkValidation()"*#></textarea>
<b style="color:red">*</b><b> Note Please fill out remarks before rejecting </b>
<br />
</div>
</div>
</div>
JS for changing value
if ($.trim($('#RejectRemarks select').val()) == "" || $.trim($('#RejectRemarks select').val()) == "Others") {
var TextBoxRemarks = $("#txtOthersRemarks").val();
if ($.trim($('#RejectRemarks select').val()) == "Others" && TextBoxRemarks.trim() == "") {
document.getElementById("txtOthersRemarks").setCustomValidity("Other Reject Remarks is required");
$('#txtOthersRemarks select').focus();
return;
}
else if ($.trim($('#RejectRemarks select').val()) == "Others" && TextBoxRemarks.trim() != "") {
var txtRemarks = document.getElementById("txtRemarks");
//txtRemarks.value = $("#txtOthersRemarks").val();
txtRemarks.val = TextBoxRemarks;
//txtRemarks.value = TextBoxRemarks;
document.getElementById("txtOthersRemarks").setCustomValidity("");
return;
}
else {
document.getElementById("txtRemarks").setCustomValidity("Reject Remarks is required");
$('#RejectRemarks select').focus();
return;
}
}
else {
document.getElementById("txtRemarks").setCustomValidity("");
}
But when i implement this js it only changes values to checkbox and not send empty value to controller.
public ActionResult BankLinkVerify(UserInfo model, string btnApprove, string Remarks)
I'm trying to find where it goes wrong but could not analysis this. I need whatever user types in text box as remarks value.( default it goes other but when i do that js dropdown value goes null to controller).
Thank You!
Regarding your case, you can access the current value through the Request or FormCollection. You can read your OthersRemarks textarea value from the current Request using Request.Form:
In your Controller method:
string Remarks= Request.Form["OthersRemarks"].ToString()
I found another solution too..
FormCollection can also be used in controller
public ActionResult BankLinkApprove(UserInfo model, string btnApprove, FormCollection collection, string Remarks){
if (Remarks.Equals("Others")){
userInfo.Remarks = collection["OthersRemarks"].ToString();
}
else{
userInfo.Remarks = info.Remarks;
}
}

Hide checkbox/div based on textbox value

I have a dropdown, when i select an item its categoryId is assigned to textbox. Then i Have 2 checkboxes 'IsAnonymous' and 'ShowReport'. I want to implement that is the value in textbox is 1 then both checkbox will be visible and when value will be 2 then 'ShowReport' checkbox must be hidden.
javascript
var ReportDiv = $('#ReportDiv');
$('#cmbCategories').on('change', function () {
if ($(this).val() == '1') {
ReportDiv.hide();
}
else {
ReportDiv.show();
}
});
View
#Html.DropDownListFor(p => p.PollSurveyId, Model.PollSurveyDetails, "Select Poll/Survey", new { #class = "form-control", required = "required", #id= "DDPollName" })
#Html.TextAreaFor(p => p.CategoryID, new {id= "cmbCategories" })
<div class="form-group">
#Html.Label("Is Anonymous")
#Html.CheckBoxFor(p => p.IsAnonymous)
</div>
</div>
<div class="col-lg-3">
<div class="form-group" id="ReportDiv">
#Html.Label("Show Report")
#Html.CheckBoxFor(p => p.ShowReport, new { id= "CBReport" })
</div>
<!-- /.col-lg-6 (nested) -->
</div>
Added a picture to give idea of my page

When I pick default dropdown value with javascript, it doesn't trigger change

I have a textfield and a date textfield. I am trying to connect them with Javascript, but I encounter a problem. My script is:
<script>
$("#solDate").change(function () {
if ($(this).val().trim() == '') {
$("#caseStatus").val('In Progress');
$("#solvedBy").val('Pick an option');
$("#solvedBy").change();
}
else if ($(this).val().trim() != '' && $("#solvedBy").val().trim() == '') {
$("#caseStatus").val('Solved');
$("#solvedBy").val('Please, pick the issue solver');
$("#solvedBy").change();
}
});
</script>
When date is picked from calendar, it should set a value 'Please, pick the issue solver'. It works perfectly.
Then, if you entered the date incidentally, it should return the previous default value - "Pick an option".
In both cases, a change is triggered.
Then, another trigger is listening for these changes.
<script>
$("#solvedBy").change(function () {
if ($(this).val() == 'Please, pick the issue solver') {
$("#saveBtn").attr('disabled', true);
$("#slvByValMsg").text('You have solution date and no solver');
}
else if ($(this).val().trim() == '' && $("#solDate").val().trim() != '') {
$("#saveBtn").attr('disabled', true);
$("#slvByValMsg").text('You have solution date and no solver');
}
else {
$("#saveBtn").attr('disabled', false);
$("#slvByValMsg").text('');;
}
});
</script>
After my troubleshooting, it turns out, that the first if statement on the first script doesn't trigger a change. It may be because it doesn't recognize the default pick option with value ''. I am not sure. Anyhow, when I delete the date from the textfield, the value of the other textfield doesn't change to 'Pick an option', but to ''.
HTML Code:
#Html.LabelFor(model => model.Solution_Date, htmlAttributes: new { #class = "control-label col-md-2" })<sup> 1 </sup>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Solution_Date, new { #id = "solDate", #class = "one", #type = "datetime" })
<br />
#Html.ValidationMessageFor(model => model.Solution_Date, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.Solved_by, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="dropdown">
#Html.DropDownListFor(model => model.Solved_by, (IEnumerable<SelectListItem>)ViewBag.SlvBy, "Pick an option", new { #id = "solvedBy" })
<br />
#Html.ValidationMessage("Solved_by", "", new { #id = "slvByValMsg", #class = "text-danger" })
</div>
I know there are probably better ways to do this, but I'm looking for a resolution mainly because I don't know why this change trigger doesn't fire.
Thanks in advance!
I've found what causes the issue. It turns out that
$("#solvedBy").val('Pick an option');
Cannot be executed, because this is the default option and the value behind it is ''. This must be messing with the .change() triggers and created havoc in other scripts as well.
I changed it to
$("#solvedBy").val('');
...and everything works now.

hide or show form control based on ddl selection in MVC using jQuery

My problem is similar to the one in show divs based on drop down selection. I have a dropdown list in a div with four options. Depending on which is selected I want one of two other controls to show in the next div and in one case it will show an EditorFor and I want the value populated. Here's what I have...
<div class="form-group">
#Html.Label("OriginType", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("OriginType", ViewData["OriginType"] as SelectList, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group" id="pnlOrigin">
#Html.LabelFor(model => model.Origin, htmlAttributes: new { #class = "control-label col-md-2" })
<div id="pnlOrigin1"class="col-md-4">
#Html.DropDownList("ddlORDER_10", (IEnumerable<SelectListItem>)ViewBag.Order, "Select an Order Number", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Origin, "", new { #class = "text-danger" })
</div>
<div id="pnlOrigin2"class="col-md-4">
#Html.EditorFor(model => model.Origin, new { htmlAttributes = new { #class = "form-control", #id = "tbOrigin" } })
#Html.ValidationMessageFor(model => model.Origin, "", new { #class = "text-danger" })
</div>
</div>
So what I need is when a user selects from the OriginType dropdown (STK, PO, WO, OTHER) it will show or hide the dropdown list or EditorFor in the pnlOrigin div. If PO or WO is selected it will show the ddl. If OTHER or STK is selected it will show the EditorFor, and in the case of STK it will prepopulate the Editor with STK.
I've tried to modify the function in the referenced post but it's not hiding the controls initially and a selection from the OriginType dropdown list isn't having any affect?
Here's the jQuery I created. I'm not sure where I'm going wrong.
$(document).ready(function () {
function ShowOptions(originType) {
if (OriginType == "0"){
$("#pnlOrigin").hide();
$("#pnlOrigin1").hide();
$("#pnlOrigin2").hide();
// hide all before show
var showOriginPanel = false;
}
if (OriginType == 'STK') {
$("#pnlOrigin").show();
$("#tbOrigin").val('STK');
showOriginPanel = true;
}
if (OriginType == 'PO') {
$("#pnlOrigin1").show();
showOriginPanel = true;
}
if (OriginType == 'WO') {
$("#pnlOrigin1").show();
showOriginPanel = true;
}
if (OriginType == 'OTHER'){
$("#pnlOrigin2").show();
showOriginPanel = true;
}
if(showOriginPanel) {
$("#pnlOrigin").show();
}
}
ShowOptions($("#OriginType").val());
$("#OriginType").change(function () {
ShowOptions($(this).val());
});
});
Any help would be greatly appreciated!
I seem to have found the problem with my code although I'm not sure why it affected the function. I had the htmlAttribues declared for the two hidden controls as "new { htmlAttributes = new { #class = "form-control" } }". Once I changed them to "htmlAttributes: new { #class = "form-control" }" the function started working properly.
I also had to add some .hides in case the user changed their initial selection prior to posting.

How to pass both the model value and javascript value to controller

I am submitting the form which has the css dropdownlist for gender how to submit the gender selected value to controller i am getting tht value null
<div class="regi-field-set">
<div id="ddlgender" class='selectBox' tabindex="7">
<span class='selected' id="gender">gender</span>
<span class='selectArrow'>&#9660</span>
<div id="disableasterisk5" style="padding-bottom:8px"><span class="required">*</span></div>
<div class="selectOptions" id="genderSelectOptions">
<span class="selectOption" id="ddlgen">male</span>
<span class="selectOption" id="ddlgen1">female</span>
</div>
</div>
<div class="regi-field-set">
#Html.TextBoxFor(model => model.DOB, new { #class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
<div id="disableasterisk7"><span class="required">*</span></div>
<div class="clear"></div>
#Html.ValidationMessageFor(model => model.DOB)
</div>
how to pass both value to controller all other fields in the form are using html.helper fields only gender field is css implemented
Is there any way to pass the entire model and the gender selected value to controller
please help
If I understood your question, the answer of passing to the View both the "model" and a list of something else to use in a dropdown list can be done by the following code:
Controller
....
var model = service.GetMyThing(id);
var genderList= service.GetGenders().Select(p =>
new SelectListItem { Value = p.Id.ToString(), Text = p.Name }).ToList();
ViewBag.GenderList = genderList;
return View(model);
View
....
#Html.DropDownList("GenderId",(IEnumerable<SelectListItem>)ViewBag.GenderList)
....
<div class="regi-field-set">
#Html.TextBoxFor(model => model.DOB, new { #class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
<div id="disableasterisk7"><span class="required">*</span></div>
<div class="clear"></div>
#Html.ValidationMessageFor(model => model.DOB)
</div>
Note: this is NOT the only solution, custom HTMLHelpers can be used to draw the combo.
using ajax you can achieve this : don't use form & declare your attributes like this in tags:
#Model.idText
<input type="text" id="textValue"/>
<input type="submit" id="btnSubmit"/>
jquery:
$(function (e) {
// Insert
$("#btnSubmit").click(function () {
$.ajax({
url: "some url path",
type: 'POST',
data: { textField: $('#textValue').val(), idField: '#Model.idText' },
success: function (result) {
//some code if success
},
error: function () {
//some code if failed
}
});
return false;
});
});
Hopefully it will help you

Categories

Resources