html button is activating asp validation in html input form - Why? - c#

I'd want to ask why after clicking on my custom button that just appends text to div that's inside form, then it activates asp validation of that form?
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div id="append_area">
</div>
<button id="appendChild" onclick="addText()">add new thing</button>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
<script>
function addText()
{
var div = document.getElementById('append_area');
div.innerHTML += `test`;
}
</script>

Set your button type as button
<button type="button" id="appendChild" onclick="addText()">add new thing</button>

As described in W3C documentation, default type of the <button> element can vary across different browsers, so it is a good practice to always specify it explicitly.
In this case, the default value is submit, so by clicking the button you are inadvertently causing the submit action and hence also validation to be performed as well.
To fix this, just specify the button type explicitly as button:
<button type="button" />

You can also do this:
<script>
function addText()
{
var div = document.getElementById('append_area');
div.innerHTML += `test`;
return false;
}
</script>
then you can call in code onclick="return addText()"

When you submit a form to a CGI program that resides on the server, it is usually programmed to do its own check for errors. If it finds any it sends the page back to the reader who then has to re-enter some data, before submitting again. A JavaScript check is useful because it stops the form from being submitted if there is a problem, saving lots of time for your readers.
<button type="button" id="ChildForm" onclick="add()">add new </button>
The CGI script is still more reliable, as it always works regardless of whether JavaScript is enabled on the client-side or not; but having this extra safety barrier is a nice thing to have in place. It makes your page much more user-friendly and takes out the frustration of having to fill out the same form repeatedly. It's also very precise, as you can point out the exact field where there's a problem.

Related

Clicking 2 submit buttons in the same page

I have a project in .Net Core with Razor Pages and I have the form bellow that contains some input fields and 2 submit buttons.
<form class="form-style" method="post" id="createForm">
<div class="form-group button-position col-md4">
<input type="submit" id="placeRequest" name="placeRequest" value="Place Request" class="btn btn-primary" />
</div>
<div class="form-group button-position col-md4">
<input type="submit" value="GetHour" asp-page-handler="Hour" class="btn btn-primary btn-style" formnovalidate />
</div>
</form>
I need to be able to click the first submit button (GetHour) and then click the second one (Placer Request)
In my Razor Page model I have
public async Task<IActionResult> OnPost()
{
//code that will be executed when the Place Request button is clicked
}
public async Task OnPostGetHour()
{
////code that will be executed when the Get Hour button is clicked
}
The problem is that I am not allowed to make the 2 submits. If I only do one of them, it works but the second one does nothing
Is there any way I could make both of the submits?
This is because once you click the first submit button, The page does a redirect and loads again.
This is the nature of form submission. If you want to click both the buttons. Change the button type from "submit" to "button".
Then create 2 click handlers and handle the form submitting using Ajax
<form class="form-style" method="post" id="createForm">
<div class="form-group button-position col-md4">
<input onclick="onBtn1Click()" type="button" id="placeRequest" name="placeRequest" value="Place Request" class="btn btn-primary" />
</div>
<div class="form-group button-position col-md4">
<input onclick="onBtn2Click()" type="button" value="GetHour" asp-page-handler="Hour" class="btn btn-primary btn-style" formnovalidate />
</div>
</form>
Then write 2 JavaScript functions
function onBtn1Click()
{
//Submit code via Ajax here
}
function onBtn2Click()
{
//Submit code via Ajax here
}

Focus back on textbox after submitting using ASP.NET Core MVC

I am trying to introduce a dynamic search function in my project. I have created a search form in my view which submits on keyup but the issue that I'm not facing is that when the view reloads, the text box is no longer in focus and so the user needs to click back onto it which obviously isn't ideal.
My view is set up as follows:
<form id="searchForm" asp-action="Index" method="get">
<div class="row">
<div class="col-9">
<input type="text" id="fooSearch" name="searchString" value="#ViewData["currentFilter"]" class="form-control" />
</div>
<div class="col-3">
<div class="row">
<div class="col-6">
<input type="submit" value="Search" class="btn btn-outline-secondary form-control" />
</div>
<div class="col-6">
<a asp-action="Index" asp-route-recent="true" class="btn btn-outline-secondary form-control">Recent</a>
</div>
</div>
</div>
</div>
</form>
with the following JQuery script to submit on keyup
$(function () {
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
});
});
</script>
Can anyone help me to retain focus on the search textbox when the DOM is loaded?
To give the focus back to the searchbar, you can use jQuery's focus(), e.g.:
$("#fooSearch").focus();
Now, where you place this depends on whether your form submit is synchronous (and makes the page reload) or asynchronous.
If the submit is asynchronous, then you can place this in your keyup event handler, right after the code that submits:
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
$("#fooSearch").focus(); //focus back on the search bar
});
Otherwise, you will need to call focus() from an onload event:
$(document).ready(function() {
$("#fooSearch").focus();
});
In all cases, first load or reload (submit), the focus should be on the search textbox so I think that you can just focus the textbox on load.
$(function() { $("#fooSearch").focus();});
The problem you may encouter is that the cursor will not be in the end of the keywords. So I think that the best option here is to use Ajax to the update the results each time the user change the keywords. Maybe waiting a few seconds before each update is a good idea also.
If you are using html5 you can just add autofocus to your html tag something like:
<input type="text" id="fooSearch" autofocus ="autofocus" name="searchString" value="#ViewData["currentFilter"]" class="form-control" />

Simple Razor C# .Net form: Checkboxes and Session Variable settings

First, I want to explain I do not know any Razor or C#. I have a client that I build out high-fidelity prototyping for. Some of the elements are getting kind of advanced where JavaScript is not working for me anymore.
The Ask:
I have a modal that I trigger (using bootstrap), this modal has some checkboxes in a form. Each checkbox will trigger to turn on or turn off a session that will turn certain elements on or off on a series of 5-6 pages. Here I am just working with one of those sessions. I can duplicate once I figure this out. Any help will be greatly appreciated.
Code:
#{
if (Request.Form["fitscorechecked"] != null && Request.Form["fitscorechecked"] == "on") {
Session["fitscore"] = "on";
} else {
Session["fitscore"] = "off";
}
}
My Form:
<form method="post">
<div class="row">
<div class="col-sm-12 bottom5"><input type="checkbox" id="fitscorechecked" name="fitscorechecked" value="true"/> Show fit score during adjustment</div>
<div class="col-sm-12 bottom5"><input type="checkbox" id="Anonymous" name="Anonymous" value="true" /> Make contributors anonymous</div>
<div class="col-sm-12 bottom5" data-toggle="tooltip" data-html="true" title="<h5>Advanced Options</h5><h6>Will allow you to view related tasks, manually adjust patterns (power users only), and the ability to download responses.</h6>">
<input type="checkbox" id="Advanced" name="Advanced" value="true" /> Show advanced options</div>
</div>
<div class="prototype-btngroup-center">
<a class="btn btn-default prototype-btn-spacersm" data-dismiss="modal">Cancel</a>
<a class="btn btn-primary" type="submit" value="submit" href="#stepAlign6" data-toggle="tab" data-step="5" data-dismiss="modal">Begin Alignment</a>
</div>
</form>
<form>
I have never built a form in .net so I am really lost. I just need something very simple that does not use controllers. Much of this code is show and then redone based on the updates from the product team, so something that is simple and easy to adjust.

Call a controller action from view

I am trying to call an action from the controller using onclick method. For some reason it's not returning action I want, it's always jumping to public ActionResult Index() by default.
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Register" class="btn btn-default" onclick="location.href='#Url.Action("RegisterIndex", "Register")'"/>
</div>
</div>
NOTE
I have created view automatically with a model. It's validating input for me by using already generated javascripts. If I change input tag to button it's not gonna do the required validation.
window.location.href does a GET request, that's why it didn't pass your input values to the server.
When you have <input type="submit"> inside a form, clicking it will submit the form with all data you need. I think this is what you want, but you just want it to submit to another action.
To achieve this, I suggest this solution:
Create a hidden field in the form. Its data will be sent to the server.
In your server, base on that hidden value, you can redirect to the appropriate action
Please feel free to ask me if you find anything unclear :)
The <input type="submit">, when inside a form element, will submit the form when clicked unless you return false or event.preventDefault();
returning false will prevent the default behavior for your submit.
EDIT
window.location.href will cause a GET request so your data will not be posted using this method.
HTML
#using (Html.BeginForm())
{
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnSubmit" value="Register" class="btn btn-default"/>
</div>
</div>
}
Javascript
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () { window.location.href = '#Url.Action("RegisterIndex", "Register")'; return false; });
});
</script>

how to create two buttons within form and have only one submit form

I am trying to create a "next" button and a "back" button in my form. I want the "next" button to validate and submit the form. And I want the "back" button to simply go back to the "cart" page. But the "back" button keeps validating and trying to submit the form.
Here is my code:
<div class="buttons">
<button class = "button" id = "back">Back</button>
<input type="submit" value="Next" class="button" />
</div>
The reason I need the back link to be a button is so that it will look the same as the "next" button. Any ideas how I can get this working correctly?
A <button> element always submits the form. The same goes for a <input type="submit" /> element.
But a <input type="button" /> will not submit the form. That's what you want.
<div class="buttons">
<input type="button" class="button" id="back" onclick="window.location = '#Url.Action("Index", "Cart")';">Back</a>
<input type="submit" value="Next" class="button" />
</div>
Edit I'm not sure if you can put that inside an <a> element though. I reworked my example to use click events rather than a link. If it is valid to put inside a <a> element (can anyone confirm?), you can do it like that as well.

Categories

Resources