I’m trying to make something where you can input numbers into an input (or would a contenteditable div be better?) and it does some calculations to them and sets the content of another div as the answer. How can I make it so that the other div will update whenever the number changes? I would prefer to make it so that there isn’t a submit button so the number instantly changes as you type it. I could probably achieve this by updating it every time there is a keystroke but the problem is storing the input data without pressing a submit button
First, please take some time to format your questions in the future. This is a difficult read.
Second please try and include all the information to show how far you have gotten.
Also I wasn't really clear what you are trying to do.
What you are looking for is called two way data binding, there are many different options for it, but it doesn't mean that's what you need. It seems like the following would be a good solution for you.
function doSomeCalculationsAndDisplay(event){
const elem = document.getElementById('input');
console.log(elem.value);
document.getElementById('result').innerText = 'Double value: ' + parseFloat(elem.value) * 2;
}
<input id="input" type="number" onKeyUp="doSomeCalculationsAndDisplay()" onChange="doSomeCalculationsAndDisplay()">
<div id="result"></div>
I always seem to figure it out on my own as soon as I make a post about it. It's not very complicated, the problem I had is that I was trying to get the innerHTML of an input which isn't possible, I needed to get its value instead.
To accomplish this all you need to do is make an input, div, and function that sets the div as the input document.getElementById('test1').innerHTML = document.getElementById('input1').value; and call this function onkeyup in the input.
Related
I'm making a game and I've a html text box, <form> <input> </form> where the users will type in a number and submit it using a html button <button>. How do I get the number using JavaScript so I can use it in my game.js so I'll know how many lives the user want when the submit button is pressed?
I'm not quite sure if this is the correct approach but I was thinking getting the id of the <input> tag and then for the JavaScript part I would use .getElementById of some sort? However, I'm not sure how to incorporate the submit button so that only when it's pressed, I will receive what the user inputted.
Or is there another better way to do this? And if possible, can you provide an example of the codes for doing this?
Let me know if any clarification is needed, thanks!
There are multiple ways to do what you are asking for, one way to do it is as cristian has shown in the comment(using jquery).
In this jsfiddle page I've shown a sample way to do it just using javascript.
The code used in the page is as shown below:
document.getElementById("submit").onclick = function(){
var a = document.getElementById("input").value;
alert("The entered value is: "+a);
}
I am using the same input textbox to collect multiple values.
After collecting the first input, I will clear the field by calling
document.getElementById("textbox").value= "";
On the surface, above snippet appears to clear the textbox.
But when I blur the textbox by clicking elsewhere, the old value reappears.
MORE CODES >>>
My HTML >>
<input id="textbox" placeholder="Start">
Javascript >>
After getting the first input, I like to reset the input value >>>
document.getElementById("textbox").value= "";
document.getElementById("textbox").setAttribute("placeholder","End");
This is how I do my data collection >>>
The same textbox is first used to collect a Google "place", and then subsequently to collect some user entered comment. In addition to collecting the data, someFunction() also try to clear the textbox by calling .value= ""
google.maps.event.addListener(textbox, "place_changed", function() {
someFunction();
});
Here is something i found googling fast for an answer; i think you can play around indeed with onFocus() a bit:
<input type="text" value="Click here to clear text" onfocus="if(!this._haschanged){this.value=''};this._haschanged=true;"/>
It may require a bit of usage of onBlur as well.
Also some other pointer, to get you going with jQuery if you want.
Looks like your input's value is stored in separate variable to be used for some other actions. So you should maybe check your code and clear thar variable.
I have practically implemented and used this solution whch is already suggested by my friend above:
document.getElementById("textbox").setAttribute("placeholder","End");
So, this works for me pretty well.(context:"placeholder" attribute used)
ICDT
..tc:)
I'm trying to run a script on an input text box that populates a div. The snippet is like so:
<input type="text" id="control" value="" />
<div id="displaydiv"></div>
<script>
document.getElementById("control").onkeydown = function() {
document.getElementById("displaydiv").innerHTML = this.value;
}
</script>
The problem here is that there is a lag of one character, i.e. if I type 'a', nothing shows up. When I type 'b', the previous 'a' shows up and so on. I tried replacing the onkeydown with onkeyup, and there is still a bit of a lag. How do I get the div to match the input text box in real time, without refreshing the page and/or losing focus on the input box?
Thanks for looking.
That is because onkeydown triggers before the key has added its value to the input. Use onkeyup instead. It will work the way you are after.
Edit: Not sure if I missed the speed thing, if you edited your question, but the lag you are seeing is unavoidable. It is as close to "real-time" as you are going to get. It's really not even that bad, less than half a second when I check it in a fiddle
Edit2: Just to satisfy my curiosity, I checked the performance against KnockoutJS's databinding, with the one input updating a div text via knockout, and another div via your script. The performance is identical. I was actually a bit surprised knockout didn't introduce any noticable overhead. Here is the fiddle
iv got a really simple javascript question. Ill be using query for parts of it here but there are akin ways of doing it via javascript. basically, I'm writing a little script that makes it so when you click a text box with a value in it, it will take out the value so your can type (ex for most username boxes they have a little note in there). there are probably much better ways of doing this (i can already think of some) so feel free to suggest them as well. anyways I got that part running easily, the problem is that whenever a user clicks again all the data is removed, so if they just want to adjust something they can't. to solve this (ill show code in sec) i put a check variable and an if. this is what it looks like. (it doesn't work, btw)
var unumber = 0;
var pnumber = 0;
if(unumber<1){
$('#username').click(function(){
unumber = 1;
$('#username').val('');
});
};
if(pnumber<1){
$('#password').click(function(){
$('#password').val('');
pnumber = 1;
});
};
what I'm assuming happens is that every time some one clicks the variables are reset, and this leads to a more general question if this is this case, why would the whole script, not just the event handler, run? Im new to javascript so forgive me if this is a stupid question. Anyways, this is a really simple script and there are better and more efficient ways to do it, but how can it be done this way?
Your check for number less than 1, should be within the click handler
var unumber = 0;
var pnumber = 0;
$('#username').click(function(){
if(unumber<1){
unumber = 1;
$('#username').val('');
}
});
$('#password').click(function(){
if(pnumber<1){
pnumber = 1;
$('#password').val('');
}
});
Note that this is not very robust, it doesn't handle tabbing into the fields. To fix that, handle the focus event.
Another problem is that you don't get the message back if you don't type anything and leave the field. A better approach is to compare against the initial value when the field receives focus. If there's nothing in there when you leave the field, restore to the original value.
Here's a jQuery plugin for creating these placeholders: https://github.com/mathiasbynens/Placeholder-jQuery-Plugin
Also, newer browsers support a placeholder attribute that does exactly that http://www.paciellogroup.com/blog/2011/02/html5-accessibility-chops-the-placeholder-attribute/
I'd say the best way of doing this is to have a clear button inside the text input. See here for an example : How do I put a clear button inside my HTML text input box like the iPhone does?
No need for the messy number checking, use data on the element in question
This should work for you.
$('#username,#password').focus(function(){
if(!$(this).data('seen')) {
$(this).data('seen',true);
$(this).val('');
}
});
http://jsfiddle.net/DeZ7D/
You could store the placeholder and replace back on blur if the user hasn't entered anything.
more detailed implementation here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
I have two inputs that together form a single semantic unit (think an hours and minutes input together forming a time input). If both inputs lose focus I want to call some Javascript function, but if the user merely jumps between those two, I don't want to trigger anything.
I've tried wrapping these two inputs in a div and adding an onBlur to the div, but it never triggers.
Next I tried adding onBlurs to both inputs and having them check the other's :focus attribute through jQuery, but it seems that when the onBlur triggers the next element hasn't received focus yet.
Any suggestions on how to achieve this?
EDIT: Someone questioned the purpose of this. I'd like to update a few other fields based on the values contained by both these inputs, but ideally I don't want to update the other fields if the user is still in the process of updating the second input (for instance if the user tabs from first to second input).
I made a working example here:
https://jsfiddle.net/bs38V/5/
It uses this:
$('#t1, #t2').blur(function(){
setTimeout(function(){
if(!$('#t1, #t2').is(':focus')){
alert('all good');
}
},10);
});
var focus = 0;
$(inputs).focus(function() { focus++ });
$(inputs).blur(function() {
focus--;
setTimeout(function() {
if (!focus) {
// both lost focus
}
}, 50);
});
An alternative approach is to check the relatedTarget of the blur event. As stated in the MDN documentation this will be the element which is receiving the focus (if there is one). You can handle the blur event and check if the focus has now been put in your other input. I used a data- attribute to identify them, but you could equally well use the id or some other information if it fits your situation better.
My code is from an angular project I've worked on, but the principle should translate to vanilla JS/other frameworks.
<input id="t1" data-customProperty="true" (blur)="onBlur($event)">
<input id="t2" data-customProperty="true" (blur)="onBlur($event)">
onBlur(e: FocusEvent){
const semanticUnitStillHasFocus = (val.relatedTarget as any)?.dataset?.customProperty === "true";
// Do whatever you like with this knowledge
}
What is the purpose of this behavior ?
The blur event triggers when a field looses focus, and only one field can gain focus at a time.
What you could do, in case of validation for instance, is to apply the same function on blur for both the fields and check the values of the fields altogether.
Without a context, it is difficult to help you more.
d.