Automatically submit input value when switching between input fields > focus lost - javascript

I have multiple input fields which can be manipulated by keypresses or a jquery keypad plugin.
At this point the only issue left is to keep the input field on focus when switched from one to another. I know the root cause of this issue is
$(".keypad-close").click();
which is simulating the keypress of the keypad's close (enter) button. this click action is setting focus to the button instead of the new input field:
Javascript:
$( document ).ready(function() {
var keypadTarget = null;
$('#inlineKeypad').hide();
function setKeypads(){
$('.inlineTarget').focus(function(){
$('#inlineKeypad').show();
if (keypadTarget != this.id) {
$(".keypad-close").click();
keypadTarget = this.id;
}
$('#inlineKeypad').keypad('option', {target: $('#'+keypadTarget)});
});
}
The function setKeypads() is initiated from within another function on page load.
HTML:
<input step="0.01" value="0.00" id="price-5" class="inlineTarget">
<input type="text" value="0" id="quantity-5" class="inlineTarget">
Can anyone of you point me in the right direction on how to achieve this?

$('.inlineTarget').on('blur', function() {
var value = $(this).val();
$.ajax({
url: '',
data: {
value: value
},
....
});
});

Related

Select2 add/update on input change

I have a select2 element and an input element as follows...
Label: <input class="default-ele" type="text"/>
<select class="some-select">
<option>-- None --</option>
</select>
and some JS/JQuery as follows...
$(document).ready(function() {
$(`.${type}-default`).select2({
theme: 'bootstrap'
});
$(document).on('change', '.default-ele', function() {
var newVal = $(this).val();
var selAdd = new Option(newVal, newVal);
$('.some-select').append(selAdd).trigger('change');
});
});
That all works except that if you enter a value into the input then click the select with the cursor still in the input, the value is not there until you move focus away from the select and back to it. Is there a timeout or some other way to get the value to display when immediately clicking on the select after the input changes?
TIA
I would suggest to use keypress event to trigger 'select' refresh functionality.
Something like below.
This should update trigger callback on input as soon as you lift key.
$(document).ready(function() {
$(`.${type}-default`).select2({
theme: 'bootstrap'
});
$(document).on('keyup', '.default-ele', function() {
var newVal = $(this).val();
var selAdd = new Option(newVal, newVal);
$('.some-select').append(selAdd).trigger('change');
});
});

e.preventDefault() behvaing differently

I have a very simple jQuery UI spinner as follows:
<input value="2" class="form-control ui-spinner-input" id="spinner" aria-valuemin="2" aria-valuemax="24" aria-valuenow="2" autocomplete="off" role="spinbutton" type="text">
Using jQuery I set the above text box readonly true/false. The readonly and value is set based on the checkbox a user selects and that function looks like
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
var isChecked = this.checked;
var currentElement = this;
var $radioButton = $('.usage-failure-type-radio');
$targetCheckBoxes.filter(function () {
return this.id !== currentElement.id;
}).prop('disabled', isChecked);
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked);
$radioButton.first().prop('checked', isChecked);
$radioButton.not(':checked').toggle(!isChecked).parent('label').toggle(!isChecked);
$('.usage-before-failure > div > span.ui-spinner > a').toggle(!isChecked);
});
}
Now what I'm trying to achieve is when the #spinner input is readonly and if the user presses the back space I want to prevent the default behaviour e.g. do navigate away from the page. For this I thought I'd do the following:
$('.prevent-default').keydown(function (e) {
e.preventDefault();
});
Which works fine if the input has the class prevent-default on page load. However, if I add it in my checkBoxes function in the following line
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default')
Then I press the backspace it ignores e.prevenDefault();
But if I do
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).keydown(function (e) { e.preventDefault(); });
Then it works absolutely fine.
Can someone tell me why this is happening please.
The reason I want to use a separate function with a class name is because I have various inputs which get set to read only based on different check/radio values.
Can someone tell me why this is happening please
This is because of the DOM parser and the timing when JavaScript is executed.
If you already have an element with a class prevent-default in your DOM before JS is executed, then the JavaScript will recognise and handle it correctly. If you instead add the class afterwards with JS, then you have to re-initialise the keydown-event again to make it work.
To re-initialise you will need something like this:
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
...
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default');
// assign new keydown events
handleKeyDown();
...
});
}
function handleKeyDown() {
// release all keydown events
$('#spinner').off( "keydown", "**" );
$('.prevent-default').keydown(function (e) {
e.preventDefault();
// do more stuff...
});
}

Onchange of a input field changed by Javascript

I have a input field type="hidden" which is changed by javascript itself.
When this field changes i want an event/function to be triggered.
Tried this:
$(".product_id").on("change paste keyup input", function(event){alert('1');});
$(".product_id").blur(function(event){alert('1');});
$(".product_id").keypress(function(event){alert('1');});
But it does not seem to work as the value is changed by other JavaScript file itself.
I cannot change or add to the existing JavaScript.
I cannot add anything to the input field.
You can use jQuery's trigger method & change event.
Changes in value to hidden elements don't automatically fire the .change() event. So, as soon as you change the hidden inputs, you should tell jQuery to trigger it using .trigger('change') method.
You can do it like this:
$(function() {
$("#field").on('change', function(e) {
alert('hidden field changed!');
});
$("#btn").on('click', function(e) {
$("#field").val('hello!').trigger('change');
console.log('Hidden Filed Value: ' + $('#field').val());
});
console.log('Hidden Filed Value: ' + $('#field').val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="field" type="hidden" name="name">
<button id="btn">
Change Hidden Field Value
</button>
Hope this helps!
It's just a hack if you can't trigger change event from sources.
May not be a good solution with setInterval(). But helps in the cases where you can't trigger change event from sources which are changing the hidden input value.
$("#input")[0].oninput = function(){
$("#hidden").val($(this).val()); //setting hidden value
}
var oldVal = $("#hidden").val();
setInterval(function(){ //listening for changes
var newVal = $("#hidden").val();
if(newVal !== oldVal){
console.log(newVal);
oldVal = newVal;
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hidden">
<input type="text" id="input">
var element = $(".product_id");
element.on("change", function(){
alert('hey');
}).triggerHandler('change');
and we need to trigger it programmatically like:
$('.product_id').val('abcd').triggerHandler('change');

how to add event handler for input text box

My program should contain both name search and ID search functionality, when user clicks the name search button, a name search validation is triggered to make sure that the required text field is not empty, on the other hand, when user clicks the id search button, an id search validation is triggered to make sure that a different required text field is not empty. So on the HTML file, I have the following jQuery and HTML codes.
$(document).ready(function() {
$('#submitIDSearch').bind('click', validateIDSearch);
$('#submitNameSearch').bind('click', validateNameSearch);
$('#searchLastName').bind('click', validateNameSearch);
$('#searchFirstName').bind('click', validateNameSearch);
$('#searchID').bind('click', validateIDSearch);
});
var validateNameSearch = function(event) {
var btnSrchLastName = getRef('searchLastName');
if (null != btnSrchLastName) {
var len = btnSrchLastName.value.length;
if (0 == len) {
alert('Last Name is a required field, please input Last Name.');
$('#searchLastName').focus();
return false;
}
}
return true;
}
var validateIDSearch = function(event) {
var btnSrchID = getRef('searchID');
if (null != btnSrchID) {
var len = btnSrchID.value.length;
if (0 == len) {
alert('ID is a required field, please input ID.');
$('#searchID').focus();
return false;
}
}
return true;
}
And I have the following HTML code:
<form id="infoForm" name="checkAbsenceForm" method="post" action="absenceReport.htm">
<label class="q">ID * <input id="searchID" name="searchID" maxlength="9" /></label>
<input id="submitIDSearch" type="submit" value="Search ID"/>
<hr />
<label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23"></label>
<br />
<label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" /></label>
<input id="submitNameSearch" type="submit" value="Search Name"/>
<hr />
</form>
The code behaves correctly except for one problem, when ever the user clicks on the textbox, a click event is fired, which cause a pre-generation of the alert message box.
I observed that when the user types 'enter' key from a text field, a click event is triggered, instead of 'submit', so I guess my listener can only be bind to the click event.
May I ask if there's a workaround method to avoid event triggering from mouse clicking on the textbox?
Thanks a lot!
In case you still need help... http://jsfiddle.net/jaxkodex/Cphqf/
$(document).ready(function() {
$('#submitNameSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchLastName'), 'Last name field is required.')) {
$('#infoForm').submit();
}
});
$('#submitIDSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchID'), 'ID field is required.')) {
$('#infoForm').submit();
}
});
});
function validate(input, errorMsg) {
if (input.val() == null || input.val().length == 0) {
alert(errorMsg);
return false;
}
return true;
}
Since you are using jQuery, You can submit the form whenever a button is clicked with $('#infoForm').submit(); If you check you'd need to use button inputs and no submit inputs any more, since they will trigger the submit event. This is just one approach. If you are looking for live validation, you could use the blur events instead of click but in the text inbut and the click event to the buttons to make sure it works. I guess that overwritting the submit function would work when you have to do some ajax. Hope it helps.
[Edit] If you want to keep the buttons as submit you can do some thing like: http://jsfiddle.net/jaxkodex/S5HBx/1/
You can use the submit event from the form, so it will check every time someone submits the form. jQuery - Submit
$('#infoForm').submit(function (event){
if (!validateIDSearch() && !validateNameSearch()){
event.preventDefault(); // Prevent the submit event, since didn't validate
}
// Will continue to the dafault action of the form (submit it)
});
You just need to set what button the user has selected and do validation based on that during form submit.
searchLastName searchFirstName submitNameSearch are calling validateNameSearch, and submitIDSearch searchRUID are calling validateIDSearch
$(function () {
var validateFx = null; //none selected;
$('#submitNameSearch, #searchLastName, #searchFirstName')
.bind('click', function () {
validateFx = validateIDSearch;
});
$('#searchIDSearch, #searchRUID')
.bind('click', function () {
validateFx = validateNameSearch;
});
$('#infoForm').submit(function (event){
event.preventDefault();
if (validateFx != null && validateFx ()) {
$(this).submit();
}
});
});

Javascript Textbox Event

I am facing problem with input text type (ie. Text Box).
I have written a function used by the onkeyup event on a Text Box. The line looks like this:
<input type='TEXT' value='abc' onkeyup='changeSomething( this );'>
But now I am facing problem that when user selects values from the previously entered values,
I am not getting any event when user selects any previously entered values from the drop down (edit: I believe he is referring to browser autocomplete here).
Does anyone have solution for this? :)
use onchange instead of onkeyup in this case
see: http://www.w3schools.com/jsref/event_onchange.asp
e.g.
<input type='text' value='abc' onchange='changeSomething(this);' />
to get around this
EDIT
Two things:
1) Autocomplete values can be selected using arrow keys and enter/tab, and by using the mouse. The arrow keys/enter.tab fire the onkeyup events... clicking in the autocomplete box does not, however, fire the onclick event.
2) The onchange event fires as soon as focus is lost IF the content has changed. Focus is not lost when selecting autocomplete values.
Essentially, there does not appear to be any way to reasonably guarantee the event will be processed the way you want.
First off, do you really need to listen to every keystroke?
Secondly, would you be better served by turning off autocomplete?
(e.g. <input type='text' value='abc' autocomplete='off' onkeyup='changeSomething(this);' />)
Here's a solution which polls the element periodically for any changes
<script type="text/javascript">
var changeWatcher = {
timeout: null,
currentValue: '',
watchForChange: function( el ) {
if( el.value != this.currentValue ) {
this.changed( el );
}
this.timeout = setTimeout( function() {
changeWatcher.watchForChange(el)
}, 200 );
},
cancelWatchForChange: function() {
clearTimeout( this.timeout );
this.timeout = null;
},
changed: function( el ) {
this.currentValue = el.value;
// do something with the element and/or it's value
//console.log( el.value );
}
}
</script>
<input type='text' value='abc' onfocus='changeWatcher.watchForChange(this)' onblur='changeWatcher.cancelWatchForChange()' onchange='changeWatcher.changed(this)' />

Categories

Resources