Below is code that is supposed to make a text box appear/disappear based on whether or not a box is checked (the text box is hidden when the page loads). All the alerts are firing properly, however I cannot get the check box to .show() function to work.
Here is the jQuery. This from inside the document.ready function. You can see from what I've commented out the other two methods I've tried (neither worked).
$('#OverrideRegionInd').click(function () {
alert($(this).is(':checked'));
if ($(this).is(':checked')) {
alert("inside if");
$('#Region').show();
//$('#Region').css("display", "inline");
// $('#Region').toggle();
$('#territoryName').html("");
$('#Region').val("");
} else {
alert("inside else");
$('#Region').hide();
//$('#Region').css("display", "none");
// $('#Region').toggle();
}
});
Here is the code from the view
<div class="M-editor-label">
#Html.LabelFor(model => model.Region)
</div>
<div class="M-editor-field" id="territoryName">
#Html.TextBoxFor(model => model.Region, new { style = "display: none;" })
#Html.ValidationMessageFor(model => model.Region)
</div>
Here is the HTML once the page is rendered for this particular set of <div>'s
<div class="M-editor-label">
<label for="Region">Territory</label>
</div>
<div class="M-editor-field" id="territoryName">
<input id="Region" name="Region" style="display: none;" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Region" data-valmsg-replace="true"></span>
</div>
That's because you're setting:
$('#territoryName').html("");
That's the parent of #Region, you're effectively removing the #Region element with that line. Take that out and it'll work fine.
DEMO
Related
I am trying to get the built in HTML5 validation working in my Blazor application but it just gets ignored.
This is my Razor code
<form class="row">
<div class="form-row">
<label for="exampleFormControlInput1" class="form-label">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="name#example.com" #bind="#details.Email">
</div>
<div class="form-row">
<label for="exampleFormControlInput1" class="form-label">Phone</label>
<input type="tel" class="form-control" id="exampleFormControlInput1" placeholder="name#example.com" #bind="#details.Phone">
</div>
<div class="form-row">
<button type="submit" class="btn btn-primary" #onclick="SubmitForm">Send</button>
</div>
</form>
</div>
#code {
private ContactDetails details = new ContactDetails();
public async void SubmitForm()
{
var result = await Http.PostAsJsonAsync("Contact", details);
}
}
I know I can use Blazors validation, but I want to just use the built in HTML5 validation for this as it is a very basic form. How do I stop the SubmitForm code from being run if the HTML5 validation is triggered?
If I remove the code from the SubmitForm() method obviously nothing then happens when it enters that method and it goes back to the webpage and the html5 validation messages are displayed, however clearly the method is still being fired. Is there a way to stop the code running if there are html5 validation errors?
Okay, I have worked out how to do this.
Simply add and onsubmit event to the Form tag and then remove the onclick from the button.
<form class="row" #onsubmit="SubmitForm">
This then works as expected.
Now there are clearly lots of benefits to using the built in Blazor forms components but sometimes just working with standard html forms is needed and thankfully there is a solution to do that.
Use Regex by adding this using #using System.Text.RegularExpressions;
Valid email : komaei#live.com
Invalid emails : komaei , komaei# , komaei#live.c
<div class="form-group row">
<label for="#nameof(createModel.Email)" class="col-sm-2 col-form-label text-right">Email : </label>
<div class="col-lg-7 col-sm-10">
<InputText type="email" class="form-control" placeholder="Email" required
id="#nameof(createModel.Email)" #bind-Value="createModel.Email">
</InputText>
</div>
</div>
#code {
private Customer createModel = new();
private async Task SubmitForm()
{
var emailPattern = #"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$";
Regex regex = new Regex(emailPattern);
if (regex.IsMatch(createModel.Email) == false)
{
await JsRuntime.InvokeVoidAsync("alert", "Email is not valid!");
return;
}
var response = await _http.PostAsJsonAsync("Customers/Create", createModel);
if (response.IsSuccessStatusCode) // 200
_navigationManager.NavigateTo("Customers");
else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
await JsRuntime.InvokeVoidAsync("alert", response.Content.ReadAsStringAsync().Result);
}
}
I am working on an asp.net core mvc web application, and i have added the following field to show google recaptcha version 2:-
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="#ViewData["ReCaptchaKey"]">
</div>
</div>
</div>
//code goes here
#section Scripts {
<script src='https://www.google.com/recaptcha/api.js'></script>}
and inside my action method i am checking if the user select the recaptcha or not, as follow:-
public async Task<IActionResult> SearchNPI(ContactinfoCreate ci)
{
//add uncompleted entry
ViewData["ReCaptchaKey"] = _configuration.GetSection("GoogleReCaptcha:key").Value;
if (!ReCaptchaPassed(
Request.Form["g-recaptcha-response"], // that's how you get it from the Request object
_configuration.GetSection("GoogleReCaptcha:secret").Value,
_logger
))
{
ModelState.AddModelError(string.Empty, "Please enter CAPTCHA");
}
but on the client side how i can ake the recaptcha required filed, so the user can not submit the form unless he/she select the recaptcha?
You can determine whether clicks recaptcha before submit by triggering the data-callback method of recaptcha, and then adding a hidden control.
After clicking recaptcha,assign a value to hidden control in data-callback method, and then judge the hidden value in the form submit method to determine whether this form can be submitted.
<form method="post">
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<div class="g-recaptcha" data-sitekey="#ViewData["ReCaptchaKey"]" data-callback="recaptchaCallback"></div>
<input type="hidden" value="" id="isClickCaptcha" />
<span class="text-danger" id="validationText"></span>
</div>
</div>
<input id="Submit1" type="submit" value="submit" />
</form>
<script src="https://www.google.com/recaptcha/api.js?hl=en-US"></script>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
var recaptchaCallback = function () {
$("#isClickCaptcha").val("yes");
};
$("form").submit(function () {
if ($("#isClickCaptcha").val() == "") {
event.preventDefault();
$("#validationText").text("Please enter CAPTCHA!");
return false;
}
})
</script>
Here is the test result:
in javascript I imagine you have a function called recaptchaCallback which is responsible to perform the form submit. It should look like this
function recaptchaCallback(token) {
}
well, just add
if (!token || token === '') {
alert("Could not verify that you are a human");
return;
}
I have this code:
<div class="col-xs-6 col-sm-3">
#Html.DropDownList("cssFiles", (IEnumerable<SelectListItem>)ViewBag.cssFiles, "Crear Nuevo", new { #class = "form-control", #id = "selCssFile" })
<span>
<input type="text" class="form-control" id="txtFileName" style="display:none;" placeholder="Nombre del archivo">
</span>
</div>
I want to add a Javascript event for show the "txtFileName" when "Crear Nuevo" is select, and hide it when the dropdown change
Basically you need to attach click event on your dropdown element.
Code
$('#selCssFile').on('change',function(){
//implement code after selected the option
});
hi am developing mvc project using c#
currently am working on employee system model
I have designed view below like this
#Html.CheckBoxFor("value", new {data_divToDisable="SSLCSection",#class="SelectSection" })
<div id="SSLCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PUCSection",#class="SelectSection" })
<div id="PUCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="GraduationSection",#class="SelectSection" })
<div id="GraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PostGraduationSection",#class="SelectSection" })
<div id="PostGraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
here I need to disable sections when loading view based on checkbox value
like if checkbox is checked no need to disable that section otherwise it would be disable
I have written jquery like this
$(document).ready(function () {
$(".SelectSection").attr('checked', false,function(){
var id = $(this).find(".DisableDiv");
alert(id);
$(this).find(".DisableDiv").find('input, textarea, select,table').each(function () {
$(this).prop('disabled', true);
});
});
this is not doing anything for us
please help and your help would be greately appreciated
Please Note I have using data-Attribute to simplify the jquery and while each time loading the page it has to disable the sections based on checkbox value (hint:it has to disable if checkbox value is false )
You could try the follow, excuse the pseudo code.
HTML
<input class="SelectSection" type="checkbox" >hello1</input>
<div id="SSLCSection" class="DisableDiv" >
<input type="input">Test</input>
<textarea>Test1</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox">hello2</input>
<div id="PUCSection" class="DisableDiv" >
<input type="input">Test2</input>
<textarea>Test12</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox" checked>hello3</input>
<div id="PostGraduationSection" class="DisableDiv" >
<input type="input">Test3</input>
<textarea>Test3</textarea>
</div>
jQuery
$(document).ready(function () {
$(".SelectSection[type='checkbox']").each(function (i, o) {
if ($(o).is(":checked")) {
$(o).next('div').find('input,textarea').each(function (i, o) {
$(o).prop('disabled', true);
});
}
});
})
The above assumes that your next element after the relevant checkbox is the div in question which holds the elements that need to be disabled.
Before some people start yelling, I realize there is similar questions up, but their all dealing with single entries...
I have a long form and want to use a generic method of dealing with the re-displaying of data.
Please note : this is an asp.Net MVC 4 application using razor2 views
Example of one of the fields,
<div class="control-group">
<label class="control-label">#Html.LabelFor(m => m.Name)
<span class="required">*</span>
</label>
<div class="controls">
#Html.TextBoxFor(m => m.Name, new { #name = "nameInput" })
</div>
</div>
My think was to add an ID to each Textbox...
Example of how is might be displayed on the confirmation view..
<div class="control-group">
<label class="control-label">Name:</label>
<div class="controls">
<span class="text display-value" data-display="nameInput"></span>
</div>
</div>
Then render that value using data-display with the ID...
jQuery that I thought would deal with it...
var displayConfirm = function() {
$('.display-value', form).each(function(){
var input = $('[name="'+$(this).attr("data-display")+'"]', form);
if (input.is(":text") || input.is("textarea")) {
$(this).html(input.val());
} else if (input.is("select")) {
$(this).html(input.find('option:selected').text());
}
});
}
Unfortunately this does not appear to be working correctly....
Can anyone point out / re-solve the issue ?
Got it, I needed to use the name in the model rather then assigning names.
Got correct names from "page view source", and simply plugged that value into data-display tag.