I have below jquery code which is execute on keypress but I would like to execute same on button click. Please help me.
$('#itemselected').live('keypress', function() {
//some code which using $(this) also.
}
var myFunction = function(event){
console.debug(event);
//do your stuff here
};
$('#itemselected').on('keypress', function(event) {
myFunction(event);
}
$('#itemselected').on('click', function(event) {
myFunction(event);
}
Try to trigger the keypress on click
$('button').click(function() {
$('#itemselected').trigger('keypress');
});
I think you can just add 'click' to the list of event types like so:
$('#itemselected').on('keypress click', function() {
//some code which using $(this) also.
});
Suppose I want to run a function myFunction at each of the events $(document).ready, $(sometag).on('click',....). How can I construct a function that checks if any of those two events are triggered, and then run the method. Can I pass $(document) as an argument and then check $(document).isReady or check $(document).click(function(e){if (e.target.is($(some tag))) ...}). Is this correct ?
It's not easy to understand what the heck you are talking about, but it sounds like you're trying to attach an event handler and trigger it on document ready, and if so you'd do that like this :
$(document).ready(function() {
$(sometag).on('click', function() {
// do stuff
}).trigger('click');
});
If I understand you correctly:
function myFunc(event) {
if (event.type == 'ready')
console.log('It is a document.ready');
else if (event.type == 'click')
console.log('It is a click');
}
$(document).on('ready', myFunc).on('click', 'a', myFunc);
jsfiddle
from what i could understand from your question...
Jsfiddle: http://jsfiddle.net/patelmilanb1/eR4wG/1/
$('.checkbox').change(function (e) {
if (e.isTrigger) {
alert('not a human');
} else {
alert("manual check by human");
}
});
$('.checkbox').trigger('change'); //alert not a human because it is automatically triggered.
I may not understand your question very much, but try this:
$(function(){
$('div1,div2,#id1,#id2,.class1,.class2').click(function(){
// do something
yourFunction();
});
});
triggering function on multiple events of an element, you may try:
$('#element').on('keyup keypress blur change', function() {
...
});
and multiple function on multiple elements, try:
$('#element #element1 #element2').on('keyup keypress blur change', function() {
...
});
$('input').change(function(){
alert($(this).val());
});
$('input').val(1);
This dont work. I need capture the change input with JavaScript :-s
Thanks.
Programmatic changes to <input> elements don't cause events. Only user interaction does.
You can do this however:
$('input').val(1).trigger('change');
You have to put those functions inside the "Ready" function. see the fiddle: http://jsfiddle.net/SfjJQ/1/
$(function() {
$('input').change(function() {
alert($(this).val());
});
$('input').val(1);
$('input').trigger('change');
});
keep in mind that your:
$('input').val(1);
initializes the input to have a value of 1.
Of course you could also do this:
$(function() {
$('input')
.change(function() {
alert($(this).val());
})
.val(1)
.trigger('change');
});
As others have mentioned, .val() does not trigger any events; however, you could add a wrapper function to jQuery that will change the value and trigger the event if wanted:
$( function () {
//-- new jQuery function
$.fn.changeVal = function () {
$.fn.val.apply( this, arguments );
$( this ).trigger( 'change' );
};
//-- your updated code
$('input').change(function(){
alert($(this).val());
});
$('input').changeVal(1);
} );
http://jsfiddle.net/bA3V2/
I've got code so that when you click on a word, it is replaced by another word.
<script>
$(document).ready(function() {
$('.note_text').click(function(){
$(this).remove();
$('#note_div').append('<span class="note_text">new</span>');
// re-applying behaviour code here
});
});
</script>
<div id="note_div">
<span class="note_text">preparing</span>
</div>
I need the appended word to have the same click behaviour. What is the best way to do this?
change
$('.note_text').click(function(){
to
$('.note_text').live('click',function(){
This will cause anything on your page that ever gets the class 'note_text' to have the behaviour set by .live
You should use a .live()help or .delegate()help binding for that purpose.
$(function() {
$('#note_div').delegate('.note_text', 'click', function(e) {
$(e.target).parent().append("<span class='note_text'>new</span>").end().remove();
});
});
Demo: http://www.jsfiddle.net/PkngP/2/
You could rebind the handler:
function handler(){
$(this).remove();
$('#note_div').append("<span class="note_text">new</span>");
$(".note_text").unbind("click");
$('.note_text').click(handler);
}
$(document).ready(function() {
$('.note_text').click(handler);
});
jquery toggle calls preventDefault() by default, so the defaults don't work.
you can't click a checkbox, you cant click a link etc etc
is it possible to restore the default handler?
In my case:
$('#some_link').click(function(event){
event.preventDefault();
});
$('#some_link').unbind('click'); worked as the only method to restore the default action.
As seen over here: https://stackoverflow.com/a/1673570/211514
Its fairly simple
Lets suppose you do something like
document.ontouchmove = function(e){ e.preventDefault(); }
now to revert it to the original situation, do the below...
document.ontouchmove = function(e){ return true; }
From this website.
It is not possible to restore a preventDefault() but what you can do is trick it :)
<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
if($(this).hasClass('prevented')){
e.preventDefault();
$(this).removeClass('prevented');
}else{
$(this).addClass('prevented');
}
});
</script>
If you want to go a step further you can even use the trigger button to trigger an event.
function DoPrevent(e) {
e.preventDefault();
e.stopPropagation();
}
// Bind:
$(element).on('click', DoPrevent);
// UnBind:
$(element).off('click', DoPrevent);
in some cases* you can initially return false instead of e.preventDefault(), then when you want to restore the default to return true.
*Meaning when you don't mind the event bubbling and you don't use the e.stopPropagation() together with e.preventDefault()
Also see similar question (also in stack Overflow)
or in the case of checkbox you can have something like:
$(element).toggle(function(){
$(":checkbox").attr('disabled', true);
},
function(){
$(":checkbox").removeAttr('disabled');
})
You can restore the default action (if it is a HREF follow) by doing this:
window.location = $(this).attr('href');
if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.
I have created a demo JS fiddle to demonstrate how this works:
Here is the code of the JS fiddle:
HTML:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Default click action is prevented, only on the third click it would be enabled
<div id="log"></div>
Javascript:
<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
event.preventDefault();
$( "<div>" )
.append( "default " + event.type + " prevented "+counter )
.appendTo( "#log" );
if(counter == 2)
{
$( "<div>" )
.append( "now enable click" )
.appendTo( "#log" );
$(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
}
else
{
$( "<div>" )
.append( "still disabled" )
.appendTo( "#log" );
}
counter++;
});
});
</script>
Test this code, I think solve your problem:
event.stopPropagation();
Reference
The best way to do this by using namespace. It is a safe and secure way. Here .rb is the namespace which ensures unbind function works on that particular keydown but not on others.
$(document).bind('keydown.rb','Ctrl+r',function(e){
e.stopImmediatePropagation();
return false;
});
$(document).unbind('keydown.rb');
ref1: http://idodev.co.uk/2014/01/safely-binding-to-events-using-namespaces-in-jquery/
ref2: http://jqfundamentals.com/chapter/events
If the element only has one handler, then simply use jQuery unbind.
$("#element").unbind();
Disable:
document.ontouchstart = function(e){ e.preventDefault(); }
Enable:
document.ontouchstart = function(e){ return true; }
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.
window.onKeydown = event => {
/*
if the control button is pressed, the event.ctrKey
will be the value [true]
*/
if (event.ctrKey && event.keyCode == 83) {
event.preventDefault();
// you function in here.
}
}
I had a problem where I needed the default action only after some custom action (enable otherwise disabled input fields on a form) had concluded. I wrapped the default action (submit()) into an own, recursive function (dosubmit()).
var prevdef=true;
var dosubmit=function(){
if(prevdef==true){
//here we can do something else first//
prevdef=false;
dosubmit();
}
else{
$(this).submit();//which was the default action
}
};
$('input#somebutton').click(function(){dosubmit()});
Use a boolean:
let prevent_touch = true;
document.documentElement.addEventListener('touchmove', touchMove, false);
function touchMove(event) {
if (prevent_touch) event.preventDefault();
}
I use this in a Progressive Web App to prevent scrolling/zooming on some 'pages' while allowing on others.
You can set to form 2 classes. After you set your JS script to one of them, when you want to disable your script, you just delete the class with binded script from this form.
HTML:
<form class="form-create-container form-create"> </form>
JS
$(document).on('submit', '.form-create', function(){
..... ..... .....
$('.form-create-container').removeClass('form-create').submit();
});
in javacript you can simply like this
const form = document.getElementById('form');
form.addEventListener('submit', function(event){
event.preventDefault();
const fromdate = document.getElementById('fromdate').value;
const todate = document.getElementById('todate').value;
if(Number(fromdate) >= Number(todate)) {
alert('Invalid Date. please check and try again!');
}else{
event.currentTarget.submit();
}
});
Worked as the only method to restore the default action.
$('#some_link').unbind();
This should work:
$('#myform').on('submit',function(e){
if($(".field").val()==''){
e.preventDefault();
}
});
$('#my_elementtt').click(function(event){
trigger('click');
});
I'm not sure you're what you mean: but here's a solution for a similar (and possibly the same) problem...
I often use preventDefault() to intercept items. However: it's not the only method of interception... often you may just want a "question" following which behaviour continues as before, or stops.
In a recent case I used the following solution:
$("#content").on('click', '#replace', (function(event){
return confirm('Are you sure you want to do that?')
}));
Basically, the "prevent default" is meant to intercept and do something else: the "confirm" is designed for use in ... well - confirming!