How to stop event in javascript? [duplicate] - javascript

This question already has answers here:
How to stop event propagation with inline onclick attribute?
(15 answers)
Closed 9 years ago.
consider following,
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txt1" />
<input type="button" id="btn1" value="Submit"/>
</div>
</form>
<script>
$("#txt1").live("blur", function () {
console.log('blur');
return false;
});
$("#btn1").live("click", function () {
console.log('click');
return false;
});
</script>
</body>
Above code will log blur event and click event on trigger of respective events.
If click or change something in text box and then click on button btn1 blur and click event will happen respectively.What i want is if blur event is happening because of btn1 then click event should not happen,it should log only blur event,I want to stop click event from happening.
How to do this? Can anyone help?

try this
<form id="form1" runat="server">
<div>
<input type="text" id="txt1" />
<input type="button" id="btn1" value="Submit"/>
</div>
</form>
javascript code
$("#txt1").on("blur", function (event) {
event.preventDefault();
alert('blur');
return false;
});
$("#btn1").on("click", function (event) {
event.preventDefault();
alert('click');
return false;
});
also test it here and remember live keyword is deprectaed from jquery 1.9 use on instead of live in jquery 1.9 or greater.

Here is one way to solve it by adding a timeout.
var inFocus = false;
$("#txt1").focus(function () {
inFocus = true;
$("#log").prepend("<p>focus</p>");
});
$("#txt1").blur(function () {
setTimeout(function(){inFocus = false;},200);
$("#log").prepend("<p>blur</p>");
});
$("#btn1").click(function () {
if (!inFocus) {
$("#log").prepend("<p>click</p>");
}
});
In the fiddle example, I put the log out to the window.

You cannot "stop" an other/foreign event like so. Event.preventDefault() and/or Event.stopPropagation() (which both will get triggered when returning false from within a jQuery event handler), will allow you to stop and prevent the exact same event from further processing on parent nodes.
In your instance, you need your own logic. Use some variables and set them properly and check the value where necessary. For instance, on click you set FOOBAR = true and in blur you check if( FOOBAR ) and act on that.

You need to destroy one event see the demo
Hope this helps you.
jsfiddle.net/rkumar670/5a86V

Related

Prevent onclick from firing

I was working around with form submissions in html. Please take a look at below code
<form id="form1">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script>
$("#btn1").click(function (event) {
alert("event triggered");
if(some_condition == true){
// stop firing onclick method but it always submits the form
event.stopImmediatePropogation(); // not working
event.preventDefault(); // not working
event.stopPropogation(); // not working it's for bubbled events
}
});
function clicked(){ alert("clicked me"); }
</script>
I want to stop clicked() function from firing which is attached to inline onclick attribute. I would like to run my jquery click function and if something goes wrong, I dont want to trigger onclick but it always runs clicked() function. Could any one help me. Any help is greatly appreciated.
The order in which an onxyz handler is called relative to dynamically-attached handlers varies from browser to browser, so your handler may well not run before the original does.
To deal with that, you save and remove the onclick handler:
var btn = $("#btn1");
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
Then, in your handler, if you want that function to be called, you call it:
clickhandler.call(this, event);
Example:
// Get the button
var btn = $("#btn1");
// Save and remove the onclick handler
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
// Hook up your handler
$("#btn1").click(function(event) {
alert("event triggered");
if (!confirm("Allow it?")) {
// Disallowed, don't call it
alert("stopped it");
} else {
// Allowed, call it
clickHandler.call(this, event);
}
});
// The onclick handler
function clicked() {
alert("clicked me");
}
<form id="form1" onsubmit="return false">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Try event.stopPropagation()
api docs
if condition is true then remove the 'onclick' attribute
if (some_condition == true) {
$("#btn1").removeAttr('onclick').click(function(event) {
alert("event triggered");
//do something
});
}
function clicked() {
alert("clicked me");
}
I am sharing a quick workaround without knowing why you cannot add logic to stop adding "onclick="clicked();" code which you are saying getting automatically added.
I recommend you hide button with id as "btn1". Add style display:none. You donot need on ready function for this but simply add style attribute to the button btn1 or if that is also not possible directly then use jQuery to do that post document ready.
Read :
How to change css display none or block property using Jquery?
Then add a new button to the form using jQuery with id as "btn2" and add register the btn2 click event as well. DO this after form load.
<form id="form1">
<div id="newbut">
<button id="btn1" onclick="clicked();">Submit</button>
</div>
</form>
jQuery("#newbut").html('<button id="btn2">Submit</button>');
$(document).on('click', '#btn2', function(){
// Your Code
});
Refer below url to how to register click event for new button:
Adding click event for a button created dynamically using jQuery
jquery - Click event not working for dynamically created button
Can't you do the condition check and the clicked() logic in one function? i.e
<script>
function clicked() {
if(some_condition == true){
return;
}
alert("clicked me");
}
</script>

jquery focusout == submit

How could I tell if the focusout event occured due to an enter press = form submit or just because of clicking away? The event data which goes to the console is of type "focusout" and has no relevant information
$(".clientrow[clientid="+clientid+"] td."+fieldname+"").bind("focusout", function(event){
console.log(event);
setTimeout(function() {
if (!event.delegateTarget.contains(document.activeElement)) {
$(".clientrow[clientid="+clientid+"] td."+fieldname+"").html(
$(".clientrow[clientid="+clientid+"] td."+fieldname+" input[type=text]").val()
);
}
}, 0);
});
Edit: As Oriol pointed in the comments, this will not work in Mozilla. If you are looking only for webkit browsers, you can try this approach. But as a generic solution, try binding an event on submit button and consecutively set a flag which identifies the element. Based on the element, you can detect whether it's an actual blur or not.
You can look out for relatedTarget property in the event.
Demo: http://jsfiddle.net/GCu2D/782/
JS:
$(document).ready(function () {
$("input").on("blur", function (e) {
console.log(e);
if (e.relatedTarget) {
console.log("Because of button");
} else {
console.log("Just a blur")
}
});
});
HTML:
<form>
<input type="text" />
<button type="button">Submit</button>
</form>
You'll have to replace the focusout with blur event. When the blur is due to a click on a button, the relatedTarget property will have button as value but in other cases it will be null.

Add an onchange event listener to an html input field

I would like to add an onchange event to those input fields without jquery:
<input type="text" id="cbid.wizard.1._latitude">
<input type="text" id="cbid.wizard.1._longitude">
I can already call the object with
<script type="text/javascript">
alert(document.getElementById('cbid.wizard.1._latitude').id);
</script>
In the end, I want to add this behaviour, that if you enter a pair of coordinates into the first input, I will spread the pair over the two input fields?
How do I add an onchange event with javascript?
Ummm, attach an event handler for the 'change' event?
pure JS
document.getElementById('element_id').onchange = function() {
// your logic
};
// or
document.getElementById('element_id').addEventListener(
'change',
callbackFunction,
false
);
jQuery
$('#element_id').change(function() {
// your logic
});
Note
Note, that change event on the text field will be fired after the blur event. It's possible that your looking for keypress event's or something like that.
document.getElementById('cbid.wizard.1._latitude').onchange = function(){
//do something
}
GlobalEventHandlers.onchange docs
or
document.getElementById('cbid.wizard.1._latitude').addEventListener("change", function(){
//do something
});
EventTarget.addEventListener docs
use addEventListener in your window.onload
window.onload=function(){
document.getElementById('cbid.wizard.1._latitude').addEventListener("change", function(){
//do something
});
};
addEventListener
Please try with the below code snippet.
<body>
<input type="text" id="cbid.wizard.1._latitude">
<input type="text" id="cbid.wizard.1._longitude">
<script type="text/javascript">
var txt1 = document.getElementById('cbid.wizard.1._latitude');
txt1.addEventListener('change', function () { alert('a'); }, false);
</script>
</body>

Getting How a Form Was Submitted on submit event

I have a form that has a couple of buttons on it. Two of the buttons use ajax to submit the form and clear it so that the user can add multiple records before moving on. The last button is for when the user is done with the page and wants to move onto the next page. Is it possible in jQuery's .submit() method to tell how the form was submitted (hitting enter, or get the object of the button clicked)?
Not sure if it is best practices, but I found that if I create a submit event handler and then after that create the handlers for the other buttons it seems to work okay, at least in Chrome.
Here's an example
$(function(){
$('form#frmField').submit(function(evt){
alert('Form Submitted');
return false;
});
$('input#btnReset').click(function(){
alert('Form Reset');
return false;
});
});
You can define onclick event handlers for your buttons which would save the state into some global-scope variable. Then you would check the state of the variable at onsubmit handler.
http://jsfiddle.net/archatas/6dsFc/
you can try this way:
HTML:
<form id="myform">
<input type="text" id="text1" name="text1" /><br />
<input type="button" class="button-submit" id="b1" name="b1" value="send 1" /><br />
<input type="button" class="button-submit" id="b2" name="b2" value="send 2" /><br />
<button class="button-submit" id="b3">send 3</button>
</form>
<br />
<div id="data"></div>
JS:
$('#myform').bind('submit', function(event, from) {
if(from)
$('#data').append("from :" + $(from).attr('id') + '<br />');
return false;
});
$('#myform').keypress(function(event) {
if (event.which == '13') {
event.preventDefault(); //preventDefault doesn't stop further propagation of the event through the DOM. event.stopPropagation should be used for that.
event.stopPropagation();
$(this).trigger('submit', [this]);
return false;
}
});
$('.button-submit').bind('click', function(event) {
event.stopPropagation();
$('#myform').trigger('submit', [this]);
return false;
});
example
event.preventDefault
jQuery events pass an event object through their calls. You can use this event object to determine how the event was called.
Specifically, if you pass it as a parameter e in the function, you can check e.type, which should be equal to click, or e.which, which if it was submitted with an enter, would be 13.
You can use target to find out which DOM element initiated the submission with e.target.
So,
jQuery('#foo').click(function(e){
var initiator = $(e.target); //jQuery object for the DOM element that initiated the submit
if(e.type==="click")
{
//is a click
}
else if(e.which==="13")
{
//is an 'enter' triggered submission
}
});
});

properly disabling the submit button

this is the code that I use to disable the button
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
and this is my submit button
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here?
If it's a real form, ie not javascript event handled, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
$(yourButton).attr("disabled", "true");
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
That should stop the button acting like a button.
Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
$('#btnSubmit').unbind('click').click( function() { return false; } );
You'd have to add the click handler's again when (if) you re-enable the button.
You need to process Back/Prev button into browser.
Example bellow
1) Create form.js:
(function($) {
$.enhanceFormsBehaviour = function() {
$('form').enhanceBehaviour();
}
$.fn.enhanceBehaviour = function() {
return this.each(function() {
var submits = $(this).find(':submit');
submits.click(function() {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = this.name;
hidden.value = this.value;
this.parentNode.insertBefore(hidden, this)
});
$(this).submit(function() {
submits.attr("disabled", "disabled");
});
$(window).unload(function() {
submits.removeAttr("disabled");
})
});
}
})(jQuery);
2) Add to your HTML:
<script type="text/javascript">
$(document).ready(function(){
$('#contact_frm ).enhanceBehaviour();
});
</script>
<form id="contact_frm" method="post" action="/contact">
<input type="submit" value="Send" name="doSend" />
</form>
Done :)

Categories

Resources