Outputting text into input field in JavaScript - javascript

Trying to press a button which outputs text in an input field. the function is to output text "x" into input field upon press, which is set to read only. only js and html allowed. Here's what i got so far in HTML and js:
<button id="button4" onclick="output()">Hokus Pokus</button>
<input id="printoutput" readonly="true" type="text">
js:
function output() {
document.getElementById("printoutput").innerHTML = "x";
}
Why does this not work?

Do it like this and it works like a charm:
function output() {
document.getElementById("printoutput").value = "x";
}
<button id="button4" onclick="output()">Hokus Pokus</button>
<input id="printoutput" readonly="true" type="text">

Fixed. did this:
function output() {
document.getElementById("printoutput").innerHTML = "x";
}
When it should be:
function output() {
document.getElementById("printoutput").value = "x";
}

You need to set the value of the input, not the inner html
document.getElementById("printoutput").value = "x";
<button id="button4" onclick="output()">Hokus Pokus</button>
<input id="printoutput" readonly="true" type="text">

Related

my value property doesn't pass me anything

I'm trying to simply get the value of an input and put it into a p tag.but it looks like that I'm not getting anything from the input tag
<body>
<input type="text" id="text">
<button class="button" onclick="sum();">click</button>
<p id="lblResult">Result</p>
</body>
<script>
const text = document.getElementById('text').value;
function sum()
{
document.getElementById('lblREsult').innerHTML = text;
}
</script>
You get value from input on page load when it's empty, move document.getElementById('text').value into sum function.
And you have an typo, lblREsult !== lblResult
function sum() {
const text = document.getElementById('text').value;
document.getElementById('lblResult').innerHTML = text;
}
<input type="text" id="text">
<button class="button" onclick="sum();">click</button>
<p id="lblResult">Result</p>

Clicking a button and getting the input from a user

Here is a picture. I have done css and html on my own and now don't know how to add javascript here.
What I want is:
a user writes something
then he clicks on button (for example uppercase) and his text appears at the bottom, instead of words "Here will be you text". How can I add such a function? I am confused.
If you want it in pure Javascript, you can do the code in the snippet.
I will assume that you know HTML and CSS, end explains only the javascript code.
The idea is:
You attach an event listener to handle de user click in each button. Each button has it's own class name, you can use it as a parameter of the document.getElementsByClassName to get an array of objects with this class name. Next you attach the event handler, you can do this with addEventListener.
Inside the click event function, you put the action that will be triggered after any click at the button.
The snippet below has commented code to clear things.
//Get input field with text before any operation
var textField = document.getElementsByClassName("text-field")[0];
//Get button that will trigger the Upper Case function
var upperBtn = document.getElementsByClassName("to-upper-btn")[0];
//Get button that will trigger the Lower Case function
var lowerBtn = document.getElementsByClassName("to-lower-btn")[0];
//Get div that will show the result
var resultContainer = document.getElementsByClassName("text-result")[0];
//Attach a click event listener to the Upper Case button
upperBtn.addEventListener("click", function(){
//Set the inner html of the result container with te value of the input field in uppercase;
resultContainer.innerHTML = textField.value.toUpperCase();
});
//Attach a click event listener to the Lower Case button
document.getElementsByClassName("to-lower-btn")[0].addEventListener("click", function(){
//Set the inner html of the result container with te value of the input field in lowecase;
resultContainer.innerHTML = textField.value.toLowerCase();
});
.text-field {
width:300px;
}
.container {
margin-top:50px;
border:1px solid #e4e4e4;
border-radius:5px;
background:#000;
color:#FFF;
padding:10px;
}
<h1>Write something</h1>
<input type="text" class="text-field"/>
<button type="button" class="to-upper-btn">To Upper Case</button>
<button type="button" class="to-lower-btn">To Lower Case</button>
<div class="container">
<div class="text-result">Just write what you want to make Upper Case or Lower Case, the result will be displayer here</div>
</div>
For more details about the javascript methods used in this code:
getElementByClassName
addEventListener
toUpperCase
toLowerCase
The combination of onclick, toUpperCase and toLowerCase can be used to obtain the required result.
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<h2>Write something</h2>
<input id="inputText" type="text" placeholder="write something" style="width: 300px;">
<br>
<button onclick="upperCaseButtonClicked()">Upper case</button>
<button onclick="lowerCaseButtonClicked()">Lower case</button>
<button onclick="doNothingButtonClicked()">Do nothing</button>
<br>
<textarea id="outputArea" rows="5" cols="35"></textarea>
<script>
function upperCaseButtonClicked() {
var input = document.getElementById("inputText").value
var output = input.toUpperCase()
document.getElementById("outputArea").innerHTML = input.toUpperCase()
}
function lowerCaseButtonClicked() {
var input = document.getElementById("inputText").value
var output = input.toUpperCase()
document.getElementById("outputArea").innerHTML = input.toLowerCase()
}
function doNothingButtonClicked() {
var input = document.getElementById("inputText").value
document.getElementById("outputArea").innerHTML = input
}
</script>
</body>
</html>
const nameNode = document.getElementById("Name");
const nameCopyNode = document.getElementById("NameCopy");
if(nameNode){
nameNode.addEventListener('input',function(){
if(nameCopyNode){
nameCopyNode.value = this.value
}
})
}
<input type = "text" placeholder = "type your name" id="Name"/>
<br>
<br>
<input type = "text" placeholder = "you are typing" disabled id="NameCopy"/>
In the simplest form, using jQuery:
$(document).ready(function() {
$('#uppercase-btn').click(function() {
$('#myoutput').val($("#textid").val().toUpperCase());
});
$('#lowercase-btn').click(function() {
$('#myoutput').val($("#textid").val().toLowerCase());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="myinput" id="textid" />
<button id="uppercase-btn">Uppercase</button>
<button id="lowercase-btn">lowercase</button>
<textarea id="myoutput" disabled></textarea>

Temperature Converter is giving me NaN

I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.
This is what I have tried to do but it gives me NaN
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(this.value)">
<input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Your code is not working because in your #button1 you wrote:
onclick="temperatureConverter(this.value)"
where this is not #inputFahrenheit but #button1. Therefore this.value actually equals to "OK".
To fix your problem, you need to change your temperatureConverter function to get value of #inputFahrenheit instead of using onclick="temperatureConverter(this.value)".
Similar situation happens in your #reset1, therefore your reset input will not work as well. You need to apply the same concept into your reset function, which I suggest to create a new function dedicated just for that.
Generally, it is not encouraged to use the same function to perform completely different actions.
function temperatureConverter(){
var input = document.getElementById('inputFahrenheit');
var value = input.value;
value = parseFloat(value);
var output = document.getElementById('outputCelcius');
output.innerHTML = (value - 32)/1.8;
}
function resetTemperature(){
/* clear the temperature */
console.log('clear');
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter()">
<input id= "reset1" type= "reset" value= "Clear" onclick="resetTemperature()">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Here is the basics needed to get your code working. Basically it is simply just changing what value is passed to the temperatureConverter function. Before you were passing it the value of the button that was being clicked, not the value of the input element you were trying to read. Also, I'm unsure on this one as I didn't look it up, but the reset element wasn't working for me until I put your items inside of a <form> element.
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<form>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(document.querySelector('#inputFahrenheit').value)">
<input id= "reset1" type= "reset" value= "Clear">
</p>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
Please note that most of the time, people don't like putting the event listener in the on[event] attributes, and many developers will prefer that you do something more like this:
// () => {} is something called Arrow function notation, if you didn't know it already.
document.addEventListener('DOMContentLoaded', () => {
function updateOutput(value) {
// make sure you do some checking to avoid XSS attacks.
document.querySelector('#output').innerHTML = value;
}
// keeps the form from submitting since we don't have an actual form handler and this is all front-end
document.querySelector('#converterForm').addEventListener('submit',(e)=>{
e.preventDefault();
});
document.querySelector('#convert').addEventListener('click', () => {
updateOutput(convertToCelsius(document.querySelector('#fahrenheit').value));
});
});
function convertToCelsius(f) {
if(typeof f == 'string') f = parseFloat(f, 10);
if(isNaN(f)) {
throw new Error('Invalid parameter passed to function convertToCelsius');
}
return (f-32) * 5 / 9;
}
<form id="converterForm" action="/">
<input type="number" id="fahrenheit" placeholder="Fahrenheit value">
<input type="button" id="convert" value="Convert to Celsius">
<input type="reset" value="Clear">
<div id="output">
</div>
</form>
Other than that, a good way to check why a function isn't working is to use console.log in your code and then check the Javascript browser (in Chrome you can get to it by hitting ctrl+shift+j, in Firefox I believe it's ctrl+shift+i).
can't see you using any form.
your function,
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
then,
<form id="tempConverter">
Convert: <input type="text" id="unit" name="converter" />
<input
type="button"
value="Submit"
onclick="temperatureConverter(document.getElementById('unit').value);"
/>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
apparently, if you console the value, you were obviously sending "OK" as param to the function(not the value of input field) which is NAN.

Why does this line work without .value?

function check() {
var input;
input = document.getElementById("check_btwn");
if (!input.checkValidity()) {
document.getElementById("check_message").innerHTML = input.validationMessage;
} else {
document.getElementById("check_message").innerHTML = "OK";
}
}
<input type="number" name="" id="check_btwn" min="100" max="300">
<button type="button" onclick="check()">check</button>
<p id="check_message"></p>
Why .value is not used in input=document.getElementById("check_btwn");
but it’s still working?
With innerHtml what you do is that you add any html within an id, for Ex.
<span id="Test"></span>
<script>
document.getElementById("Test").innerHtml = <h2>This is a test</h2>
</script>
As you can se the span tag will have inside it a new tag that will be an h2, with some text in it, now with value there is a difference, because what value does is that it changes the value attr of a tag, for Ex:
<input type="text" id="Test2" value=""/>
<script>
document.getElementById("Test2").value = "i am the new value"
</script>
you can also find a good documentation in
Javascript innerHtml
javascript value

Add a string of text into an input field when user clicks a button

Basically just trying to add text to an input field that already contains a value.. the trigger being a button..
Before we click button, form field would look like.. (user inputted some data)
[This is some text]
(Button)
After clicking button, field would look like.. (we add after clicking to the current value)
[This is some text after clicking]
(Button)
Trying to accomplish using javascript only..
Example for you to work from
HTML:
<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />​
jQuery:
<script type="text/javascript">
$(function () {
$('#button').on('click', function () {
var text = $('#text');
text.val(text.val() + ' after clicking');
});
});
<script>
Javascript
<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
var text = document.getElementById('text');
text.value += ' after clicking';
});
</script>
Working jQuery example: http://jsfiddle.net/geMtZ/
​
this will do it with just javascript - you can also put the function in a .js file and call it with onclick
//button
<div onclick="
document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>
Here it is:
http://jsfiddle.net/tQyvp/
Here's the code if you don't like going to jsfiddle:
html
<input id="myinputfield" value="This is some text" type="button">​
Javascript:
$('body').on('click', '#myinputfield', function(){
var textField = $('#myinputfield');
textField.val(textField.val()+' after clicking')
});​
HTML
<form>
<input id="myinputfield" value="This is some text">
<br>
<button onclick="text()">Click me!</button>​
</form>
Javascript
const myinputfield = document.querySelector("#myinputfield");
function text() {
myinputfield.value = myinputfield.value + "after clicking";
}
I know this question is almost ten years old but this answer does not use jquery so it may be useful to others.
https://codepen.io/frog22222/full/oNdPdVB

Categories