Div class show after refresh page - javascript

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();
}
});
});

Related

Custom Client Side Validation through JavaScript

I am developing a project in MVC 5. There is are some form input field where I need to put custom client side validation using jquery/javascript. The expected behaviour is for example when someone tries to type alphabets or special characters in the phone input, there should be a validation error displayed below the field or atleast an alert box should get triggered containing the error. I have added the custom validation file in my scripts folder. I can see some basic logs I wrote on the console of the page. I am facing challenges on the js function where we can capture the id of the field and provide custom logic for it. Here is my code. Please suggest what can be done.
#model StudentMVCApp.Models.registration
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm(new
{
#id = "registerFormId",
#class = "form-horizontal",
role = "form"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Register a new student</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.firstname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.firstname, new { htmlAttributes = new { #class = "form-control", data_val = "true", data_val_required = "Please dont provide empty name!" } })
#Html.ValidationMessageFor(model => model.firstname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.lastname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.lastname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.lastname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.phone, new { htmlAttributes = new { #class = "form-control",#id="phoneid" } })
#Html.ValidationMessageFor(model => model.phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.email, "", 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/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Unobtrusive")
#Scripts.Render("~/CustomValidation")
}
Here is my Custom JavaScript
console.log("I am working JS");
(function ($) {
console.log("This function is captured");
var phone = $("#phoneid").val();
console.log(phone);
if (phone != null)
console.log(phone);
else if (phone == 100)
alert($(this).val());
else if (phone == "abc")
alert(phone);
else if (phone == abc)
alert(phone)
})(jQuery);
I tried different tutorials and experimented with some js functions. But couldn't get it working using id of the field.
I would recommend using jquery.validation.unobstrusive package scripts on your view:
<script src="~/Scripts/Jquery/jquery-1.9.1.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.unobtrusive.js"></script>
and adding your own custom validation on a form element by writing jquery such as:
$("#myinput").rules("add", {
required: true,
minlength: 2,
messages: {
required: "Required input",
minlength: jQuery.validator.format("Field needs to be more than{0}")
}
});
More info can be found at https://jqueryvalidation.org/rules/
You need to attach your code above to an event, input or submit for example.
Now it only runs once, when the page loads
something like
$(function() {
console.log("This function is captured");
const $phone = $('#phoneid');
$phone.on('input',function() {
const val = $(this).val(); // get the value - it is a string
console.log(val);
if (val == 100) console.log('100'); // note the == coerces the numeric string to number
else if (phone == 'abc') console.log('abc');
});
});

Cascading population of a mvc dropdown

I have 2 DropDowns in an MVC application. Trying to populate the second one based on the first one's chosen value (Cascading)..
Since I am rather new to MVC this is giving me a little problem..
This is how ot looks in my View..
I am getting the data based on the selection in the first DropDown
This is the JS code for retriving the data..
<script type="text/javascript">
$('#AllShips').change(function () {
var selectedShip = $("#AllShips").val();
console.log(selectedShip);
var arrivalSelect = $('#AllShipArrivals');
arrivalSelect.empty();
if (selectedShip != null && selectedShip != '') {
$.getJSON('#Url.Action("GetArrivals")', { ShipID: selectedShip }, function (arrivals) {
console.log(arrivals);
if (arrivals != null && !jQuery.isEmptyObject(arrivals))
{
arrivalSelect.append($('<option/>', {
value: null,
text: ""
}));
$.each(arrivals, function (index, arrival) {
console.log(arrival.Value);
console.log(arrival.Text);
arrivalSelect.append($('<option/>', {
value: arrival.Value,
text: arrival.Text
}));
});
};
});
}
});
Here is my HTML
<div class="col-lg-2 form-group">
#Html.LabelFor(model => model.AllShips, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#if (Model.AllShips != null)
{
#Html.DropDownListFor(model => model.ShipID, Model.AllShips, new { #class = "form-control", id = "AllShips" })
#Html.ValidationMessageFor(model => model.ShipID, "", new { #class = "text-danger" })
}
</div>
</div>
<div class="col-lg-2 form-group">
#Html.LabelFor(model => model.AllShipArrivals, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#if (Model.AllShipArrivals != null)
{
#Html.DropDownListFor(model => model.ArrivalId, Model.AllShipArrivals, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ArrivalId, "", new { #class = "text-danger" })
}
else
{ #Html.DropDownListFor(model => model.ArrivalId, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ArrivalId, "", new { #class = "text-danger" })}
</div>
</div>
Still the second DropDown is not changing (initially I populate it with a list of all Arrivals, yes I know..not a good option)
Any idea what I am doing wrong here??
Thanks for the HTML, it is what I suspected. In your JS your are referencing 2nd DDL by var arrivalSelect = $('#AllShipArrivals'); but there is no such element (it is, but this is just a label), instead you should use:
var arrivalSelect = $('#ArrivalId');
Make 'PartialView' or 'ViewComponent' for the second Dropdown, do ajax call on changing selection in the first dropdown, choose data depending on the value you passed during the ajax call, pass the data into your partial view and return it.
Something like
public IActionResult SecondDropdownPartial(int selectedShip)
{
var data = GetSomeData(selectedShip);
return Partial("ViewName", data);
}
In js 'success' you get your view in response. Replace it on the page with
$('#container').html(response);
for example.
More information : Rendering Partial Views using ajax
edited
try making the value to be empty string rather than null
emptyStr="";
arrivalSelect.append('<option value="${emptyStr}"> ${emptyStr} </option>');
arrivalSelect.append('<option value="${arrival.Value}"> ${arrival.Text} </option>');

Disable require message when radiobutton is selected to No

I am trying to disable required message when I checked radio button "No"
However when I submit form nothing happen, it's just redirect to same page and required message is display
Updated code
//hide/show chapela Yes/No
$(document).ready(function () {
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
$(document).ready(function () {
var test = $(this).val();
if(test == 'No'){
$("hideChapel").prop("required", false);
}
else {
$("hideChapel").prop("required", true);
}
});
<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 {id="Yes", #class = "styled", htmlAttributes = new { #checked = "true"} })
Yes
</label>
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "No", new {id="No", #class = "styled", htmlAttributes = new { #checked = "true" } })
No
</label>
#Html.ValidationMessageFor(model => model.Chapel, "", new { #class = "text-danger" })
</div>
</div>
RENDERED HTML
<label class="radio-inline">
<div class="choice" id="uniform-No"><span class="checked"><input checked="checked" class="styled" htmlattributes="{ checked = true }" id="No" name="Chapel" type="radio" value="No" autocomplete="off"></span></div>
No
</label>
<input class="styled" htmlattributes="{ checked = true }" id="Yes" name="Chapel" type="radio" value="Yes" autocomplete="off">
You need to do it on form submit, you're currently setting the required attr on document load and on input click. Achieve like this:
$('form').submit(function(e)
{
e.preventDefault(); //stop form submitting straight away
var radio = $('.my-radio');
if (radio.val() === 'foo') {
//disable require msg e.g. (this is an example - not a copy + paste)
$('form input').each(function()
{
$(this).removeAttr('required')
})
}
$(this).submit()
})
ref:
https://api.jquery.com/removeAttr/

JQuery blocking post action MVC

I'm using this jQuery from CodePen https://codepen.io/dicson/pen/eJzoEX & it's working great however it is somehow blocking the FormMethod.Post action from firing. I'm not very experienced with JS / JQuery so hoping someone can help.
FORM
#using (Html.BeginForm("Login", "Authentication", FormMethod.Post, new { role = "form" }))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<form class="form">
<div class="f_row">
<label>Username</label>
#Html.TextBoxFor(m => m.Email, new { #name = "username", #type = "username", #class = "input-field", #required = "" })
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "text-danger" })
<u></u>
</div>
<div class="f_row last">
<label>Password</label>
#Html.PasswordFor(m => m.Password, new { #name = "pass", #type = "password", #class = "input-field", #required = "" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
<u></u>
</div>
<div class="form-group">
<input type="submit" value="GO" class="btn btn-default submit-btn input-field" />
</div>
</form>
}
JQUERY
var inP = $('.input-field');
inP.on('blur', function () {
if (!this.value) {
$(this).parent('.f_row').removeClass('focus');
} else {
$(this).parent('.f_row').addClass('focus');
}
}).on('focus', function () {
$(this).parent('.f_row').addClass('focus');
$('.btn').removeClass('active');
$('.f_row').removeClass('shake');
});
$('.resetTag').click(function(e){
e.preventDefault();
$('.formBox').addClass('level-forget').removeClass('level-reg');
});
$('.back').click(function(e){
e.preventDefault();
$('.formBox').removeClass('level-forget').addClass('level-login');
});
$('.regTag').click(function(e){
e.preventDefault();
$('.formBox').removeClass('level-reg-revers');
$('.formBox').toggleClass('level-login').toggleClass('level-reg');
if(!$('.formBox').hasClass('level-reg')) {
$('.formBox').addClass('level-reg-revers');
}
});
$('.btn').each(function() {
$(this).on('click', function (e) {
e.preventDefault();
var finp = $(this).parent('form').find('input');
console.log(finp.html());
if (!finp.val() == 0) {
$(this).addClass('active');
}
setTimeout(function () {
inP.val('');
$('.f_row').removeClass('shake focus');
$('.btn').removeClass('active');
}, 2000);
if (inP.val() == 0) {
inP.parent('.f_row').addClass('shake');
}
//inP.val('');
//$('.f_row').removeClass('focus');
});
});
If I dont load the jquery the form works fine.
I get an undefined log on the console when running the jquery

how to hide the validation message on click of the textbox in asp.net mvc?

when i am trying to hide the validation message onclick of the textbox it is not hiding could you please help me out
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #autocomplete = "off", onclick = "clearValidation()" })
#Html.ValidationMessageFor(m => m.Email, "", new { #style = "color:white; font-weight:normal; margin-left:-155px;" })
</div>
<script>
function clearValidation() {
document.getElementsByClassName("validation-summary-errors").style.color = "#ff0000";
}
</script>
Use this-
$.fn.clearValidation= function () {
$(this).each(function() {
$(this).find(".field-validation-error").empty();
$(this).trigger('reset.unobtrusiveValidation');
});
};

Categories