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?
Related
I'm working on virtual keyboard with autosuggestion. I found hundreds of ready made example on internet. But all these autocomplete javascript code working only on keyboard key press. I'm very new to javascript. Can anyone help me to show autosuggest when i press mouse on a virtual keyboard button's key. My code is given below which is working good in keyboard key press.
$(function() {
var availableTags = [
"computer",
"keyboard",
"mouse",
];
var minWordLength = 1;
function split(val) {
return val.split(' ');
}
function extractLast(term) {
return split(term).pop();
}
$("#note-textarea")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: minWordLength,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
var term = extractLast(request.term);
if (term.length >= minWordLength) {
response($.ui.autocomplete.filter(availableTags, term));
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(" ");
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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 have a custom grid and some cells have a cell editor , an Ext.form.TextField, in order to modify value of the cell.
Here is how is defined the TextField:
var labelTextEditor = new Ext.form.TextField({
allowBlank: false,
maxLength: 256,
id: "labelTextEditor",
maxLengthText: Label.conf.ui.javascript.TooLongText,
validateOnChange: true,
validator: function(value) {
console.log(value);
if (value == "" && value.trim() == "") {
return formatMessage(Label.conf.ui.supv.LabelMandatory);
} else
return true;
},
msgTarget: 'under',
listeners: {
focus( a, event, eOpts ){
var rowIndex = customFieldGrid.getSelectionModel().getCurrentPosition().row;
if(rowIndex !== undefined && rowIndex !== null){
a.setValue(view.listOfServiceDefinition[0].customFields[rowIndex].labels[userLanguagePrefix]);
}
},
blur(a, event, eOpts){
var cellValue = a.getValue();
if(cellValue !== undefined && cellValue !== null){
a.setValue(cellValue);
}else{
a.setValue("");
}
}
}
});
When I focus on the cell, it keeps me the value that was there before focusing on the cell, thanks to the focus listener. But when I lose focus, the cell displays nothing. When I click back on it, the value is displayed again and can be edited. So the problem is that when I lose focus, the value cannot be kept displayed on the cell. I've tried to blur event but didn't help...
Problem here is your blur event. As Per Documentation blur event Fires when this Component loses focus. So in your case when you loosing focus your blur event is firing. And As I can see in your blur event You are setting some other values, Therefor it is coming as empty.
This line is causing an issue in your code :
else{
a.setValue("");
}
I also created one fiddler to understand blur and focus.
Fiddle
Me and a few co-workers are slightly puzzled by this issue. We have an onclick event in Javascript which opens a JQuery dialog box. This works when you actually click the designated button. However, when you press enter, it will trigger the onclick event and also perform the other required functions. But when it hits the dialog, it does not open. Strangely, if you insert an alert before the dialog code, it will open the alert and then open the dialog. Any fixes?
JQuery:
$(document).ready(function () {
$('#applyFilter').click(function () {
console.log('event triggered');
var suppString = $('#FK_SupplierID').val();
var carryOn = true;
//if the supplier ID fields is showing and populated:
//check if supplier ID values are all numeric, if not show message and modal form
if (suppString != null) {
suppString.split(",").forEach(function (item) {
if (item != '') {
if (!isInt(item)) {
//invalid value - set carryOn to false and exit the loop
carryOn = false;
return false;
}
}
});
if (!carryOn) {
alert("The Supplier ID field must only have a whole number, or a comma-separated list of whole numbers. Please type in a valid value or click the ellipsis button to select the required suppliers from the supplier list.")
return false;
} else {
//check if supplier label is populated - if not, populate it
if (suppString != '' && $('#suppliersShown').text() == '') {
//GetSupplierNames
$.getJSON("./GetSupplierNames", { ids: suppString },
function (data) {
$('#suppliersShown').text("Supplier(s):" + data);
$('#suppliersShown').show();
}
);
}
}
}
$('#dialog-processing').dialog({
closeOnEscape: false,
//open: function (event, ui) {
// $(".ui-dialog-titlebar-close").hide();
//},
autoOpen: false,
width: 400,
resizable: false,
modal: true
});
$('#dialog-processing').dialog('open');
var table = $('#invoiceTable').on('processing.dt', function (e, settings, processing) {
// $('#dialog-processing').dialog('close');
}
).DataTable({
retrieve: true,
});
table.ajax.url('./FilterData/?filterString=' + FilterParams()).load(function (json) { console.log(json); });
});
});able({
retrieve: true,
});
table.ajax.url('./FilterData/?filterString=' + FilterParams()).load(function (json) { console.log(json); });
});
HTML:
<button id="applyFilter">click</button>
I am using jQuery validation plugin, and after I added focus() and blur()event handlers to delete and set pre populated value,if I try to submit form without changing default value, value is replaced with empty string, where desired is to leave value untouched and run validate().
JS code is as follows:
$.validator.addMethod("mobileHR", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^\+[0-9]{1,3}\.[0-9]{1,14}$/);
}, "Unesite broj u fromatu: +385.111234567");
$(document).ready(function () {
// append help block below input
$('.controls').append('<span id="helpBlock" class="help-block">Format broja: +385.11123456789</span>');
// clear pre populated value on focus
var value = $("input[name='contactdetails[Registrant][Phone]']").val();
$("input[name='contactdetails[Registrant][Phone]']").focus(function() {
if ($(this).val() == value)
{
$(this).val("");
}
}).blur(function(event) {
if($(this).val() == "")
{
$(this).val(value);
}
});
// initialize validation
$('.form-horizontal').validate({
// set immediate validation, on event code 9
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
},
rules: {
"contactdetails[Registrant][Phone]": {
required: true,
mobileHR: true
}
},
messages: {
"contactdetails[Registrant][Phone]": {
required: "Molimo unesite broj telefona"
}
}
});
// check if form is valid then enable submit button
$('.form-horizontal input').on('keyup blur', function () {
if ($('.form-horizontal').valid()) {
$('.btn-primary').removeClass('btn-disabled');
} else {
$('.btn-primary').addClass('btn-disabled');
}
});
//do we valid form on document.ready?
//$('.form-horizontal').valid();
});
Fiddle is here.
After little research, I've found why is value changing on form submit:
$("input[name='contactdetails[Registrant][Phone]']").focus(function() {...});
After form is submitted, validate() is run, and as field is empty, input field is focused, so focus() is triggered again, and value of input field is "".
Changing event to click input field get focused, but value is untouched, as now function is fired on click event.