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!
Related
This code doesn't work for me because I can't do anything with form.isValid(), so I only need to show the tooltip and color textfield border to show user that I don't recommend to use length > 15, but if code does it anyway, its ok.
// I have some field
{
xtype: 'textfield',
maskRe: /[0-9.]/,
vtype: 'imei',
fieldLabel: 'IMEI:',
name: 'imei',
flex: 1
}
// validation for textfield on keypress
imei: function (v) {
return v.length < 16;
},
imeiText: 'length more then 15 symbols is not recommended'
// validation on save button click
validateForm: function (form) {
if (!form.isValid()) {
// don't save form
}// can't save form because imei is not valid
}
Is there any method to display vtype tooltip, color border and do not set textfield invalid ?
any help in this regards will be appreciated.
you can use listener in your textfield:
listeners: {
change: function (c, newValue, oldValue) {
var tn = newValue.replace(/[^0-9]/g, '');
if (tn.length === 0) {
setTimeout(function () {
c.markInvalid('Imei length must be at least 1 symbol');
}, 100);
}
if (tn.length > 15) {
setTimeout(function () {
c.markInvalid('Imei length more than 15 symbols is not recommended');
}, 100);
}
}
},
There is a timeout, because base field trigger the markInvalid as '' after pushing event.
Look at example on fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2r9h
if ($('<input/>').length == 0) {
T.stop();
}
the above is how I create the timer stop function.
This is where the part of the code has been placed:
$.map(exercise.syllables, function (syllable, j) {
if (!syllable || !syllable.trim().length) {
// If it doesn't exist or is an empty string, return early without creating/appending elements
return;
}
var innerSylCol = $('<div/>', {
class: 'col-md-3 inputSyllables'
});
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').each(function () {
$(this).replaceWith(getCorrectBtn($(this).val()))
});
S.addRight();
S.playRight();
} else if (cValue !== syllable){
// $(this).css({'color':'#e00413'});
S.playWrong();
S.addWrong();
}
});
innerSylCol.append(sylInput);
sylRow.append(innerSylCol);
});
idsyll = 0;
sylCol.append(sylRow);
exer.append(colLeft, sylCol);
exerciseArea.append(exer);
});
return exerciseArea;
if ($('<input/>').length == 0) {
T.stop();
}
}
The loop creates inputs based on words in my array, the inputs change to buttons when the inserted data is correct. I am trying to create it such that when the length of the inputs becomes 0 (so there are no input fields left, only buttons) it will stop the timer.
Two problems:
This code:
if ($('<input/>').length == 0) {
creates an input element, which is put in a jQuery wrapper, and then checks the number of elements in the wrapper. So the condition will always be false, because the length will always be 1. To search for input elements, remove the < and />: $("input")
You need to run that code in response to some condition (perhaps within the timer itself?) that might make $("input").length 0 by removing all input elements. Your quoted code is incomplete, but it doesn't seem like that check is being done later or in response to some event where inputs may have been removed.
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.
I've a kendo menu to dynamically enable or disable the kendo grid columns. When I select the options from the KendoMenu, the selection is firing twice. I've created the demo version below.
demo
$("#menu").kendoMenu({
dataSource: [{
text: "Menu",
items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
var selector;
$.each(grid.columns, function () {
if (this.hidden) {
selector = "input[data-field='" + this.field + "']";
$(selector).prop("checked", false);
}
});
},
select: function (e) {
// don't show/hide for menu button --- calling twice
if ($(e.item).parent().filter("div").length) return;
console.log("******");
var input = $(e.item).find("input.check");
var field = $(input).data("field");
if ($(input).is(":checked")) {
grid.showColumn(field);
} else {
grid.hideColumn(field);
}
}});
Check the console log while selecting the menu items.
Adding the checkbox to the menu item seems to lead to kendo firing the event for the menu click and the checkbox check. It seems hard to differentiate between the two instances, so it might be better to do something different to indicate the check. The following icons can be used - maybe use the tick icon instead of an actual checkbox:
http://demos.telerik.com/kendo-ui/styling/icons
I've fixed the issue with the updated code
$("#menu").kendoMenu({
dataSource: [{
text: "Menu",
items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
var selector;
$.each(grid.columns, function () {
if (this.hidden) {
selector = "input[data-field='" + this.field + "']";
$(selector).prop("checked", false);
}
});
},
select: function (e) {
// don't show/hide for menu button
if ($(e.item).parent().filter("div").length) return;
var removeItemFlag = false;
var input = $(e.item).find("label");
var selectedValue = input[0].innerHTML;
if(selectedValue)
{
for(var i=0; i< droplist.length; i++){
if(droplist[i] === selectedValue){
removeItemFlag = true
input[0].classList.remove = "fa fa-check-square-o";
input[0].className = "fa fa-square-o";
break;
}
}
var selectedIndex = droplist.indexOf(selectedValue);
if (selectedIndex > -1 && removeItemFlag) {
droplist.splice(selectedIndex, 1);
grid.hideColumn(selectedValue);
}else{
droplist.push(selectedValue);
grid.showColumn(selectedValue);
input[0].className = "fa fa-check-square-o";
}
}
}
});
Based on the answer to this question: Select all in ExtJS 4.0 Combobox
afterrender: function () {
me.container.on({
click: function(e) {
console.log('on clic called');
var el = e.getTarget('div', 3, true);
if(el.getAttribute('action') == 'select-all') {
me.select(me.getStore().getRange());
me.setSelectedCount(me.getStore().getRange().length, flabel);
allSelected = true;
} else if (el.getAttribute('action') == 'select-none'){
me.reset();
allSelected = false;
}
}
})
}
I have implemented my own Combobox with 'Select All' and 'Select None' in Ext JS.
However, if I use it more than once, the actions are applied to all the instances. Just try to click 'Select all / Select none' in one combo and you will see how the other changes: http://jsfiddle.net/hernan666/vfbkgmmu/.
For the original answer I get the same wrong behavior: http://jsfiddle.net/hernan666/dFEsc/414/
I would appreciate any help to fix this issue
I think using me.container.on is the problem.
I tried a different approach, based on your example, listening to the expand and then to the picker element click and it seems to work:
listeners: {
expand: {
single: true,
fn: function () {
var me = this,
flabel = this.getFieldLabel();
me.picker.on({
click: {
element: 'el',
fn: function (e) {
var el = e.getTarget('div', 3, true);
if (el.getAttribute('action') == 'select-all') {
me.select(me.getStore().getRange());
me.setSelectedCount(me.getStore().getRange().length, flabel);
allSelected = true;
} else if (el.getAttribute('action') == 'select-none') {
me.reset();
allSelected = false;
}
}
}
});
}
}
}
A working example: http://jsfiddle.net/ot0eaqv1/