Capturing a button click as part of a field validation - javascript

I have an onblur='validate(this)' on a text field but I do not want the validate code to run when a cancel button is clicked.
function validate(oField) {
if (document.getElementById('Cancel').clicked != true) {
console.log("Cancel clicked");
}
}
<input id='reviewername'
name='reviewername'
type='text'
class='$class'
value='$reviewername'
tabindex=1
size=$size
onkeydown='setKeyCode(event)'
onblur='validate(this)'/>;
<input type='submit'
name='Button'
id='Cancel'
value='Cancel'>;
The document.getElementById('Cancel').clicked is always 'undefined'.
I have tried addListener(), probably incorrectly, as well as other newbie tricks with no success!
What I am trying to do is check whether the Cancel button is clicked while the text field has the focus. Immediately I click the button, the text field event 'onblur' runs. I want to check for the button click as the first part of the javascript validate() function.
Is what I am attempting even possible?
Please help before I lose the rest of my hair.

You can use àddListener() if you name it correctly as addEventListener().
Then, you can set some variable when the cancel button is clicked and use that variable in replacement to your document.getElementById(...).clicked.
cancel_clicked = false;
function validate(oField) {
if (cancel_clicked != true) {
console.log("Cancel not clicked");
} else {
console.log("Cancel clicked");
}
}
<input id='reviewername'
name='reviewername'
type='text'
class='$class'
value='$reviewername'
tabindex=1
size=$size
onkeydown='setKeyCode(event);'
onblur='validate(this);'/>
<input type='submit'
name='Button'
id='Cancel'
value='Cancel'
onclick='cancel_clicked = true;'/>

Browsers are removing direct event listener attachment to DOM elements, it's better to use javascript to add the event listeners, instead of the onlick or onblur attributes on DOM elements, this is what I've noticed lately.. So you are more safe with using addEventListener, also do watch out for your spelling too incases where you get undefined,or you are loading your script before your DOM tree.. As a thumb rule, load your javascript file last.

Related

Auto search after barcode/qrcode scanner update values into input? [duplicate]

I want to fire the JQuery change event when the input text is changed programmatically, for example like this:
$("input").change(function(){
console.log("Input text changed!");
});
$("input").val("A");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
But it doesn't work. How can I make this work?
change event only fires when the user types into the input and then loses focus.
You need to trigger the event manually using change() or trigger('change')
$("input").change(function() {
console.log("Input text changed!");
});
$("input").val("A").change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' />
The event handler .change() behaves like a form submission - basically when the value changes on submit the console will log. In order to behave on text input you would want to use input, like below:
$("input").on('input', function(){
console.log("Input text changed!");
});
$("input").val("A");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
What you need to do is trigger the change event after you've set the text. So you may create a function to do that so you won't have to repeat it every time you need to update the text, like this:
function changeTextProgrammatically(value) {
$("input").val( value );
$("input").trigger( 'change' ); // Triggers the change event
}
changeTextProgrammatically( "A" );
I've updated the fiddle,
You can use the DOMSubtreeModified event:
$('input').bind('DOMSubtreeModified',function(){...})
If you want to fire both user and code changes:
$('input').bind('input DOMSubtreeModified',function(){...})
This event is marked as deprecated and sometimes quite CPU time consuming, but it may be also very efficient when used carefully...
jquery change event only works when the user types into the input and then loses focus. So you can use the following workaround to do so:-
Let's say you have a button clicking on which results in change in value of input. (this could be anything else as well instead of a button)
var original_value = $('input').val();
$('button').click(function(){
var new_value = $('input').val();
if(original_value != new_value ){
//do something
}
//now set the original value to changed value (in case this is going to change again programatically)
original_value = new_value;
})

How can I fire a Javascript event when a text box is changed but not by the user?

I have a custom tag STRUTS in a JSP set as standard used to handle the calendar and I can't set any type of event here.
This tag render this HTML : <A onmouseover="return true" href="javascript:ShowCalendar('data')> (..img..) </A>**
When you select date on link, this change my text box with the date selected, I need fire my event in this moment.
My textbox struts tag is this <html:text property="data" styleClass="testo10" size="12" maxlength="10" tabindex="3"/>
I tried with onchange event, but this work only if user do the changes.
I need fire event whenever the textbox is changed whether the user is or not(changes from Javascript for example or from link, like in my case).
How can I do that?
This can be achieved with 'input' event.
<input type="text" class="txtTest" value="test" onchange="textChange();" oninput="this.onchange();"/>
Here I used jQuery to trigger 'input' event and setTimeout() to just mimic text change dynamically.
function textChange(){
alert('text change');
}
setTimeout(function(){
$('.txtTest').val('new text').trigger("input");
},2000);
JS Bin link here
Basically .trigger() method of jQuery help to trigger the event which you want to fire. In this case I'm firing 'input' event of textbox, which in return calling it's own onchange() method. Or simple you can directly trigger change event also.
Another Solution
For IE7 support
jQuery 1.x + textchange plugin help to achieve this.
I tried with IE7 Emulation.
<input type="text" id="txtTest" value="test"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://zurb.com/playground/uploads/upload/upload/5/jquery.textchange.min.js"></script>
<script type="text/javascript">
$('#txtTest').bind('textchange', function (event, previousText) {
alert(previousText);
});
setTimeout(function(){
$('#txtTest').val('new text').trigger('textchange','some data');
},3000)
</script>
Bind change event in javascript
document.getElementById('txtbox_id').addEventListener('change', function() {
alert("text changed"); //or do whatever u want here
});

How to stop element with first onclick event to be fired when enter key is pressed first time

I was fixing a bug in a jsp page in which even though a function is defined with onkeypress event to click a particular button (actually its an image of button with onclick property associated with it) when the page is opened first time and then enter key is pressed its throwing an error.
When I debugged the code then I find out that actually two calls are made simultaneously. i.e. the first button with onclick property is also clicked.
Here is just a sample code:
<html>
<head>
</head>
<body>
<div onkeypress =handleEnter()>
name <input type="text" src='Create.gif' >
</br>
<input type="image" src='Create.gif' onclick="alert('not done')">
<input type="image" src='Create.gif' onclick="alert('done')">
</div>
</body>
<script>
function handleEnter()
{
if(window.event.keyCode==13)
{
alert('nothing');
event.cancelBubble=true;
}
}
</script>
</html>
on pressing enter key both functions are getting called.
The following will probably work. By preventing the default action of the keypress it should stop the browser from triggering the standard "form submit" — which is what I think is happening.
function handleEnter(e)
{
e || (e = window.event); /// support for both ie and non-ie browsers
if(e.keyCode==13)
{
alert('nothing');
// old ie support
e.cancelBubble = true;
e.returnValue = false;
// non-ie
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
}
}
You have to bear in mind though that if you are preventing default for enter on the whole page, it will stop it working for textareas and other places where enter might be used. If this is a problem you could decide whether or not to prevent the default action depending on:
var elm = e.srcElement || e.target;
elm should contain the triggering element of the event. scrElement is for old IE and target is for non-IE browsers. For example, you could use this to shortcircuit your code before reaching the prevent default.
if ( elm.nodeName == 'textarea' ) return;
I don't have IE8 lying around to test this however, but considering the following link, it is likely to work:
http://support.microsoft.com/kb/298498
I know this is an old question, but I did not find any other questions/answers for this, and I was having this same issue with buttons.
But for some reason when I look at the "event" that is passed into javascript function, there is no keyCode passed in with it, so I can not distinguish which key was pressed. FYI "event" was only passing in isTrusted property (and nothing else), but that is another question for another time...
My solution was that I just added a button with onclick="return false;" and style="display:none;" in front of all the other elements so that the ENTER key affects this element and is essentially ignored, and is invisible. With onclick='return false;' the form will NOT be submitted. With onclick='return true;' the form WILL be submitted.
<button id='prevent-onclick-on-enter' style='display:none;' onclick='return false;'/>
<input type="image" src='Create.gif' onclick="alert('not done')">
<input type="image" src='Create.gif' onclick="alert('done')">
SECOND ANSWER
So this is maybe for a slightly different issue that only involves BUTTONS (not INPUTS), but this may be good to know for some people (like me) that did not know this...
When you have a button in a form, it defaults to type "submit" which means the first button in a form will have its onclick event triggered by the ENTER key. To prevent this from happening, simply assigm type="button" to the button, and enter key will no longer affect it.
as jsherk mentioned, any unintended onclick should have type="button" and will stop firing when enter is pressed

OnClick bypasses form submit

I have a form which is made like this:
<form id= 'lol' name = 'whyyyyy'>
<input name='dumbo'>
<input name='idiot'>
<input type='submit' value='I have no idea why its like this' onclick='document.lol.submit()'>
</form>
Now, I want to prevent the actual sending of the form, but so far all attempts failed.
My current code looks like this:
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
})
but the inline submit command bypasses as it seems the jQuery function.
Can someone shred light into it?
EDIT:
The form CANNOT be changed, I don't have permission to change.
the on click code should trigger the submit function, it some complex validation wall of code in it. So I have to cache the submit action that it triggers, but I can't do that at moment.
the submit function should be triggered on send but it does not get triggered.
Here is an example of the code in jfiddle. As you can see it gets past by jQuery...
http://jsfiddle.net/StCPp/4/
if you don't need a submit button, why don't you use a regular button instead
<input type="button" />
<input type='button' value='i have no idea why he done it like this' onclick='document.getElementById('lol').submit()'>
Just use a normal button instead of a submit.
If you want to bypass a submit button you can make the class of the button cancel.
<input type='submit' class='cancel' value='i have no idea why he done it like this' onclick='document.lol.submit()'>
In your add-on JavaScript, remove the inline onclick event and replace it with whatever you desire. Problem solved.
You could also completely remove his button and replace it with one of your choice.
Remove the document.lol.submit function. This way, you can do whatever you want.
// Magic line
delete document.lol.submit;
// Or
$('form[name="whyyyyy"] input[type=submit]').attr('onclick', '');
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
});
Ok so if I got this right you could remove the inline event handler onclick and add your custom handler (where you do the validation and all necessary steps):
$(document).ready(function() {
var $submit_button = $('input[type=submit]');
$submit_button.removeAttr('onclick');
$submit_button.click(function() {
//TODO: implement your custom handler
//execute validation etc.
});
});
Remove the onclick
$('input[type=submit]').attr('onclick','')
Then add the click event to function ready
$('input[type=submit]').on('click',function(){
//do your event
});
You aren't necessarily required to use jquery to implement this. You could use standard javascript.
$(document).ready(function(){
document.whyyyyy.submit = function(e){
alert(1);
return false;
};
});
This example works, but you might be hitting a jquery bug.

Javascript change event on input element fires on only losing focus

I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.
<input type="text" id="name" onchange="checkLength(this.value)" />
----onchange does not fire on changing contents of name, but only fires when name goes out of focus.
Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.
I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?
(function () {
var oldVal;
$('#name').on('change textInput input', function () {
var val = this.value;
if (val !== oldVal) {
oldVal = val;
checkLength(val);
}
});
}());
This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.
http://jsfiddle.net/katspaugh/xqeDj/
References:
textInput — a W3C DOM Level 3 event type. http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents
A user agent must dispatch this event when one or more characters have
been entered. These characters may originate from a variety of
sources, e.g., characters resulting from a key being pressed or
released on a keyboard device, from the processing of an input method
editor, or resulting from a voice command. Where a “paste” operation
generates a simple sequence of characters, i.e., a text passage
without any structure or style information, this event type should be
generated as well.
input — an HTML5 event type.
Fired at controls when the user changes the value
Firefox, Chrome, IE9 and other modern browsers support it.
This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.
It took me 30 minutes to find it, but this is working in June 2019.
<input type="text" id="myInput" oninput="myFunction()">
and if you want to add an event listener programmatically in js
inputElement.addEventListener("input", event => {})
As an extention to katspaugh's answer, here's a way to do it for multiple elements using a css class.
$('.myclass').each(function(){
$(this).attr('oldval',$(this).val());
});
$('.myclass').on('change keypress paste focus textInput input',function(){
var val = $(this).val();
if(val != $(this).attr('oldval') ){
$(this).attr('oldval',val);
checkLength($(this).val());
}
});
Do it the jQuery way:
<input type="text" id="name" name="name"/>
$('#name').keyup(function() {
alert('Content length has changed to: '+$(this).val().length);
});
You can use onkeyup
<input id="name" onkeyup="checkLength(this.value)" />
You would have to use a combination of onkeyup and onclick (or onmouseup) if you want to catch every possibility.
<input id="name" onkeyup="checkLength(this.value)" onmouseup="checkLength(this.value)" />
Here is another solution I develop for the same problem. However I use many input boxes so I keep old value as an user-defined attribute of the elements itself: "data-value". Using jQuery it is so easy to manage.
$(document).delegate('.filterBox', 'keyup', { self: this }, function (e) {
var self = e.data.self;
if (e.keyCode == 13) {
e.preventDefault();
$(this).attr('data-value', $(this).val());
self.filterBy(this, true)
}
else if (e.keyCode == 27) {
$(this).val('');
$(this).attr('data-value', '');
self.filterBy(this, true)
}
else {
if ($(this).attr('data-value') != $(this).val()) {
$(this).attr('data-value', $(this).val());
self.filterBy(this);
}
}
});
here is, I used 5-6 input boxes have class 'filterBox',
I make filterBy method run only if data-value is different than its own value.

Categories

Resources