I am currently doing a project in .net MVC4 and I have requirement to populate a Display field with current date, when a checkbox is ticked in the Edit form.
Since it's an edit form Checkbox, might be ticked already and I need to check if it's selected the first time then I need to populate the current date.
Update:
Matt Thanks..I got this around by using Hidden field.
Steps involved:
1. store the model field in Hidden field in your Edit Screen.
#Html.Hidden("hiddenDateField", Model.DateField)
#Html.Hidden("hiddenCheckBox", Model.CheckBoxField)
Then using JQuery I added following logic..
$('#chkBox').on('click', function () {
var myDate = new Date();
var displayDate = (myDate.getUTCDate()) + '/' +(myDate.getUTCMonth() + 1) + '/' + myDate.getUTCFullYear() + " " + myDate.getUTCHours() +":" + myDate.getUTCMinutes() +":"+myDate.getUTCSeconds();
if ($('#chkBox').is(":checked")) {
if ($('#hiddenCheckBox').val() == "False") { // This condition is to check if the user is selecting checkbox for 1st time by comparing with received model data value.
$('#lblDate').text(displayDate);
} else {
$('#lblDate').text($('#hiddenDateField').val()); // This condition is to restore the Date if user unticks and Select Checkbox again.
}
}
if (!$('#chkBox').is(":checked")) { // This when user unticks the checkbox and I replaced the date to empty char.
$('#lblDate').text("");
}
});
no need to use ajax, just use jquery. without your code it is hard to give an example so you will need to change this to match your code
$(document).ready(function(){
//this will check if checked on load and set the text box to now
if($('.chkClass').is(":checked")){
$('.txtClass').val($.now());
}
$('.chkClass').on('click', function(){
//check again so it only sets the date if they check and not uncheck
if($('.chkClass').is(":checked")){
$('.txtClass').val($.now());
}
});
});
Related
I have cloned row form existing row in a table,i have gave validations for first row using jquery.validate.unobtrusive but it is not working properly for cloned row
You can use jQuery in your view and validate for client site.
For example if you have table you can use scripts some like:
Before form submit you can use:
var filterTable = $('#tableID').find('tr').length;
if (filterTable != 1) {
CheckFilterNameField(); // Use function
}
This function
function CheckFilterNameField() {
var $namefield = $('.filterPanel tr .namefield');
$namefield.each(function () {
if ("your conditions")
$(this).addClass('error');
else
$(this).removeClass('error');
});
}
If you will be have class error on the element in your table page can't load and in the specific item for example will be red or you can show alert about error in your form.
I am trying to use Remote Validation with an additional bool checkbox field
[Remote("IsStorageConnectionValid", "TenantManagement", AdditionalFields = "CreateStorage")]
public String StorageConnectionString { get; set; }
Validation code
public JsonResult IsStorageConnectionValid(string storageConnectionString, bool createStorage){
It works perfectly in terms of it hitting the validator. However createStorage is always true irrespective of the value of the checkbox. If I use additional fields that aren't check boxes they are supplied perfectly.
Checkbox created as standard:
#Html.CheckBoxFor(m => m.CreateStorage)
Is this a bug? Or am I doing it wrong?
Fiddle Is here (Is MVC4 I think but does the same thing)
It does appear that this is a bug when used with #Html.CheckBoxFor. The problem is that CheckBoxFor renders 2 elements, a checkbox with value="true" and a hidden input with value="false" (Unchecked checkboxes do not post back so the second hidden input ensures a value is posted back for use by the DefaultModelBinder)
Looking at the relevant section of the jquery.validate.unobtrusive.js file
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
return $(options.form).find(":input[name='" + escapeAttributeValue(paramName) + "']").val();
};
});
setValidationValues(options, "remote", value);
});
the return statement returns (in your case) .find(':input[name="CreateStorage"]').val(); which returns the value of the first input with the name="CreateStorage" which will always be true (the value of the checkbox)
As a test, if you render the value using HiddenFor rather that CheckBoxFor you will receive the correct value in your IsStorageConnectionValid method (but of course this does help since you cant change the value)
Not sure of the best solution, but the unobtrusive script should be first checking if .find(..) returns more than one element, then if the first is a checkbox which is unchecked, returning the value of the second element.
Edit
I have reported this as an issue at Codeplex
Edit 2
I have been advised the the issue has now been fixed here
How I can strip out the variables listed below from within a textbox (input) that if a user tries to type a URL i.e these variables:
"http://"
"www."
".com"
".co.uk"
If any of the variables above exist in the textbox on keyup the submit button gets disabled or/and it removes/strips out the variables above.
Is this possible? I've tried doing it using Charcodes, but I face the problem that I would like the user to still use '.; (full-stops) etc
Can somebody help?
Thanks,
Here you go!
Demo
$("#myinput").keyup(function()
{
var a = ["http://", "www.", ".com", ".co.uk"]; //Add the substrings
a.forEach(function(k)
{
if($("#myinput").attr("value").indexOf(k) > -1)
{
alert('Found!'); //Do something
return true;
}
else
{
return false;
}
});
});
Every time the user types a char, it checks for the string in array a. If the substring is found, it popups an alert message.
Using blur it will check for the string only when the user go outs of the input box (its more efficient using blur, but you can use this way if you want to check few strings and the input value is not too long).
Try this,
$("#textboxId").blur(function (event) {
var text = event.target.val();
if(text.contains("www")) {
$("submitBtnId").prop('disabled', true);
}
});
I have a grid (list generated using scaffolding option) with search criteria. And I created paging concept. I entered search criteria data and search, after post back, I retained the form data using TempData. But, if I click page numbers in grid, the form data not retained and also the grid also getting refreshed.
Is there any way to retain data on pagination?
Thanks!
I added a hidden field dynamically within the form using JavaScript. The page number stored in hidden field, when the user click page number, then submit the form. It is working well without any issue.
Paging:
<button onclick="navigateTo(this, '#Url.RouteUrl("Defined_Route", new { currentPage = j })');">#j</button>
Javascript:
$(function () { //Page Load - Create hidden field, if search button found
if ($("#search")) // Button id
{
var element = document.createElement("input");
element.type = "hidden";
element.id = "currentPage";
element.name = "currentPage";
element.value = '#TempData["Page"]';
if (isNaN(element.value)) element.value = "1";
$(to).parent().append(element);
}
});
function navigateTo(field, url)
{
$("#currentPage").val(field.innerText);
if (isNaN($("#currentPage").val()))
{
location.href = url;//This is for direct url, ie. no search form
}
else
{
$("form").action = url;
$("form").submit();
}
}
I am using the custom binding provided in How to create an auto-complete combobox?
I want to allow the user to either select a value from the list of suggestions or enter a value that is not in the list of suggestions. How can I get the value of the input into my observable field?
For example, if the user types 'smi' the autocomplete list will show Smith and other surnames beginning with 'smi', however, if they do not select an option from the list, I just want to set the value of my observable field to be 'smi'. At present, the only way the observable propety is set is when the user selects an item from the list of suggestions.
I have the following code (HTML):
<input type="text" data-bind="
value: surname,
jqAuto: { autoFocus: true },
jqAutoSource: surnames,
jqAutoQuery: surnameAutocomplete,
jqAutoValue: surname"
/>
JavaScript view model (simplified):
var vm = {
surnames: ko.observableArray(),
surname: ko.observable(),
surnameAutocomplete: function (searchTerm, result) {
repository.surnameAutocomplete(searchTerm, result);
};
Solution:
I amended the custom binding handler in two places:
init: function - added the following
// New setting to allow / disallow a user to enter values that are in the autocomplete list.
forceSelection = allBindings.jqAutoForceSelection;
options change function - amended to the following
//on a change, make sure that it is a valid value or clear out the model value
options.change = function (event, ui) {
var currentValue = $(element).val();
// Start: new code, check new setting on whether to force user to make a selection
if (!forceSelection) {
writeValueToModel(currentValue);
return;
}
// End: new code
var matchingItem = ko.utils.arrayFirst(unwrap(source), function (item) {
return unwrap(inputValueProp ? item[inputValueProp] : item) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
}
I also found that the first item in the autocomplete list was being automatically selected, but then noticed by setting autofocus: false solved my issue, e.g.,
<input type="text" data-bind="
jqAuto: { autoFocus: false }, /* This fixes the auto select issue */
jqAutoSource: surnames,
jqAutoQuery: surnameAutocomplete,
jqAutoValue: surname,
jqAutoForceSelection: false"
/>
If you look closely at the binding handler you're using, you will notice this section:
//on a change, make sure that it is a valid value or clear out the model value
options.change = function(event, ui) {
var currentValue = $(element).val();
var matchingItem = ko.utils.arrayFirst(unwrap(source), function(item) {
return unwrap(item[inputValueProp]) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
What this section of the binding handler essentially does is check if the text the user entered into the text field matches something in the autocomplete dropdown, and if it doesn't, it clears the model value (which it sounds like what you want to change).
You can either try deleting this section or extend it to suit your purposes.