I have a simple Blazor Server app and would like to enable a button when there is text in an input, and disable the button if there is no text in the input. I have looked at and tried numerous examples, and have not come up with a working solution yet. This is for a page with a search button, which requires valid text before the search button becomes enabled.
So, when as a user enters a character in the text input, button is enable. If the user deletes all the text in the input, button is disabled.
Here is the simplified code:
#page "/InputExample"
<h3>Input Example</h3>
<input type="text" #onkeyup="#(e => EnableButton(e))" #bind="myInputText" />
#if (disableState == true)
{
<input type="button" value="I'm disabled" disabled="#buttonState">
}
else
{
<input type="button" value="I'm not disabled">
}
#code
{
private string buttonState = "disabled";
private string myInputText = "";
bool disableState = true;
public void EnableButton(EventArgs args)
{
if (myInputText.Length == 0)
{
disableState = true;
}
else
{
disableState = false;
}
}
}
I'm not very experienced with Blazor yet and I don't know if this will work, but I can't say this in a comment, so....
Use #bind:event="oninput" so that the event fires on change instead of on loss of focus.
Get rid of the event handler and use set in the bound property to set disabledState.
Also, you could use the code you have and just see if calling StateHasChanged() in the handler does the trick.
#page "/InputExample"
<h3>Input Example</h3>
<input type="text" #bind:event="oninput" #bind="myInputText" />
#if (disableState == true)
{
<input type="button" value="I'm disabled" disabled>
}
else
{
<input type="button" value="I'm not disabled">
}
#code
{
bool disableState = true;
private string _myInputText;
public string myInputText {
get{ return _myInputText;}
set{
_myInputText = value;
disableState = _myInputText?.Length < 1 ? true : false;
}
}
}
I'm also not very familiar with the Blazor, but if you want to achieve this by regular JavaScript in your Blazor app, you can add the function to .cshtml file (_Host.cshtml)
JS function:
function changeValue() {
var edValue = document.getElementById("myInputId");
var s = edValue.value;
if (s.length === 0) {
document.getElementById("myBtn").setAttribute("disabled", "true");
document.getElementById("myBtn").value = "I'm disabled";
} else {
document.getElementById("myBtn").removeAttribute("disabled");
document.getElementById("myBtn").value = "I'm not disabled";
}
}
And then can use it on .razor page e.g (Index.razor)
Index.razor
<input id="myInputId" type="text" onInput="changeValue()">
<input type="button" id="myBtn" value="I'm disabled" disabled="">
Related
I'm working in an ASP.NET MVC app and I want to disable a button when during OnSubmit event of the form, just for prevent double click of the users.
All JQuery part is working fine but I don't understand why, when I disabled the submit button, it always call the default Action of my controller.
Here is the cshtml code:
#using(Html.BeginForm()){
<input type="submit" value="Submit"/>
}
<script>
$(function(){
$("form").submit(e=>{
$('input[type="submit"]').prop("disable",true)
})
})
</script>
The JQuery part works and make the button disabled.
My controller:
public class MyController:Controller{
public ActionResult MyController(ExampleModel model){
return View(model);
}
[HttpPost,ActionName("MyController")]
public ActionResult FormSubmmit(ExampleModel model){
//Do some checks
return View(model);
}
}
The case is that if I make the button disabled, the form always call the action 'MyController' instead of the action FormSubmit (is which I want to call).
Do somebody know why can be the reason of this "error"?
try this
#Html.BeginForm("FormSubmit", "My", FormMethod.Post) {
<input type="submit" value="Submit"/>
}
and remove [HttpPost,ActionName("MyController")] from the action, it is a very strange attribute
This is a fast and reliable way of disabling the button to prevent any "Double click"
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
You can see the source here
Another way of doing this when submitting is to do an overlay and then redirect
function(Optional, I use it to stop the overlay and just to basically inform the user that the function is done)
HTML:
<input type="submit" onclick="return FunctionOverlay(this);" />
<script>
function FunctionOverlay(btnElement)
{
showOverlay(btnElement);
$('#myForm').submit();
}
</script>
JS:
function showOverlay(buttonElement) {
$(buttonElement.parentNode).css('position', 'relative');
$bgColor = $(buttonElement).attr('data-overlay-color');
if ($bgColor === undefined) {
$bgColor = '#fff';
}
$(buttonElement.parentNode).append('<div class="button-overlay" style="background-color:' + $bgColor + ';"><img src="images/blahblah.gif" /></div>'); //.css('background-color', $bgColor)
}
You can use this to create your own overlay GIF
and then in your controller where you are calling the Method you can end it with
return View("ButtonClicked");
and in your home page create a cshtml ButtonClicked.cshtml
and just create a landing page where you can insert some text for example:
<div class="row">
<div class="col">
<p> Thank you for clicking😊</p>
</div>
</div>
Another option is doing an overlay with a timeout
$('form').submit(function () {
var button = $('#button');
var oldValue = button.value;
var isDisabled = true;
button.attr('disabled', isDisabled);
setTimeout(function () {
button.value = oldValue;
button.attr('disabled', !isDisabled);
}, 3000)
});
Firstable, thank for answer! And I just find the solution.
The problem of the code was if I use disabled it change the request metadata during the form submit event, so I can not make the button disabled.
I fount this solution, it just take off the pointer events from the button and then it prevent the double submit problem.
$('input[type="submit"]').css("pointer-events","none")
I am using Blazor framework with ASP.NET Core 3.0.
I have a Input Box and I added a Label HTML next to it. When user enters, say 5, in the Input Box, the Label should show calculated value of 5/2. That is, value of Input Box divide by 2.
In the Blazor framework, I am not understanding how to add jQuery.
Code is something like this:
<div class="col-sm-4">
<div class="justify-content-center mb-2">
<input type="text" class="form-control form-control-sm border border-secondary" #bind="myModel.CarWeight[index]" />
</div>
</div>
#if (myModel.AppType == "LC" || myModel.AppType == "LN")
{
decimal calcRes = Convert.ToDecimal(myModel.CarWeight[index]) / 2;
<div class="col-sm-4">
<div class="justify-content-center mb-2">
<label class="col-form-label"><b>calcRes</b></label>
</div>
</div>
}
Please note this line: myModel.CarWeight[index]
When the page is loaded, it creates an entry Form of 5 rows and 2 columns. 5 input boxes. When user fills any of the input box, I want the corresponding label to show the calculation.
You can update bind value on specific event
#bind:event="oninput"
See https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-5.0
You get this very simple code
#page "/"
<input type="number" #bind="inputVal" #bind:event="oninput" />
<label>#(Convert.ToDouble(inputVal)/2)</label>
#code{
string inputVal = "0";
}
Maybe somebody will come up with better idea to achieve what you want, but currently you could try something like this with C# code (.NET 5.0.103):
#page "/SampleComponent"
<input type="number" #bind="Operations[0].Input" #oninput="#( (input) => Calculate(input, 0))"/>
<label>#Operations[0].Result</label>
<input type="number" #bind="Operations[1].Input" #oninput="#( (input) => Calculate(input, 1))"/>
<label>#Operations[1].Result</label>
#code {
public List<Operation> Operations = new List<Operation>();
protected override void OnInitialized()
{
base.OnInitialized();
Operations.Add(new Operation{Input = 0, Result = 0});
Operations.Add(new Operation{Input = 0, Result = 0});
}
public void Calculate(ChangeEventArgs input, int id)
{
float result;
if(float.TryParse((string)input.Value, out result))
{
Operations[id].Result = result/2;
}
else
{
Operations[id].Result = 0;
}
}
public class Operation
{
public float Input { get; set; }
public float Result { get; set; }
}
}
I try to change the value of an input button after it was clicked. The button itself is an submit button, and the controller is getting back to the page by RedirectToAction. My problem is, that I can change the value of the button, but this new value is only shown for a millisecond before it is set back to its original value. Is the page reloaded after the script fired? Or why is the button value set back after the script fired?
Here is my code:
The button:
#using (Html.BeginForm("StartNewM2OLIEProcess", "Patient", new { label = Model.PatientID }, FormMethod.Post))
{
<input type="submit" id="btnStartProcess" value="M²OLIE Prozess starten" class="btn btn-primary" />
}
The Script
#section Scripts{
<script type="text/javascript">
$("#btnStartProcess").on('click', function () {
var self = $(this);
var errorMsg = '#errorMsg';
if (errorMsg == '') {
//self.attr('M2OLIE Prozess starten', 'Prozess gestartet');
self.val('Prozess läuft...');
}
else {
self.val("M²OLIE Prozess starten");
}
});
</script>
<script type="text/javascript">
var message = '#message';
if(message){
alert(message);
}
</script>
}
So the scripts are correctly fired, that I could test with the debugger. And I can also see the value of the button changing during debugging, but as soon as the script ends, the value changes back to the value that is defined in the Html form. What is happening here?
When the first click, the jQuery event is executed, then the page is sent to the action.
You either have to post the page or manage the click event.
test this code with your script
$("form").submit(function (e) {
e.preventDefault();
});
I will give you an example to see how the changes after the form post.
In Controller
[HttpGet]
public ActionResult StartNewM2OLIEProcess()
{
return View();
}
[HttpPost]
public ActionResult StartNewM2OLIEProcess(string myText)
{
ViewBag.ButtonText = myText;
return View();
}
In View
#{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("StartNewM2OLIEProcess", "Home", FormMethod.Post))
{
string buttonValue = "M²OLIE Prozess starten";
if (!string.IsNullOrEmpty(ViewBag.ButtonText))
{
buttonValue = ViewBag.ButtonText;
}
<input type="text" id="myText" name="myText" />
<input type="submit" id="btnStartProcess" value="#buttonValue" class="btn btn-primary" />
}
<div id="myDiv" style="width:300px;height:50px;background:#FF5511;color:white;text-align:center;font-weight:bold;"></div>
#section scripts{
<script>
var result = '#(ViewBag.ButtonText)';
if (result != null) {
document.getElementById("myDiv").innerText = result;
}
</script>
}
this is my first post on Stackoverflow so I apologize for any errors on this post (And sorry for my English too).
I'm having a problem using C# functions on Razor. I have a form with some textboxes to fill them with data from a SQL Server database. I also have some buttons to move across the elements on the DB table (like previous, next, first...).
I'll show you the code:
#{ var codcur = "";
var descripcion = "";
var horas = "";
var tutor = "";
int pos = 0;
if(IsPost) {
pos = Convert.ToInt32(Session["position"]);
}
else {
pos = 0;
}
using(PracticaRazor2.ModeloOcupacional Contexto = new PracticaRazor2.ModeloOcupacional()) {
var registro = (from cur in Contexto.CURSOS orderby cur.COD_CUR select cur).Skip(pos).First();
codcur = registro.COD_CUR;
descripcion = registro.DESCRIPCION;
horas = registro.HORAS.ToString();
tutor = registro.TUTOR;
}
<h1>Mantenimiento cursos</h1>
<form action="~/Cursos.cshtml" method="post">
<label>Código curso:</label>
<input type="text" name="cod_cur" id="cod_cur" value="#codcur" /><br />
<label>Descripción:</label>
<input type="text" name="descripcion" id="descripcion" value="#descripcion" /><br />
<label>Horas:</label>
<input type="text" name="horas" id="horas" value="#horas" /><br />
<label>Tutor:</label>
<input type="text" name="tutor" id="tutor" value="#tutor" /><br />
<br /><br />
<input type="submit" name="first" id="first" value="|<" onclick="#first(pos)"/>
<input type="submit" name="prev" id="prev" value="<<" onclick="#prev(pos)"/>
<input type="submit" name="next" id="next" value=">>" onclick="#next(pos)"/>
<input type="submit" name="last" id="last" value=">|" />
<input type="submit" name="borra" id="borra" value="Borrar" />
<input type="submit" name="Modifica" id="mod" value="Modifica" />
<input type="submit" name="Nuevo" id="new" value="Nuevo" />
</form>
#functions{
int next(int pos) {
if(IsPost) {
pos++;
Session["position"] = pos.ToString();
}
return pos;
}
int prev(int pos) {
if(IsPost) {
pos--;
Session["position"] = pos.ToString();
}
return pos;
}
int first(int pos) {
if(IsPost) {
pos = 0;
Session["position"] = pos.ToString();
}
return pos;
}
}
}
</body>
My problem is when I click on the buttons with the onclick events, all the methods declared in "#functions" are called in reverse order, even when the page is loaded for the first time. I tried to separate them on diferent #functions, use #helper on each method instead of #functions and nothing works.
Anyone have any idea of why is this happening or knows any way to do this propely?
Thanks in advance.
Best regards.
You need to create a postback method with your controller
so lets say this is your controller you would do something like this
public ActionResult YourPageName(string NextAction)
{
if(NextAction == "next")
{
Session["position"] = (int)Session["position"] + 1;
}
elseif(NextAction == "prev")
{
Session["position"] = (int)Session["position"] - 1;
}
else
{
Session["position"] = 0;
}
return View();
}
And change your View to send the right text with your button value when its clicked on
I am using the multiple file upload in Asp.net with c#
<asp:FileUpload ID="FileUpload2" multiple="multiple" class="form-control" runat="server" />
I want to validate client side on uploading that the selection of file must be 6.
function ValidateFile2(){
var fileCount = document.getElementById('FileUpload2').files.length;
if(fileCount > 10) // Selected images with in 10 count
{
alert("Please select only 10 images..!!!");
return false;
}
else if(fileCount <= 0) // Selected atleast 1 image check
{
alert("Please select atleat 1 image..!!!");
return false;
}
return true; // Good to go
}
Fiddle
<asp:FileUpload ID="FileUpload2" ClientIDMode="Static" multiple="multiple" runat="server"/>
JQuery solution:
$(document).ready(function () {
$('#FileUpload2').change(function () {
var files = $(this)[0].files;
if (files.length != 6) {
alert("Six files have to be selected at a time!");
}
else
{
submit();//your custom method to submit the form
}
});
});
Note: I could use the ID as selector as I have set the ClientIDMode property to static. This property was introduced from .NET 4.0 [Click here to know more]. Alternatively, you may also use the class name for the control as selector.
Try below
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<input type="file" ID="fuPhoto" multiple="multiple" />
<input type="button" ID="btnUpload" Text="Upload" Enabled="false" />
<label ID="myLabel" ForeColor="#CC0000" />
</div>
</form>
<script>
$(function () {
$('#fuPhoto').change(
function () {
var files = $('input[type="file"]')[0].files;
alert(files.length )
//var fileExtension = ['jpeg', 'jpg'];
if (files.length>6) {
$('#btnUpload').attr("disabled", true);
$('#myLabel').html("limit upto six");
}
else {
$('#btnUpload').attr("disabled", false);
$('#myLabel').html(" ");
}
})
})
</script>
updated Code below
$(function () {
var files = $('input[type="file"]')[0].files;
alert(files.length )
if (files.length>6) {
$('#btnUpload').attr("disabled", true);
alert("limit upto six");
}
else {
//nothing
}
})
you can use the code behind and do something like
if(FileUpload2.Count < 6)
{
//Error
}
else
{
//OK
}
you can also use a bit of JavaScript on the page to do the validation
`
function Validate() {
var f = document.getElementById("fu");
if(f.files.length < 6)
{
}
else
{
}
}
</script>`
and on the button click event set OnClientClick="Validate();"
Try Below in code behind,
if (FileUpload1.PostedFiles.Count > 2)
{
//error will show if file number more than 2
}
else
{
//will proceed with uploading if file count not more than 2
}