How to validate a column in an editable datatable? - c#

Am using an editable HTML datatable on my asp.net web page .Which look like this,
How to add validation on column Target, to receive only float values.?
Function (For enable edit):
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
jqTds[0].innerHTML = aData[0];
jqTds[1].innerHTML = aData[1];
jqTds[2].innerHTML = '<input type="text" id="Float" class="form-control" value="' + aData[2] + '">';
jqTds[3].innerHTML = '<a class="save-row" href="">Save</a>';
jqTds[4].innerHTML = '<a class="cancel-row" href="">Cancel</a>';
}
I tried to add keypress event on the textbox , but its not working.!
$('#Float').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && (event.which != 8)) {
event.preventDefault();
}
});
Am new to jquery so please help me solve this ?

Try:
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
Note: Above code doesn't work for -ve values.

Related

Devextreme datagrid column filter value validation

I have a datagrid with date range filter (FilterOperations.Between) for date column
x.AddFor(m => m.RequestDate)
.Caption("Дата запроса")
.Width(150)
.Alignment(HorizontalAlignment.Center)
.DataType(GridColumnDataType.Date)
.Format("dd.MM.yyyy")
.FilterOperations(new[] {FilterOperations.Between})
.SelectedFilterOperation(FilterOperations.Between)
.AllowHeaderFiltering(false)
.FilterValue(new object[] {
DateTime.Now.AddMonths(-3),
DateTime.Now
});
How to make custom validation for filter values?
I want user to fill two fields in range filter or neither.
For example: If user fill only one field in range filter - show error message, If user fill two or neither fields in range filter - it's Ok.
Any ideas?
Finally I find out how to make custom validation
I made it with OnEditorPreparing event handler
cshtml:
.OnEditorPreparing("onEditorPreparing")
js:
function onEditorPreparing(e) {
if (e.editorName === "dxDateBox") {
prepareDateFilterCustomValidation(e);
}
}
function prepareDateFilterCustomValidation(e) {
e.editorOptions.onValueChanged = $.proxy(function () {
// Get Date inputs
var firstInput = $("div.dx-editor-container.dx-datagrid-filter-range-start > div > div .dx-texteditor-input").last()[0];
var secondInput = $("div.dx-editor-container.dx-datagrid-filter-range-end > div > div .dx-texteditor-input").last()[0];
validateDateInputs(firstInput, secondInput);
applyInputFilter(firstInput, secondInput, arguments[0]);
}, null, e.dataField);
}
function validateDateInputs(firstInput, secondInput) {
// If two inputs are filled - date range is valid
if (firstInput.value !== "" && secondInput.value !== "" || firstInput.value === "" && secondInput.value === "") {
$("div.dx-editor-container.dx-datagrid-filter-range-start > div").last().removeClass("dx-invalid");
$("div.dx-editor-container.dx-datagrid-filter-range-end > div").last().removeClass("dx-invalid");
return;
}
// If filled only first - date range is invalid
if (firstInput.value !== "" && secondInput.value === "") {
$("div.dx-editor-container.dx-datagrid-filter-range-start > div").last().removeClass("dx-invalid");
$("div.dx-editor-container.dx-datagrid-filter-range-end > div").last().addClass("dx-invalid");
return;
}
// If filled only second - date range is invalid
if (firstInput.value === "" && secondInput.value !== "") {
$("div.dx-editor-container.dx-datagrid-filter-range-start > div").last().addClass("dx-invalid");
$("div.dx-editor-container.dx-datagrid-filter-range-end > div").last().removeClass("dx-invalid");
return;
}
}
function applyInputFilter(firstInput, secondInput, filtrationFieldName) {
// If two inputs filled
if (firstInput.value !== "" && secondInput.value !== "") {
// change date format dd.mm.yyyy -> mm-dd-yyyy
var firstDate = new Date(
firstInput.value.substr(3, 2) + "-" + // Месяц
firstInput.value.substr(0, 2) + "-" + // День
firstInput.value.substr(6, 4)); // Год
// change date format dd.mm.yyyy -> mm-dd-yyyy
var secondDate = new Date(
secondInput.value.substr(3, 2) + "-" + // Месяц
secondInput.value.substr(0, 2) + "-" + // День
secondInput.value.substr(6, 4)); // Год
// apply datagrid filter
setColumnFilterValue(filtrationFieldName, [firstDate, secondDate]);
}
}

JsTree Checkbox checked unchecked with based on condition jquery

I am trying to JsTree Checkbox checked unchecked based on condition.
i have to checked and unchecked based dropdown change event.
string has value 0 and 1.
0 means unchecked and 1 means checked.
This is my menu design
Here is my controller code.
[HttpPost]
public ActionResult GetSingleUser(int id)
{
MachineShopDBEntities DB = new MachineShopDBEntities();
var SPresult = DB.GetSingleUser(id).FirstOrDefault();
return Json(SPresult);
}
Here is my Script.
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
var count = $('.menux ul li').length;
for (i = 0; i < count; i++) {
if (databaseString[i] == '0') {
$('.menux .jstree-anchor').removeClass('jstree-clicked');
}
else {
$('.menux .jstree-anchor').addClass('jstree-clicked');
}
}
});
});
Use the eq function to select the element based on index i
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
var count = $('.menux ul li').length;
for (i = 0; i < count; i++) {
if (databaseString[i] == '0') {
$('.menux .jstree-anchor').eq(i).removeClass('jstree-clicked');
}
else {
$('.menux .jstree-anchor').eq(i).addClass('jstree-clicked');
}
}
});
});

Table column values calculation using jQuery

I have some table & i need to calculate Column values.In my scenario i need to calculate Total Item Price 99 + 55 = 154 to Sub Total Row.In here my SubTotal Calculation not working.
My Code(part of my Table Creation)
$option.each(function () {
if ($(this).prop('selected')) {
var txtId = 'txtQty' + i;
var lblId = 'lblQty' + i;
var row = $('<tr><td>' + $(this).text() + '</td><td>' + $(this).attr('RetailPrice') + '</td><td>' + $(this).attr('WholesalePrice') + '</td><td>' + '<input type="text" id="' + txtId + '">' + '</td><td> <button type="button" class="btn btn-warning btn-xs btncalc">Calculate</button></td><td class="tot"><label for="tempprice" id="' + lblId + '"></label></td><td><img id="imgdel" src="../../Images/delete.png" alt="" onclick="deleteclick(this)" title="Delete" /></td></tr>');
table.append(row);
i++;
}
});
var row2 = $('<tr><td>' + "SubTotal" + '</td><td></td><td></td><td></td><td></td></tr>');
table.append(row2);
$('#product-load-tbl').append(table);
});
Calculation Part
$('.btncalc').live('click', function () {
debugger;
var row = $(this).parents("tr:first");
var rowval = $(row).find("td:eq(1)").html();
var inpval = $(row).find("td:eq(3) input").val();
if (inpval != null || inpval != 0) {
var result = (rowval * inpval);
}
else {
var result = 0;
}
$(row).find("td:eq(5)").html(result);
var lstrow = $(this).parents("tr:last"); // this sub total calculation not working
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
})
You can change this:
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
to this:
var total = 0; // intialise a var with value 0
$('.tot').each(function (i, element) { // loop the selected item in each row
total += +$(this).text(); // cast the string to integer and add it to total
});
$(lastrow).find("td:eq(5)").text(total); // then at last place the total
Short demo
And for a short note:
.live() is now removed from the latest jQuery versions, so if you are using version 1.7+ then you can move your code to .on() method to delegate the event. Syntax is something like this for event delegation:
$(static_parent).on(event, selector, callback);
$(static_parent) is the element which was available when the relative dom is ready and it was available at that time before appending any dynamic dom element in the page.
so in your case:
$('table_ID/Class').on('click', '.btncalc', function(){
//...all the stuff with .live goes here
});

Limit Character in FreeTextBox line

I've known many ways to limit the characters inputed inside the Textbox control or Freetextbox control.
How can I limit the character in each line (row) of FreeTextBox control???
For example, if the character in a line is 200, then it auto go to the next line
Best regard!
Hello this tricky way to handle by Javascript or JQuery..
Please follow below code for same with Jquery
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<asp:TextBox ID="txtData" CssClass="text-limit" runat="server" TextMode="MultiLine" style="width:500px; height:150px;"></asp:TextBox>
<script type="text/javascript">
var charactorPerLine = 20;
$(function () {
$(".text-limit").keydown(function (event) {
// Allow: backspace(8), delete(46), tab(9), escape(27) and enter(13)
if ($.inArray(event.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
if ($(this).val().lastIndexOf("\n") == -1) {
if ($(this).val().length >= charactorPerLine) {
$(this).val($(this).val() + "\n");
}
}
else {
if (($(this).val().length - $(this).val().lastIndexOf("\n")) >= charactorPerLine {
$(this).val($(this).val() + "\n");
}
}
}
});
});
</script>

textbox accepts the following values in Javascript?

I have a textbox and i need to validate that it accepts only 1,1.5,2,2.5,3,3.5,...11.5
How to validate it.. pls tell the answer please.
$(document).on('keyup', '#Dia_Inch', function (e) {
Dia_Inch = $(this).val();
if (Dia_Inch.charAt(1) == ".") {
if (Dia_Inch.charAt(2) != "5") {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
}
var val = isNumberInch(e);
if (val == false || Dia_Inch > 11.5) {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
});
this my sample code.. but it wont be worked.
You can do this using jquery:
function validate(value){
var arr = [1,1.5,2,2.5,3,3.5,...11.5];
if($.inArray(value, arr) >= 0){
return true;
}
return false;
}
You'll have to modify this according to your needs.
Here is a fiddle: http://jsfiddle.net/5Cm2w/
Do not forget to update the array with your actual values.
This may solve your purpose.
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^\d+(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo
But if u want to allow up to 11.5 then
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^[1-9]{1}[1]{0,1}(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo

Categories

Resources