Activating a function by clicking outside the box - javascript

Alright so I'm having a bit of trouble with getting a function to work. All I have to do is to make the function activate once i click out from a HTML box.
<hmtl>
<body>
<center>
<script>
function calculateTax() {
var a = document.getElementById('boxone').value;
var b = document.getElementById('boxtwo').value;
var c = a/100*18;
b = c + a;
document.getElementById('boxone').value = a;
document.getElementById('boxtwo').value = b;
}
</script>
<input type="text" id="boxone" value="">
<input type="text" id="boxtwo" value=""><br>
<input type="hidden" onclick="calculateTax()">
</center>
</body>
</html>
Can anyone tell me what I should put instead of onclick and why my formula does not work.Thanks

I made a fiddle for you: http://jsfiddle.net/Dmc9Z/1/
Basically, you can add an onclick event to the body. I also added a button there which can submit it too, depending on what you want.
The reason your code wasn't working was because the input was being processed as a string. When you were 'adding', you were just concatenating values to the string. I added parseInt to fix that for you. I also removed some redundant code.

You want the onBlur event listener.
<input type="text" id="boxone" value="" onBlur="calculateTax()">
onBlur is the event called when an element loses focus - when you click away from an input, for example.
Adding an onClick to the body will work, but isn't the best approach because it will make the function run every time anyone clicks anywhere on your page - not just when they click away from the input.

I would suggest to keep your javascript and html separated. You can add an event listener to the body and make you it only fires when it's not an input field, for example like this:
document.getElementsByTagName("body")[0].addEventListener("click", function(target) {
if (target.nodeName === "INPUT") return false; // if our focus is an input field we don't want to fire the event
calculateTax();
}, false);

Related

Having issues with setting an even listener to prevent default in input field with javascript

I am trying to make a simple password generator and i want the password generation to happen on the click of a button and that part works when i test it in the console. And now to implement it on sort of a real web page, the password generated to the input field doesn't stay!!, i know to use the .preventDefault() method but i don't know hot to apply it in this case using an event listener for when the value of the input field changes.
I couldn't add the html because it looks strange when i add it, but it looks like this:
Password: <input type="text" name="password" id="password" value="">
<button id="button" onclick="makePassword()">Get password</button>
here is my code below:
var capitalAlphabets=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var smallAlphabets=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var numbers=[1,2,3,4,5,6,7,8,9,0,];
function randomCapital(){
var capital=capitalAlphabets[Math.floor(Math.random()*capitalAlphabets.length)];
return capital;
}
function randomSmall(){
var small=smallAlphabets[Math.floor(Math.random()*smallAlphabets.length)];
return small;
}
function randomNumber(){
var number=numbers[Math.floor(Math.random()*numbers.length)];
return number;
}
var password="";
function makePassword(){
password="";
for(var i=0; i<=12; i++){
password=password+randomCapital()+randomSmall()+randomNumber();
// console.log(i + password);
}
console.log(password);
input=document.getElementById("password");
input.value=password;
}
//having issues with setting an even listener to prevent default in input field
You probably have your button inside a form so it is interpreted as a submit button (<button type="submit">). Pressing enter inside an input field inside a form will click on the first submit button inside the form. Just explicity make the button type a button so clicking it will not submit the form and refresh the page:
<button type="button" onclick="makePassword()">Get password</button>
If you want to add an event listener, use document.getElementById to get the DOM element to add a keypress event listener to and if the event's keycode is 13 (enter), prevent the default action.
document.getElementById("password").addEventListener("keypress", function(e){
if(e.keyCode==13){
e.preventDefault();
}
});
Overall, using onclick="" for a button is bad practice.
You should add an eventListener for your button instead:
var button = document.getElementById("button");
button.addEventListener("click", function(event) {
event.preventDefault();
makePassword();
});
That should work much better, let me know if you have any questions.
http://jsfiddle.net/316xjkqu/2/

Javascript - Can I run my event handler AFTER the default handler for the "onkeypress" event?

I have an input text and I want to run my function after the default event handler
<input type="text" onkeypress="myfunction()"></input>
the function
function myfunction(){alert($("input")[0].value)}
because myfunction() is using the input value and this property will be changed after the default handler runs and change it.
Example: if the text field has value "1234" , and I pressed the key "5", the function will alert "1234" not "12345"
So, I want the default function runs first to change the value property , then I can use it in myfunction()
can I do something like this ?!
onkeypress="default();myfunction()"
I did a work around by putting myfunction() in the onkeyup event, but I don't want that.
Thanks, and please consider I'm very newbie.
TRIVIAL SOLUTION:
You should use oninput instead of onkeypress. Like so:
<input type="text" oninput="myfunction(event)" />
The keypress event is emitted when a key gets pressed, i.e., before the DOM is modified with the pressed key's value. This is why you never got the value of the last key pressed.
The input event is emitted when data is entered into the input element. So we can access the data by reading the value of the element.
USING EVENT-BINDING:
HTML
<input id="input_field" type="text" />
jQuery
$(document).ready(function() {
$("#input_field").on("input", function() {
console.log($(this).val());
});
});
Pure JS
var input_field = document.getElementById("input_field");
input_field.addEventListener("input", function(event) {
console.log(event.target.value);
});
NOTE: Add this in a script tag after the HTML or use window.onload to simulate the behaviour of $(document).ready.
See this SO answer for more information about how event-binding works.

Create onchange event with javascript in Firefox

I've been working on trying to trigger an onchange listener with java script in Mozilla Firefox. I've found a lot on Stack Overflow posted about this, but nothing seems to be working for my unique case.
I've created this HTML with a onchange listener from an onchange event using this helpful post (JavaScript OnChange Listener position in HTML markup). Here's my code:
<HTML>
<head>
<script type="text/javascript">
window.onload= function () {
if(window.addEventListener) {
document.getElementsByClassName('search-box')[0].addEventListener('change', loadXMLDoc, false);
} else if (window.attachEvent){
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);
}
function loadXMLDoc(){
alert('It worked');
}
}
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
}
</script>
</head>
<BODY>
<input type="text" class="search-box" placeholder="Player Search">
<br \>
<button type="button" onclick="addTextCallListener()">Click Me!</button>
</BODY>
</HTML>
I also saved it as this jsfiddle (for some reason I had to keep it all together for it to work, I couldn't break it up into js and html).
https://jsfiddle.net/josephfedor42/crogL0zd/1/
If you play with this jsfiddle you can see that entering text and pressing enter will trigger the listener and the pop up with the message “It worked” will appear.
But if the button “Click Me!” is pressed it only changes the value of the text box, and the onchange listener is not called.
I realize I could easily add an onchange event to this button. But I want to to trigger the listener by programatically/ superficially using javascript in my addTextCallListener() function.
I've tried the simple stuff, like calling
searchBox.onchange();
searchBox.focus();
searchBox.click();
And a combination of these to add and remove the focus. But it doesn't seem to work. I've found quite a few posts on triggering an onchange event, but nothing that works in Firefox.
Any help would be appreciated.
Thanks for that link of a possible duplicated question. I had checked out that link before.
But I gave it a try again. I saved the jsfiddle from them both and neither one work.
My implementation of Dorian's answer
https://jsfiddle.net/josephfedor42/zaakd3dj/
My implementation of Alsciende's answer
https://jsfiddle.net/josephfedor42/xhs6L6u2/
emphasize mine
According to the mdn page about the change event,
The change event is fired for <input>, <select>, and <textarea>
elements when a change to the element's value is committed by the
user.
and to whatwg specs :
When the input and change events apply (which is the case for all
input controls other than buttons and those with the type attribute in
the Hidden state), the events are fired to indicate that the user has
interacted with the control.
Therefore, setting the value of an input is not an action "committed by the user" nor a sign that "the user has interacted with the control", since it was made by the code.
So, even if the specifications for this event are kind of unclear, the event should not fire when you change its value by code.
Something like this should work:
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
//fire the event
if (document.createEvent) {
searchBox.dispatchEvent('change');
} else {
searchBox.fireEvent("onchange");
}
}
Here is the code I needed to add to my function addTextCallListener:
var evObj = document.createEvent('HTMLEvents');
evObj.initEvent( 'change', true, true );
searchBox.dispatchEvent(evObj);
I updated the jsfiddle. The working code is here https://jsfiddle.net/josephfedor42/crogL0zd/7/
Replace onchange with change in this part:
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);

how to show alert in html page when text change in input field

I have a text box, and I wanted an alert when the text changes but now, the problem is, when I write 11 it show two times alert.
function onChangeText(){
alert("Please show update buttons");
}
You can try this : My Fiddle
<input type="text" onchange="alert('Hello');">​
Try onkey up instead of onchange
<input type="text" onkeyup="onChangeText()" />
You can call your javascript onblur instead of onchange like
<input type="text" onblur="onChangeText();">​
Try this:
<input type="text" onblur="if(this.value != '') onChangeText();">​
you can try focusout.
Check out this fiddle
Another way would be create global timeout variable, bind listener to the input event. The callback function would reset timeout and check if previous event occured specified time ago (500ms in example).
As you might have noticed, examples with onchange execute after clicking on the other element. This is default behaviour for change event. Input behaves different.
Example: http://jsfiddle.net/Klaster_1/3byVb/
var timeout;
$("input").on("input", function(event) {
var value = event.target.value;
clearTimeout(timeout);
timeout=setTimeout(function(){
if(value.length){
alert(value);
}
},500);
});​

Why is my onchange function called twice when using .focus()?

TLDR
Check this example in chrome.
Type someting and press tab. see one new box appear
type something and press enter. see two new boxes appear, where one is expected.
Intro
I noticed that when using enter rather then tab to change fields, my onchange function on an input field was firing twice. This page was rather large, and still in development (read: numerous other bugs), so I've made a minimal example that shows this behaviour, and in this case it even does it on 'tab'. This is only a problem in Chrome as far as I can tell.
What it should do
I want to make a new input after something is entered into the input-field. This field should get focus.
Example:
javascript - needing jquery
function myOnChange(context,curNum){
alert('onchange start');
nextNum = curNum+1;
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum).focus();
return false;
}
HTML-part
<div>
<input type="text" onchange="return myOnChange(this,1);" id="prefix_1">
</div>
the complete code is on pastebin. you need to add your path to jquery in the script
A working example is here on jFiddle
The onchange gets called twice: The myOnChange function is called, makes the new input, calls the focus(), the myOnChange gets called again, makes a new input, the 'inner' myOnChange exits and then the 'outer' myOnchange exits.
I'm assuming this is because the focus change fires the onchange()?. I know there is some difference in behaviour between browsers in this.
I would like to stop the .focus() (which seems to be the problem) to NOT call the onchange(), so myOnChange() doesn't get called twice. Anybody know how?
There's a way easier and more reasonable solution. As you expect onchange fire when the input value changes, you can simply explicitly check, if it was actually changed.
function onChangeHandler(e){
if(this.value==this.oldvalue)return; //not changed really
this.oldvalue=this.value;
// .... your stuff
}
A quick fix (untested) should be to defer the call to focus() via
setTimeout(function() { ... }, 0);
until after the event handler has terminated.
However, it is possible to make it work without such a hack; jQuery-free example code:
<head>
<style>
input { display: block; }
</style>
<body>
<div></div>
<script>
var div = document.getElementsByTagName('div')[0];
var field = document.createElement('input');
field.type = 'text';
field.onchange = function() {
// only add a new field on change of last field
if(this.num === div.getElementsByTagName('input').length)
div.appendChild(createField(this.num + 1));
this.nextSibling.focus();
};
function createField(num) {
var clone = field.cloneNode(false);
clone.num = num;
clone.onchange = field.onchange;
return clone;
}
div.appendChild(createField(1));
</script>
I can confirm myOnChange gets called twice on Chrome. But the context argument is the initial input field on both calls.
If you remove the alert call it only fires once. If you are using the alert for testing only then try using console instead (although you need to remove it for testing in IE).
EDIT: It seems that the change event fires twice on the enter key. The following adds a condition to check for the existence of the new field.
function myOnChange(context, curNum) {
nextNum = curNum+1;
if ($('#prefix_'+nextNum).length) return false;// added to avoid duplication
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum)[0].focus();
return false;
}
Update:
The $('#prefix_'+nextNum).focus(); does not get called because focus is a method of the dom object, not jQuery. Fixed it with $('#prefix_'+nextNum)[0].focus();.
The problem is indeed that because of the focus(), the onchange is called again. I don't know if this is a good sollution, but this adding this to the function is a quick sollution:
context.onchange = "";
(The onchange is called again, but is now empty. This is also good because this function should never be called twice. There will be some interface changes in the final product that help with problems that would arise from this (mistakes and all), but in the end this is something I probably would have done anyway).
sollution here: http://jsfiddle.net/k4WKH/2/
As #johnhunter says, the focus does not work in the example, but it does in my complete code. I haven't looked into what's going on there, but that seems to be a separate problem.
maybe this some help to anybody, for any reason, in chrome when you attach an event onchage to a input text, when you press the enterkey, the function in the event, do it twice, i solve this problem chaged the event for onkeypress and evaluate the codes, if i have an enter then do the function, cause i only wait for an enterkey user's, that not works for tab key.
input_txt.onkeypress=function(evt){
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if(charCode === 13) evaluate( n_rows );
};
Try this example:
var curNum = 1;
function myOnChange( context )
{
curNum++;
$('<input type="text" onchange="return myOnChange( this )" id="prefix_'+ curNum +'" >').insertAfter( context );
$('#prefix_'+ curNum ).focus();
return false;
}
jsFiddle.

Categories