jquery bind form submission and anchor in single call - javascript

Currently I have this code (which works just fine):
<form>
<input type="text" />
<a id="btn">add</a>
</form>
$(document).ready(function () {
$('form').submit(foo);
$('#btn').click(foo);
});
function foo() {
//do some stuff
}
I am currently binding the foo function to both the form submission, and the anchor click. But, I actually prefer not to have the form, although it seems to be the easiest way to bind the enter key on the textbox to the foo function.
What is the easiest way to achieve both bindings in one single statement, without the form, and without binding the textbox to a keypress and checking the keycode == 13? Is there a built in event I can bind to for the enter key on the textbox?
To explain with some pseudo code, this is roughly what I would like it to look like:
//get rid of the form
<input type="text" class="submit"/>
add
$(document).ready(function () {
//and only have one binding statement
$('.submit').bind('click enterPressed', foo);
});
function foo() {
//do some stuff
}

There's no ready-made event called enterPressed or any event for that matter that just responds to the enter key. The short answer is, therefore, there's no way to achieve what you've asked. The long answer is below, if you're open to creating a custom event, enterPressed.
You can define a custom event called enterPressed on the input element, and then you would have to prevent the input element from responding to any click events:
$(function() {
$('input.submit').on('keypress', function(e) {
e.which !== 13 || $(this).trigger( 'enterPressed' );
})
.on('click',function(e) { e.stopImmediatePropagation(); });
$('.submit').on('click enterPressed', foo);
function foo() {
console.log( 'foo called' );
}
});
WORKING JS FIDDLE DEMO

For your enterPressed event you can do this. Trigger your custom event:
$('#element').keyup(function(event) {
if(event.which === 13) $('#element').trigger('enterPressed');
});
You can use .on() to bind a function to multiple events including the custom one:
$('#element').on('click enterPressed', function() {
...
});
Not sure about the code. But it should give you something to look up.

Related

Double event handler and one function. How to prevent executing code twice?

I have one callback function bound to two events (change and focusout). However, I need the focusout to happen only when the element we're interacting with is not a checkbox.
This is the example code:
$(document).on('focusout change', '.selector', function() {
if ($(this).is(':checkbox')) {
// Do stuff and prevent the focusout to trigger. HOW???
}
doStuff(); // Action that applies to both cases, but needs to be limited at one execution only
});
The code above will execute twice:
When the checkbox gets checked/unchecked
When you click outside of the checkbox (lose focus (blur))
I tried using .off, but it ends up killing the focousout handler altogether, which I will need later for other elements which aren't checkboxes.
What would be the way to prevent the focusout handler to trigger for certain elements?
What you want to do is
$(document).on('focusout change', '.selector', function(event) {
event is an event object, which has properties, one of which is type. Checking the type you can now see if your function has been called because of a focusout or a change and run code as appropriate
The best way is to affect both events (or more) to the same function, like this :
A text input for example
<input id="myfield" type="text" />
Now the Javascript
var myfield = document.getElementById('myfield');
myfield.onfocus = myfield.onchange = function(e)
{
//your code
}
Yo can even add an other element
button.onclick = myfield.onkeyup = function(e)
{
//when the client press the enter key
if(e.key && e.key == "Enter")
{
//catch the target
}
//when the client click the button
else if(!e.key || e.target == button)
{
//catch the target
}
//otherwise you can do not care about the target and just execute your function
}
You must only know that you can add many elements and many events
element1.onfocus = element1.onblur = element2.onchange = element3.onchange = function(e){//your code}

jQuery - bind multiple events and exclude other events

I've got a search form that has both <input type="text"> and <select> form elements. Listening in to that form I've got this jQuery...
$('#searchform :input').stop().on('keyup change',function(){
// do some ajax stuff
})
The tricksy bit is the way the script listens for multiple events using .on('keyup change' etc.). This works great but there's a problem...
When the input fields lose focus the script jquery listener is triggered.
Here's a demonstration to explain what I mean https://jsfiddle.net/o2k4jf90/1/
I want to do something like this...
$('#searchform :input').stop().on('keyup change not:blur',function(){
// do some ajax stuff
})
...but clearly that's nonsense. What can I do?
Try substituting input event for change , keyup events
$(document).ready(function () {
$(':input').on('input',function(e) {
$('#report').append('stuff happened<br />');
})
});
jsfiddle https://jsfiddle.net/o2k4jf90/3/
The issue is because the change event fires when an input field loses focus, and when the chosen option of a select is modified. To achieve what you need, you would need to bind the events separately. Try this:
$(document).ready(function () {
$('input').keyup(stuffHappened);
$('select').change(stuffHappened);
})
function stuffHappened() {
$('#report').append('stuff happened<br />');
}
Updated fiddle
You can still use a single event handler if you hook the event to the form, however you would need to check the type and target.tagName of the event to achieve the same logic, which is not pretty at all:
$('form').on('keyup change', function(e) {
if ((e.type == 'change' && e.target.tagName == 'SELECT')
|| (e.type == 'keyup' && e.target.tagName == 'INPUT')) {
$('#report').append('stuff happened<br />');
}
});
For this reason, I would suggest using the former method.

Firefox onchange not calling function

I have a form that contains input:
<input onchange="checkDomain(true); return false;" type="text" id="dsearch" value="" name="domain" maxlength="30"/>
Which works just fine in Opera, Chrome and IE - but Firefox and Safari are having problems with calling the function checkDomain(). I added a line into the function for debugging:
function checkDomain(check)
{
console.log('checkDomain() called!');
// do rest of the stuff...
}
So, Chrome/Opera/IE calls the function with no problem after you enter text and click somewhere else - but Firefox/Safari doesn't. Anyone have a clue?
I cannot remember where I read it, but you should use .keydown()/.keyup()/.keypress() (whatever suits your needs) instead of onchange. At least for input[type=text].
you can use .blur() and .focus for their respective purposes too.
Seeing this in your question: "after you enter text and click somewhere else", makes me conclude you need the .blur() function.
$("input[type=text]").blur(function(){
console.log('checkDomain() called!')
});
maybe onblur is best for this:
<input onblur="checkDomain(true); return false;" type="text" id="dsearch" value="" name="domain" maxlength="30"/>
This problem happens when you change the behavior of your input keypress and key down.
You need to manually call the onchange trigger to fire it.
As an example consider you have a jQuery function for your inputs which do some stuff when user clicks on keyboard.
You need to call input.trigger("onchange"); to make sure the onchange is fired after keypress and keydown
/**
* Keyboard Manager
*/
(function($) {
$.fn.inputManager = function(options) {
};
options = $.extend(defaults, options);
// The key down event only use to manage key board language changes
var keyDown = function(e) {
//Do something
};
var keyPress = function(e) {
//Do something
};
return this.each(function() {
var input = $(this);
//The Firefox dose not trigger the input onchange when you change keypress and key down
//functions. So manually call it!
input.keypress(function(e) {
keyPress(e);
input.trigger("onchange");
});
input.keydown(function(e) {
keyDown(e);
input.trigger("onchange");
});
});
};
})(jQuery);

jQuery trigger not working in IE. Why?

$('#XynBp0').find('input').each(function(){
if ($(this).attr('value') == 'Cancel'){
$(this).trigger('click');
}
});
doesn't work in IE7
it's strange but try to create a custom event
$('#XynBp0 input').bind('custom',function(){
//code
})
$('#XynBp0').find('input').each(function(){
if ($(this).attr('value') == 'Cancel'){
$(this).trigger('custom');
}
});
Does this work?
$.click() (or $.trigger('click')) doesn't simulate a mouse click; it fires off any onclick events bound to that element. If you haven't assigned an onclick event to that input you're searching for, nothing will happen.
It sounds like you're trying to submit the form with a traditional submit button (e.g. <input type="submit" value="Cancel">). If that's the case, you may have to use $(yourform).submit() to submit the form, in combination with some handling of the data sent to the server to simulate clicking the Cancel button.
Is it wrapped in a dom ready event? Might help if you provide more code.
$(function () {
$('#XynBp0').find('input').each(function () {
if ($(this).attr('value') == 'Cancel') {
$(this).trigger('click');
}
});
});
Your code snippit doesn't make any sense, you are clicking inputs if they are canceled?
Here's some things to clean up in your code
$('input','#XynBp0').each(function () {
var $this = $(this);
if ( this.value === 'Cancel' ) { //Don't need jQuery here
$this.trigger('click'); //Probably don't need it here either
}
});
What does click even do? If you are trying to submit a form, use form.submit();

jQuery .keyPress() - How to get value of input which triggered event?

Trying to do some jQuery validation (without the plugin - please no answers like "Just use the validate-js plugin").
I'm wiring up a client-side event handler keypress for each "required field" on doc ready:
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keypress(onRequiredFieldKeyPress);
});
});
Which correctly fires this event on each keypress:
function onRequiredFieldKeyPress() {
if ($(this).val().trim() == '') {
$(this).next('em').html('*').show(); // show req field indicator
} else {
$(this).next('em').html('*').hide(); // hide req field indicator
}
}
But $(this).val() is always null/empty. Looks like it's passing in an "HTMLInputElement" which is what i'd expect, but it's almost like i have to project this into some other jQuery type?
Essentially i'm trying to do this: on the keypress event of any field which i have wired-up (which are all input elements), call that function. In that function, if that field has a value of '' (empty), then show a hidden field which displays a required field indicator.
I don't really care which actual element fired the keypress, as the behaviour of my logic will be the same. I just need to get the actual value.
Am i missing something?
Because you are using key-press event. Key press has 3 phase:
1. Key down: when key is press
2. Key hold: key is hold down
3. Key up: key is release
In your case, problem can be solved by using keyup event
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keyup(onRequiredFieldKeyPress);
});
});
Try using event.currentTarget, where event is the first param of your function.
See here: http://api.jquery.com/event.currentTarget

Categories

Resources