Javascript - Display input inside div - javascript

So this is probably an easy one, but I'm just not doing it right. My goal is to send the user input from this textbox:
<input type='text' placeholder='Form Name...' id='formNameInput' required>
Into this Div:
<div id="code_output"></div>
I'm trying to make it appear in real time, and so far I used this to try and do so, but it doesn't work:
document.getElementById("code_output").innerHTML += document.getElementById("formNameInput").value;
Why doesn't it show? Does my code need something to trigger the Javascript?

You're close, but the issue is that you're not using an event handler. The script is executing your code once, as soon as possible (before you have the chance to enter anything into the text input). So, you have to add some sort of event listener so that the copying happens at the appropriate time. Something like below:
document.getElementById('formNameInput').addEventListener('keyup', copyToDiv);
function copyToDiv() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
<input type='text' placeholder='Form Name...' id='formNameInput' required>
<div id="code_output"></div>

You need to do that whenever the value of formNameInput changes. For that you need an event.
Your code should look like:
document.getElementById("formNameInput").addEventListener('input', function () {
document.getElementById("code_output").innerHTML += this.value;
});

function change() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
document.getElementById('formNameInput').onkeyup = change
maybe this is what you are trying?

You need to attach an event listener to your input that executes a function any time an input event occurs on the field:
formNameInput.addEventListener('input', function(e) {
code_output.textContent = e.target.value
})
<input type="text" placeholder="Form Name..." id="formNameInput" required />
<div id="code_output"></div>
Please note that the above code takes advantage of the fact that browsers automatically create a global variable for each element with a unique id attribute value, and this variable has the same name as the value of the id.
If the concept of events is new to you, this might be a good place to get started:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Related

Javascript "input" event value is undefined

I have an Electron app that needs to monitor an input text field on a form. The HTML looks like this:
<input type="text" class="cloneProjectName" id="outputProjectName" value="" >
I add an event listener for the element and console log what I think should be the typed data from the input:
projectNameControl.addEventListener("input", function (event) {
console.log(event.value)
})
All I see in the console is "undefined."
I would appreciate any input, I have searched and searched without finding an answer.
Sid
It's not the value of the event that you want (events don't have a value). It's the value of the element that triggered the event that you want and that element can be referenced with this or event.target.
Also, make sure that your JavaScript projectNameControl variable correctly references the input.
let projectNameControl = document.getElementById("outputProjectName");
projectNameControl.addEventListener("input", function (event) {
console.log(this.value, event.target.value);
})
<input type="text" class="cloneProjectName" id="outputProjectName" value="" >

how to copy a text of span

I copy need the dynamic text of a spam that is generated by a slider that the user sets. It must be copied to a value of an input.
I tried that, and didnt work:
<h4>Valor do consórcio: <span class="slider-value quote-form-element valor-carro1" data-name="Valor | Automóvel" name="Valor" data-slider-id="consorcio-auto">R$ <span id="THAT_VALUE"></span></span>
</h4>
<div class="slider" data-slider-min="20000" data-slider-max="100000" data-slider-start="23192" data-slider-step="1000" data-slider-id="consorcio-auto"></div>
<h4>Seus dados:</h4>
<input type="hidden" id="THAT_FIELD" name="THAT_FIELD" value="" />
<h4>Seus dados:</h4>
<input type="hidden" id="valorcarro" name="valorcarro" value="" />
script
$(function(){
var valorcarro = $('#THAT_VALUE').html();
$('#THAT_FIELD').val(valorcarro);
});
example in this page in the button on menu "Simulação".
The script just does not copy because the value is generated later and the user can still change
You need to use an event to fire your code after the slider value has changed. This is how you do it with a bootstrap slider.
$('.slider').on('slideStop', function () {
var valorcarro = $('#THAT_VALUE').text();
$('#THAT_FIELD').val(valorcarro);
});
To get the text of an element, use text()
For example
$("span").text();
you can try this code.
jQuery(function(){
var valorcarro = jQuery('#THAT_VALUE').text();
jQuery('#THAT_FIELD').val(valorcarro);
});
Actually, #Pamblam's response is better than mine. I was assuming the .slider class was for regular range inputs, which fire the 'change' event when their value changes, but it looks like it is in fact a bootstrap slider, which fires the slideStop event instead. Regardless, the code here listens for a change in the slider value, and when it is triggered, takes the text from the #THAT_VALUE span (from op's code) and sets the value of the #THAT_FIELD field to whatever it is :
$(".slider").change(function(){
var valorcarro = $('#THAT_VALUE').text();
$('#THAT_FIELD').val(valorcarro);
});

how to get input field name through event object in angular 2

I am not sure whether its logical to get.
Here is the html code for my input box.
<input type="text" id="name" #name="ngForm" [ngFormControl]="userProfileForm.controls['name']"
[(ngModel)]="loggedUserInfo.name" (change)="firechange($event,'name')"
/>
and here is my firechange function
firechange($event, field){
if(this.userProfileForm.controls[field].valid){
this._userService.updateUserProfile(this.loggedUserInfo);
this._userService.loadUserData();
}
}
I want to pass only the event in the firechange function and inside the fire change function I want to get the input field name from the event so that I can understand that which input field in my form triggered the event. Expected code will be something like that
[ngFormControl]="userProfileForm.controls['name']"
[(ngModel)]="loggedUserInfo.name" (change)="firechange($event)"
/>
firechange($event){
if(this.userProfileForm.controls[$event.fieldname].valid){
this._userService.updateUserProfile(this.loggedUserInfo);
this._userService.loadUserData();
}
}
My ideal requirement is, in a form there are number of form fields, I don't even want to write firechange function in each individual form field. Is there any generic way to call the event on each input field value change for a particular form without writing it on each input field?
To get the actual name of the element you can do the following:
firechange(event){
var name = event.target.attributes.getNamedItem('ng-reflect-name').value;
console.log('name')
}
If the id is the same as the name you are passing you can get the name like
firechange(event){
if(this.userProfileForm.controls[$event.target.id].valid){
}
If you want to get hold of the element from within your fire change function you may want to try something like:
firechange(event){
let theElement = event.target;
// now theElement holds the html element which you can query for name, value and so on
}
If you in addition you want to instruct your component to apply the firechange() logic on all of your input fields with one single instruction in your component (and not having to specify this on every single input field) than I suggest you to look at in Angular2 how to know when ANY form input field lost focus.
I hope this helps
If id is not the same or it can change, here's more leverage...
You may want to reflect the [name] property the the element's attribute:
... #input [name]="item.name" [attr.name]="item.name" (change)="fn(input)" ...
Then,
...
fn(input) {
log(input.name); // now it returns the name
}
...
See more here
Try this:
<input type="text" (change)="firechange($event.target.value)">
This worked for me in Angular 10
$event.source.name

In Vanilla JS - Change a variable once a user finishes typing

Without using jQuery - I am trying to simply change a var based on a input's value - when the user finishes typing then update the div value. Is there a way to do it without writing a function to fire onchange? Something like if a change happen change var.
<div>
<input type="text" maxlength="12" id="inNum" />
</div>
<div id="rooms"></div>
var disNum = document.getElementById('inNum').onchange;
document.getElementById('rooms').innerHTML = disNum.value;
The best way is to listen to one of keypress, keydown or keyup.
I tried listening to onchange but that would only fire when the input was blurred; maybe this is your current problem, or actually your desired behaviour. If this is your desired behaviour, just replace .onkeyup below with .onchange.
The only other way you could do this (that I can think of) is by using some setInterval loop, and re-checking the state in each iteration, but really, that would be a terrible idea.
Here, I've made a JSFiddle to demonstrate my approach.
var disNum = document.getElementById('inNum');
disNum.onkeyup = function(){
document.getElementById('rooms').innerHTML = disNum.value;
};
<div>
<input type="text" maxlength="12" id="inNum">
</div>
<div id="rooms"></div>

html <input type="text" /> onchange event not working

I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the onchange event property to make it happen but it doesn't work. I still need to press the submit button to make it work. I read about AJAX and I am thinking to learn about this. Do I still need AJAX to make it work or is simple JavaScript enough? Please help.
index.php
<script type="text/javascript" src="javascript.js"> </script>
<form action="index.php" method="get">
Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
<input type="submit" value="Compute" />
</form>
javascript.js
function checkInput(textbox) {
var textInput = document.getElementById(textbox).value;
alert(textInput);
}
onchange is only triggered when the control is blurred. Try onkeypress instead.
Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.
For static and dynamic inputs:
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
For static inputs only:
$('.my-class').on('input', function(){
alert('Input changed');
});
JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/
HTML5 defines an oninput event to catch all direct changes. it works for me.
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc
Read more about the change event here
Read more about the input event here
use following events instead of "onchange"
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
Firstly, what 'doesn't work'? Do you not see the alert?
Also, Your code could be simplified to this
<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />
function checkInput(obj) {
alert(obj.value);
}
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
A couple of comments that IMO are important:
input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.
The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input
The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)
Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...
jQuery has nothing to do with this. This is all in HTML standard.
If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.
My two cents.
onkeyup worked for me. onkeypress doesn't trigger when pressing back space.
It is better to use onchange(event) with <select>.
With <input> you can use below event:
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
when we use onchange while you are typing in input field – there’s no event. But when you move the focus somewhere else, for instance, click on a button – there will be a change event
you can use oninput
The oninput event triggers every time after a value is modified by the user.Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.
<input type="text" id="input"> oninput: <span id="result"></span>
<script>
input.oninput = function() {
console.log(input.value);
};
</script>
If we want to handle every modification of an <input> then this event is the best choice.
I have been facing the same issue until I figured out how to do it. You can utilize a React hook, useEffect, to write a JS function that will trigger after React rendering.
useEffect(()=>{
document.title='fix onChange with onkeyup';
const box = document.getElementById('changeBox');
box.onkeyup = function () {
console.log(box.value);
}
},[]);
Note onchange is not fired when the value of an input is changed. It is only changed when the input’s value is changed and then the input is blurred. What you’ll need to do is capture the keypress event when fired in the given input and that's why we have used onkeyup menthod.
In the functional component where you have the <Input/> for the <form/>write this
<form onSubmit={handleLogin} method='POST'>
<input
aria-label= 'Enter Email Address'
type='text'
placeholder='Email Address'
className='text-sm text-gray-base w-full mr-3 py-5 px-4 h-2 border border-gray-primary rounded mb-2'
id='changeBox'
/>
</form>
Resulting Image :
Console Image
try onpropertychange.
it only works for IE.

Categories