Kendo comboBox validation - javascript

My issue is whenever I type a text item that's already in the combobox and I tab away, the combobox does not save my entry. It just leaves it at selectedIndex = 0. So my list is { hi, hello, hey } and I type hi in the combobox it should save my text hi even though i did not select it from the dropdown.
Id: {
type: "number",
validation: {
idvalidation: function (input) {
if (input.is("[name='Id']") && input.val() !== "") {
input.attr("data-idvalidation-msg", "Please select a Code");
return input.val() >= 0 && $("#Id").data("kendoComboBox").selectedIndex >= 0;
}
return true;
}
}
},
Code: { type: "string" },

That is the default behavior of Kendo Combobox. If you want to select the filtered item once you select tab (without clicking the selected item in the list), you'll have to add some JavaScript to capture keypress (ASCII code 9), something like:
combobox.input.on("keydown", function(e) {
var filter = combobox.dataSource.filter() || { filters: [] };
if (e.keyCode === 9 && filter.filters[0]) { //TAB
combobox.select(combobox.current().index());
}
});
Here is a link to Kendo's example for above code.

Related

Shift tab not retaining the element focus

Javascript version code -- Link
if (el.value.length > 1) {
el.value = el.value[el.value.length - 1];
}
try {
if (el.value == null || el.value == "") {
this.foucusOnInput(el.previousElementSibling);
} else {
this.foucusOnInput(el.nextElementSibling);
}
} catch (e) {
console.log(e);
}
AngularJS version code - Link
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "") {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
Not able to implement the javascript version of
Tab & Shift+Tab
functionality in AngularJS. Let me know what am missing here!
Requirement - Once you enter the value to the input text the next input text element should be focused; On Shift-Tab previous input text element should be focused.
The keyup event gets triggered for every key up including tab and shift. This is the difference between your javascript solution angularjs solution.
I'm not sure if there is an equivalent to oninput in angularjs. 'keyup', 'keydown', 'input' all work differently. There is ng-change in angularjs but it requires ng-model on the input element and I don't think $event works with ng-change.
Anyway, there is a working solution. Try this:
$scope.readKey = function(ele) {
console.log(ele);
if(ele.shiftKey) return;
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "" ) {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
};
This code, as listened on keyup instead of input, will not allow to go to next input field if current input field is empty. In your javascript example, the code in input handler never gets executed and so you can move to next input field if current one is empty.
If you want to achieve the same thing in angularjs solution as well, then try changing the condition to this:
if(ele.shiftKey || ele.keyCode === 9) return;
This prevents the code from getting executed if its shift key or tab key. 9 is the keycode for TAB.
Working solution -- Link
if(ele.key != "Tab" && ele.key != "Shift" ){
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "") {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
}

How to highlight a checked radio button using jquery validate highlight property

I am trying to add some new functionality to something that was previously written by some other guy, I need to highlight a radio button after a validation on one of grid element which is in the same row as the radio butotn.
$.validator.addMethod(
"CountyCheck",
function (value, element) {
if ($("input[type='radio']:checked").closest('tr').find('select') && $("input[type='radio']:checked").closest('tr').find('select').length > 0) {
if ($("input[type='radio']:checked").closest('tr').find('select').val() != '')
return ($.trim($('#tobevalidated').val()).toLowerCase() === $.trim($("input[type='radio']:checked").closest('tr').find('select').val()).toLowerCase());
else
return true;
}
else {
return ($.trim($('#tobevalidated').val()).toLowerCase() === $.trim($("input[type='radio']:checked").closest('tr').find('.labelclass').html()).toLowerCase());
}
}, "");
the above validation method checks for the radio buttons in a grid and searches for the drop down list(if one exists) or a label and checks if the selected option/label value is equal to a certain value to be validated.(#tobevalidated). The cshtml for the grid looks some thing like this:
var grid = addresses != null ? new WebGrid(addresses, canSort: false, canPage: false) : new WebGrid(new List<Address>(), canSort: false, canPage: false);
var gridColumns = new List<WebGridColumn>();
gridColumns.Add(grid.Column("", format: item => Html.RadioButton("IsStandardized", true, ((bool?)item.IsStandardized).GetValueOrDefault(), new { data_SerializedAddressData = (string)item.JSonSerializedAddressData }), style: "webgridcol1Width"));
gridColumns.Add(grid.Column("Address1", "Address1", style: "addrLine"));
gridColumns.Add(grid.Column("Address2", "Address2", style: "addrLine"));
gridColumns.Add(grid.Column("City", "City", style: "webgridcol2Width"));
gridColumns.Add(grid.Column("State", "State", style: "webgridcol2Width"));
gridColumns.Add(grid.Column(header: "Postal Code", style: "webgridcol2Width", format: item => CommonUtility.GetZipCode((Address)item.Value, true)));
gridColumns.Add(grid.Column("Country", "Country", style: "webgridcol2Width"));
//TODO: Need to see how to add AddressType to Standardized Addresses or just check with updated Address' AddressType
if (updatedAddresses.Any(addr => !(addr.AddressType == AddressCodeEnum.BillingAddress || addr.AddressType == AddressCodeEnum.MailingAddress)))
{
gridColumns.Add(grid.Column(columnName: "County", header: "County", style: "countyname", format: addr =>
{
if (addr.StandardizedCounties != null && addr.StandardizedCounties.Count > 1)
{
bool isRadioSelected = ((bool?)addr.IsStandardized).GetValueOrDefault();
List<SelectListItem> countiesList = Html.ConvertToSelectList<string>((List<string>)addr.StandardizedCounties, (a) => a, (a) => a, true, isRadioSelected ? Model.StandardizedAddress.County : "");
MvcHtmlString returnValue = Html.DropDownList((string)string.Format("CountyDDL[{0}]", addr.WebGrid.Rows.IndexOf(addr)), countiesList);
return returnValue;
}
else
{
String county = (addr.StandardizedCounties != null && addr.StandardizedCounties.Count == 1) ? Model.County : addr.County;
return county;
}
}));
}
I want to highlight the checked radio button when the validation fails, but the problem is jquery-validate.js
highlight: function(element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).addClass(errorClass).removeClass(validClass);
}
}
uses something like this to add a css class, since the element.name in this is same for all the radio buttons, but I want to just highlight the button which is checked.
I used something like this in the highlight method of the validate.js
highlight: function(element, errorClass, validClass) {
if (element.type === 'radio') {
$(element).is(":checked").addClass(errorClass).removeClass(validClass);
} else {
$(element).addClass(errorClass).removeClass(validClass);
}
},
but this does not seem to work and more over it reloads the page whenever the validation is fired.
I am really nub at this and if any one could point me in the right direction, that would be of great help.
Thanks!

change focus after selecting an item in a jquery UI autocomplete field

I have two fields. An autocomplete field and a simple textbox. When user selects an item from autocomplete field I want to set focus on the next field and call a function when enter key is pressed on it. Here is the code:
this.initPiecesAutocomplete = function (){
$('#product_autocomplete_input1')
.autocomplete('ajax_products_list.php', {
minChars: 1,
autoFill: true,
max:20,
matchContains: true,
mustMatch:true,
scroll:false,
cacheLength:0,
formatItem: function(item) {
return item[1]+' - '+item[0];
}
}).result(self.getCount);
this.getCount = function(event, data, formatted) {
if (data == null)
return false;
$('#pieceCount').focus();
$('#pieceCount').on('keypress', function(e) {
if (e.which == 13) {
self.addPiece(event, data, formatted)
}
});
}
After selecting an item from the autocomplete field (by pressing the enter key), instead of setting focus on the #pieceCountfield, self.addPiece() is called. What's wrong?

Javascript on input text change, change div text

I am trying to change text of one div, when I enter different values into my text input:
EXAMPLE:
Input = 1,
DIV TEXT: "rok" //in eng. "year"
Input = 2,
DIV TEXT: "roky"
Input = 3,
DIV TEXT: "roky"
Input = 4,
DIV TEXT: "roky"
Input = 5,
DIV TEXT: "rokov"
Default value of my input is 3.
html
<input type="text" id="pocetrokov" value="3"><span id="year">roky</span>
Js:
function rok() {
if(roky==2 || roky==3 || roky==4){
$('#year').html('roky');
} else if( roky>4 || roky == 0){
$('#year').html('rokov');
} else if (roky==1){
$('#year').html('rok');
}
}
$(function () {
$('select, input').on('keydown blur change', rok);
});
I get this when I change the defalut value:
Input = 1,
DIV TEXT ="rokov" instead of "rok"
Input = 2,
DIV TEXT ="rokov" instead of "rok"
... etc.
I get the correct value only when I click somehere outside the input
What is wrong?
Thank you.
Try this:
function rok(roky) {
if(roky==2 || roky==3 || roky==4){
$('#year').html('roky');
} else if( roky>4 || roky == 0){
$('#year').html('rokov');
} else if (roky==1){
$('#year').html('rok');
}
}
$(function () {
$('input').on('keyup blur change', function(){
rok( $(this).val() );
});
});
Use Keyup Event instead of other,because value of text field is fetched when you keydown and when key down your actual value thats on variable is the previous value,Not the one that is currently in input field So, the function Works correctly :
$(function () {
$('input').on('keyup', rok);
});
Here is DEMO
Guys why are you complicating it so much with 2 functions?
$("html").on("keyup","#pocetrokov",function(){
var roky=parseInt($(this).val());
if(roky==2 || roky==3 || roky==4){ $('#year').html('roky');}
else if(roky>4 || roky === 0) { $('#year').html('rokov');}
else if (roky==1){ $('#year').html('rok'); }
});

SlickGrid not shifting focus away from grid when tabbing out of last cell that is editable

When a SlickGrid is set up with:
enableAddRow: false,
enableCellNavigation: true,
autoEdit: true
and the last column in that SlickGrid is configured with:
editor: null,
focusable: false,
selectable: false
When attempting to tab out of the SlickGrid by tabbing out of the second to last column in the last row, I would expect the focus to be moved to the next focusable element outside of the grid, but it does not.
See this example, and try to tab out of the grid from the last row. I would expect the focus to shift to the textboxes below the grid, but it does not and instead focus is lost while the active cell in the grid is not reset.
Is there a way to fix this? To ensure, when tabbing out of an editable cell that is followed by an uneditable unfocusable cell, that focus is moved out of the grid?
A workaround would be to make the last column focusable: true, but that is not an option since it breaks the user experience forcing the user to tab through an uneditable cell before reaching an editable cell.
Can you try below if it works for you.
yourGrid.onKeyDown.subscribe(function(event) {
if (event.keyCode === 9 && event.shiftKey === false) { // check its only tab not shift tab
if (yourGrid.getActiveCell().cell === lastCol) { // check if the current cell is the last editable column
$("#b").trigger('focus'); // this or below line should work for focus, "b" is your text input
document.getElementById("b").focus(); // either this or above line
event.stopImmediatePropagation();
}
}
});
UPDATE
Fixed it by changing the code in the plugin. The issue were coming and I think its a bug in the Slickgrid. After the change in below function your example is working in my local. Please replace the below function code and let me know if this is working for you.
function setActiveCellInternal(newCell, opt_editMode) {
var lastActiveCell = null;
var lastActiveRow = null;
if (activeCellNode !== null) {
makeActiveCellNormal();
$(activeCellNode).removeClass("active");
if (rowsCache[activeRow]) {
$(rowsCache[activeRow].rowNode).removeClass("active");
}
var lastActiveCell = getCellFromNode(activeCellNode); // my added
lastActiveRow = activeRow;
}
var activeCellChanged = (activeCellNode !== newCell);
activeCellNode = newCell;
if (activeCellNode != null) {
//alert('1-3')
activeRow = getRowFromNode(activeCellNode.parentNode);
activeCell = activePosX = getCellFromNode(activeCellNode);
if (opt_editMode == null) {
opt_editMode = (activeRow == getDataLength()) || options.autoEdit;
}
$(activeCellNode).addClass("active");
$(rowsCache[activeRow].rowNode).addClass("active");
//alert(options.editable +' - '+ opt_editMode);
if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell) && ((lastActiveCell !== activeCell || lastActiveRow !== activeRow) ) ) { // not sure if need acheck on row also
clearTimeout(h_editorLoader);
if (options.asyncEditorLoading) {
h_editorLoader = setTimeout(function () {
makeActiveCellEditable();
}, options.asyncEditorLoadDelay);
} else {
makeActiveCellEditable();
}
//alert('1-4')
}
} else {
activeRow = activeCell = null;
//alert('1-5')
}
if (activeCellChanged) {
//alert('1-6')
trigger(self.onActiveCellChanged, getActiveCell());
}
}
See the link below.
https://github.com/mleibman/SlickGrid/issues/104
Since you cannot tab out of the last cell, you can try committing the change when you click on save changes
if (Slick.GlobalEditorLock.isActive() &&
!Slick.GlobalEditorLock.commitCurrentEdit()) return;
Will that work?
Can you try to replace the gotoRight function with below code in slick.grid.js file and try.
function gotoRight(row, cell, posX) {
if (cell >= columns.length) {
return null;
}
do {
cell += getColspan(row, cell);
}
while (cell < columns.length && !canCellBeActive(row, cell));
if(cell == columns.length && !canCellBeActive(row, cell)) {
setActiveCell(row,cell-1)
}
if (cell < columns.length) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
return null;
}

Categories

Resources