fire jquery focus out when only the input focus is changed - javascript

I use the following code to add the selected div value into a input.
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
$('.del').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val(function(index, text){
return text.replace(/(\s+)?.$/, '');
});
})
below is a sample image if the input panel I have! This is developed for a touch device and hence the key pad.
The script works fine to add value on each button press in the keypad. The problem I'm facing is for the room number I want to run an ajax call after the user has entered the amount. But since the focus is removed every button click, how can I run the script when the focus is changed to another input. I tried the jquery .focusout() method but it gets fired each and every time the user clicks on a number button.
if anyone can suggest me a work around that would be a great help!
thank you!

Perhaps you could delay the request with something like the following:
var roomNoChanged = false;
$('#room-number').change(function() {
roomNoChanged = true;
});
$('#table-number, #no-of-guests').focus(function() {
if(roomNoChanged) {
roomNoChanged = false;
$.post(...)
}
});

Related

jQuery on change using a select dropdown with ajax search

Firstly, here is my code:
<script>
$(document).ready(function(){
$("#search_dropdown").on('change', function() {
ajax_search();
});
});
function ajax_search(){
var search_this = $("#search_dropdown").val();
$.post("../includes/db-search-properties.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
});
}
</script>
What I am trying to achieve here is quite simple. I have a select dropdown with a list of clients. On click, the select changes the data table (called #display_results) without the need of pressing a button and that is why the change function is used.
This works, how ever you can only click the select dropdown twice and then it will not drop down again unless the page is refreshed. The event also causes my other jQuery events to break (such as my menu accordion to go up and down repeatedly) and I don't know how to tell this script to only focus on the task at hand.
Even though i've removed the login script, you can view the errors via this link:
https://www.summersproperty.com/dashboard3/directory/search-properties.php
Click the drop down on the right a few times and it will stop working, click the navigation menu items afterwards and they will bounce.
I would try stopping the event from propagating further. Like so:
$(document).ready(function(){
$("#search_dropdown").on('change', function(e) {
ajax_search();
e.stopPropagation();
});
});
Documentation
It does appear after much trial and error a bug with Chrome, as it works wonders in all other browsers but stops after a few clicks in Chrome.
$(document).ready(function(){
$("#search_dropdown").on('change', function() {
var search_this = $(this).find('option:selected').val();
if(search_this !=''){
$.post("../includes/db-search-properties.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
});
}
else{ console.log("no value found"); }
return false; # optional
});
});
Have you tried this ? passing the value of current selection to your ajax call ?
for running example check this

Trigger validation after first submit, then after after every keystroke on input element

I am using jquery validation for everything I'm about to talk below.
so I have an input field, lets call it email. I also have a submit button for this form. Now by default the error message for email field will not kick in until I hit the submit button. Then whenever I type it will show/hide error message dependant on if it is a valid email. This check happens with every key stroke and this is a very important distinction to make so that you would understand my problem I posted below.
Now I have a background colour on the input, it is suppose to be green when validation has passed and red when it has failed. I have this part working, let me show you how I did it:
window.onload = function () {
$(".js-validate-circle").on("input", function () {
UpdateValidationCircle(this);
});
}
function UpdateValidationCircle(e) {
if ($(e).valid()) {
$(e).parent().addClass("active");
} else {
$(e).parent().removeClass("active");
}
}
The active class is what determines if its green or red. There is styling that is irrelevant I think to the question so I wont post it here.
Here is my problem: When the page loads and I start typing, it forces validation to trigger and error messages start coming in before I click the submit button for the first time. I am trying to prevent this. I want the color the start changing on typing only after the submit button was hit. Functionality of my red/green background should match jquery validation messages.
How would I accomplish something like this? I tried using on change but then the validation triggers only when the box loses focus.
jQuery(function($) { // DOM ready and $ alias in scope
// Cache elements
var $circle = $(".js-validate-circle");
var addedInputEvent = false; // Just a flag to know if we already added the evt listener
// On form submit....
$("#form").on("submit", function(event) {
// Prevent default form submit
event.preventDefault();
// Check immediately
$circle.each(UpdateValidationCircle);
// If not already assigned, assign an "input" listener
if(!addedInputEvent) {
addedInputEvent = true;
$circle.on("input", UpdateValidationCircle);
}
});
function UpdateValidationCircle() {
var $el = $(this);
$el.parent().toggleClass("active", $el.valid());
}
});
Use the keyup event instead:
$(".js-validate-circle").on("keyup", function () {
...
Assuming .js-validate-circle is your input... or if it is the form:
$(".js-validate-circle").on("keyup", "#id-of-the-input", function () {
...
If this doesn't work, we are going to need to see validate()s code and some markup.

Cannot get enter keypress to work in jQuery when calling click function

I'm currently working on code that builds a div box when the user clicks on the .pTile div that does not have the .join class. The click function works, however, for accessibility reasons, I need to have the enter key also build the div when the user uses the enter key. There are multiple .pTile's on the page and more or less can be added at any time through a database. I can't seem to get the enter key function to work. Assistance would be much appreciated.
The following is the working click function the code in it is omitted as it's pretty long:
$(document).on('click', '.pTile:not(.join)', function (e) {
//Do stuff
});
This is the code that I am not able to get to work:
$('.pTile:not(.join)').bind('keypress', function (e) {
if (e.keyCode || e.which) {
$('.pTile:not(.join)').click();
return false; }
});
EDIT: I'd also like to note that the key press function does not get fired at all.
Here is a JSBin with a solution: http://jsbin.com/yelomunafo/1/
Basically you add keypress to the $(document).on('click') part.

event.PreventDefault doesnt work until end of function

I have a checkbox on which i am trying to send an ajax request based on its position. It is true by default. I want to be able to click it, and get a dialog that asks me if I want to discard my changes,and this dialog depends on the fact that the checkbox is not yet false.
$("input[type='checkbox']").click(function(evt) {
evt.preventDefault();
alert(this.checked);
if(checkEdited()){
var result = confirm("Do you want to continue?");
}
});
function checkEdited(){
var checkbox = $("div.managerContent input[type='checkbox']");
if(!checkbox.checked){
return false;
}
else{
//check other stuff
}
}
And everytime, I am getting false in the alert. In the browser, when I click the checkbox the check goes away, i get the alert, and then the check comes back.. checkEdited() is also used in other places
Everywhere I look to find how to stop a checkbox change event and assign it a value later just tells me to use .click and e.prenventDeafult()
Any ideas? Thanks so much!
You should attempt to capture the event before the click is complete, you can do this with mousedown like so:
$("input[type='checkbox']").on('mousedown',function(evt) {
evt.preventDefault();
alert(this.checked);
});
Here is a demo with a working example of capturing it before it changes
JSFIDDLE DEMO

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources