How to disable Submit behavior on readonly text box? - asp.net-mvc

Have the following READONLY textbox:
#Html.TextBoxFor(model => model.ClientNumber, new {#readonly = "readonly", #class ="message-label"})
and Save button:
<button type="submit" id="btnSave" name="Command" value="Save">Save</button>
When user clicks on Client Number text box and hits Enter, then submit behavior is invoked and next page is displayed after data is saved to the database.
How to change this, so that hitting Enter while in this field does nothing, similar to how page behaves for a usual label?

You can do this with a little bit of javascript, handling keydown event and checking whether Enter was hit:
$(document).ready(function() {
$('input[name=ClientNumber]').keydown(function(e) {
if (e.keyCode === 13) {
e.preventDefault();
return false;
}
});
});

Related

DirtyForms does not work properly with $.blockUI

I'm using DirtyForms and $.blockUI plugin, the latter to change pages when clicking on links (in my app, some pages take a couple of seconds more to load and a visual feedback is fine).
When I change field content and then click any link, DirtyForms is triggered: but when I cancel the process to stay on the page, $.blockUI starts its game, resulting in a stuck page
$('form[method="post"]').dirtyForms();
$('a').on('click', function(){
$.blockUI();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
Please, any solution?
EDIT: I also tried with stay.dirtyforms and afterstay.dirtyforms events, but they have no effect. defer.dirtyforms seems to work but the event is triggered twice (I put a console.log() to check) and I am not sure this is the way to go...
I've edit my answer: I've added some line of code to disable first the onbeforeunload dialog alert, taken from here. And at the end a link to an answer with another idea you can try.
My idea: you have to prevent the default link action and use the $.blockUI Modal Dialogs methods to open a custom dialog, then catch the link attribute href from the link put it inside a variable and use the variable value for the #yes button of the dialog.
See if this solution can meet your needs
/* beforeunload bind and unbind taken from https://gist.github.com/woss/3c2296d9e67e9b91292d */
// call this to restore 'onbeforeunload'
var windowReloadBind = function(message) {
window.onbeforeunload = function(event) {
if (message.length === 0) {
message = '';
};
if (typeof event == 'undefined') {
event = window.event;
};
if (event) {
event.returnValue = message;
};
return message;
}
};
// call this to prevent 'onbeforeunload' dialog
var windowReloadUnBind = function() {
window.onbeforeunload = function() {
return null;
};
};
var linkToFollow; // href to follow
$('form[method="post"]').dirtyForms();
$('a').on('click', function(e){
e.preventDefault();
windowReloadUnBind(); // prevent dialog
$.blockUI({ message: $('#question'), css: { width: '275px' } });
linkToFollow = $(this).attr('href');
});
$('#no').click(function() {
$.unblockUI();
return false;
});
$('#yes').click(function() {
$(window.location).attr('href', linkToFollow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
<div id="question" style="display:none; cursor: default">
<h6>Would you like to contine?.</h6>
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" />
</div>
Other idea taken from another answer: Other idea would be to make a simple jQuery.ajax({}) call before return value in beforeunload as seen in this answer

Making Kendo Datepicker readonly but also selectable

I´ve been struggling to make my Kendo Datepicker without user-text-input and the only solution I´ve come up with was making the tag "readonly". However I want to be able to select the date from the selector with the mouse without being able to input text directly to the picker, therefore making the datepicker readonly but selectable.
Any ideas how?
<div>
#(Html.Kendo().DatePicker()
.Start(CalendarView.Year)
.Name("DatePicker")
.Value(DateTime.Now.AddDays(-365))
.Max(DateTime.Now)
.HtmlAttributes(new { style = "width: 125px;" })
.Events(e => e.Change("onDateChange")))
</div>
After a while I found a very simple solution using javascript. I simply declared a script that prevents any user input without disabling or making the input readonly. Something like this:
$("#inputId").keypress(function (evt) {
var keycode = evt.charCode || evt.keyCode;
if (keycode == 9) { //allow Tab through
return true;
} else {
return false;
}
});
It was easier than I thought :)
########### EDITED ####################
As suggested in a comment, it is probably not good practice to suppress all the keystrokes so I will paste almost the same code but suggesting that I open the datePicker instead (but still kind of suppressing the user text input as well).
$("#inputId").keypress(function (evt) {
var keycode = evt.charCode || evt.keyCode;
if (keycode == 9) { //allow Tab through
return true;
} else {
// Allow the datepicker to open instead
var datePicker = $("#inputId").data("kendoDatePicker");
datePicker.open();
return false;
}
});
You can do something like this:
#(Html.Kendo().DatePicker().Name("FollowUpDate").HtmlAttributes(new{onkeydown="javascript:return false;" }))
when someone clicks the datepicker it returns false hence does not allow to type anything while it still remains selectable.
If you want to just select data from opening calendar which kendoDatePicker show you but user not allow to enter date
<link href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.default.min.css" rel="stylesheet" />
<input type="text" onkeydown="return false" placeholder="Enter Date" class="DatePicherKendo" />
<script src="~/bower_components/DataPicker-Kendo/JalaliDate.js"></script>
<script src="~/bower_components/DataPicker-Kendo/kendo.web.js"></script>
$(".DatePicherKendo").kendoDatePicker();
Add a maxlength attribute of 0 in HtmlAttributes.

Enabling disabled submit button doesn't work during filling the field which is required to enable the submit

sorry if the title isn't clear, i was trying to explain in the best possible way. The situation I have is the following: I have a newsletter with a submit button. I have used jquery to unlock the SUBMIT button after the correct email is typed in. It is working fine apart of one thing - I have to click anywhere outside the field (not on the submit button) to enable the submit, then on submit. There was something I have to add somewhere around this line i think, but I dont know what:
document.getElementById("submit").disabled = false;
the full code is here:
HTML:
<div class="element">
<input type="text" id="email" name="email" value="Enter your email" />
</div>
<div id="bsubmit">
<input name="submit" id="submit" src="_images/generic/send_button.png?submit+button=" type="image" disabled="disabled" />
</div>
and jq:
$.fn.swapText = function(){
return this.each(function(){
var tmpDefVal = $(this).val();
$(this).css('color', '#999');
$(this).focus(function(){
if($(this).val() == tmpDefVal){
$(this)
.css('color', '#000')
.val('');
}
});
$(this).blur(function(){
if($(this).val() == ''){
$(this)
.css('color', '#999')
.val(tmpDefVal);
}
});
});
}
$(document).ready(function(){
$('#email').swapText();
$('#email').change(function(){
var regexp = /^\w+[#]\w+\.\w{2}$/;
if(regexp.test($(this).val())){
$(this).removeClass('err');
$(this).addClass('ok');
document.getElementById("submit").disabled = false;
}else{
$(this).removeClass('ok');
$(this).addClass('err');
}
});
});
Thanks for any help.
One problem is that you have two elements with an id of submit.

Display cursor and text both in textbox when page load

I am working on Asp.net MVC.
i am using regular html
<label for="txtbox1" > User Name</label>
<input type="text" id="txtbox1" name="text" class="water"/>
I want to display Cursor before text and Text both when page load. When user start writting in text box at that time "User Name" removed.
You need to use javascript for this. If you are using jquery you could:
$(function() {
$('#txtbox1').focus();
});
And if you want to do this with plain javascript:
window.onload = function() {
var textbox = document.getElementById('txtbox1');
if (textbox != null) {
textbox.focus();
}
};
UPDATE:
If you want the text to disappear when the user starts typing you may try the following:
$('#txtbox1').keypress(function() {
if (!$(this).data('dirty')) {
$(this).val('').data('dirty', true);
}
});
Live demo.

ASP.NET MVC jquery.UI dialog - How to validate the dialog's input on server and return error?

I am using jQuery1.4.2, ASP.NET MVC 2 and jQuery.UI-1.8.
I am creating a data input dialog which works OK when all the data is valid, but I want to validate the input data on the server and return an error to the dialog describing the error and I am not quite sure how to do that and keep the dialog open. The dialog is opened when a link is clicked. The solution may be to try to bypass more of the MVC framework's default binding that handles the submit button clicks and creates the expected ProfilePermission object and calls the Controller's AddPermission POST Action method, but I was hoping there may be an easier way without having to write more jquery/javascript code to handle the button clicks and pass the data to/from the server.
My script code looks like
$("#dialog").dialog({ modal: true,
position: ['center', 180],
width: 500,
height: 130,
autoOpen: false
});
$(".addPermissionDialog").click(function (event) {
event.preventDefault();
$("#dialog").dialog('open');
return false;
});
My View
<div id="dialog" title="Add Permission">
<%: Html.ValidationSummary("") %>
<% using (Html.BeginForm("AddPermission", "Profile"))
{ %>
<%: Html.Hidden("PersonId") %>
<%: Html.Hidden("ProfileId") %>
<div class="editor-label">
<label for="PersonName">User Name:</label>
<%: Html.TextBox("PersonName")%>
<label for="PermissionType">Permission:</label>
<select name="PermissionTypeId" id="PermissionTypeId" >
<option value="2">Edit</option>
<option value="3">View</option>
</select>
</div>
<br />
<p>
<input type="submit" name="saveButton" value="Add Permission" />
<input type="submit" id="cancelButton" name="cancelButton" value="Cancel" />
<script type="text/javascript">
document.getElementById("cancelButton").disableValidation = true;
</script>
</p>
<% } %>
</div>
<br />
<p>
<%: Html.ActionLink("Add Permission", "AddPermission", new { profileId = Model.First().ProfileId }, new { #class = "addPermissionDialog" })%>
</p>
My Controller action
[AcceptVerbs("Post")]
[HandleError]
public ActionResult AddPermission(string cancelButton, ProfilePermission profilePermission)
{
ViewData["Controller"] = controllerName;
ViewData["CurrentCategory"] = "AddPermission";
ViewData["ProfileId"] = profilePermission.ProfileId;
PermissionTypes permission = repository.GetAccessRights(profilePermission.ProfileId);
if (permission == PermissionTypes.View || permission == PermissionTypes.None)
{
ViewData["Message"] = "You do not have access rights (Edit or Owner permissions) to this profile";
return View("Error");
}
// If cancel return to previous page
if (cancelButton != null)
{
return RedirectToAction("ManagePermissions", new { profileId = profilePermission.ProfileId });
}
if (ModelState.IsValid)
{
repository.SavePermission(profilePermission);
return RedirectToAction("ManagePermissions", new { profileId = profilePermission.ProfileId });
}
// IF YOU GET HERE THERE WAS AN ERROR
return PartialView(profilePermission); // The desire is to redisplay the dialog with error message
}
LATER EDIT
I was hoping for a mechanism to return an error to the dialog using MVC's plumbing, I eventually broke down and added a save button via the jquery.ui.dialog API and handled the issue that way. I removed the buttons from the .aspx page. I returned return new EmptyResult(); from the controller's actions if everything worked OK and if there was an error
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Content(errorMessage, MediaTypeNames.Text.Plain);
// To add a button and bypass more of MVC plumbing
buttons: {
"Save": function () {
var dlg = $(this);
$.ajax({
url: "/Profile/AddPermission",
type: 'POST',
data: {
PersonId: $("#PersonId").val(),
ProfileId: $("#ProfileId").val(),
PermissionTypeId: $("#PermissionTypeId").val(),
PersonName: $("#PersonName").val()
},
success: function (data) {
dlg.dialog('close');
},
error: function (data) {
alert(data.responseText);
}
});
}
}
I was doing this kind of stuff using jquery.form and jquery dialog;
in the post action if everything is good you return Content("OK") if not you return the PartialView() (that contains the modelstate errors) after in the function that handles the successful post response you check if it is "OK" close the dialog if not you set the $("#yourDialogDiv").html(responseHtmlThatYouGotFromTheServer)
I would suggest changing the input type submit to a normal button and making an Ajax call on click of the button, to ensure that the dialog is not closed. Send data to the server using JsonValueProviderFactory from the MVC2 futures library based on Phils post. If the validation fails trap the error in the ajax error: option. If data is valid close the dialog from the Ajax complete: option. Hope this helps.

Resources