Clicking a button and getting the input from a user - javascript

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>

Related

textContent display Content only for a while (using addEventListener)

I'm trying to display typed text, but it shows only for a moment - don't know why.
HTML
<div>
<h1 id="ASD"></h1>
</div>
<form>
<input type="text" id="OUTPUT">
<input type="submit" value="Check">
</form>
CSS
div{
height: 200px;
width: 200px;
background: red;
}
JS
let output= document.getElementById('OUTPUT');
const newSubmit = document.querySelector('input[type=submit]');
function checkNumber() {
document.getElementById('ASD').textContent = output.value;
}
newSubmit.addEventListener('click', checkNumber, false);
http://codepen.io/Shalahmander/pen/QdKvgJ
Typed text should be display in box after click Submit.
The page is refreshing on the submit click (the form is processed). You can handle event object and call .preventDefault to cancel the default behavior, like this:
let output= document.getElementById('OUTPUT');
const newSubmit = document.querySelector('input[type=submit]');
function checkNumber(e) {
document.getElementById('ASD').textContent = output.value;
e.preventDefault();
}
newSubmit.addEventListener('click', checkNumber, false);
But I suggest using <button/></button>or <input type="button"></input> if you want to perform another action (than submit your form).
Also, remember to close your tags: <input>...</input> or <input />.

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

Input text value into a div?

Say I have this text box:
<input type="text" id="myText" placeholder="Enter Name Here">
Upon pressing a button, I would like to send the value entered into this div:
<div id="text2"></div>
I'm not entirely sure how to do this. Do I create a function and call it to the div? How would I do that?
Could someone clear this up for me? Thanks.
Add an onclick to your button:
<input type="button" id="somebutton" onclick="addText()">
Then write the javascript:
function addText()
{
document.getElementById('text2').innerHTML = document.getElementById('myText').value;
}
Solution using onclick event:
<input type="text" id="myText" placeholder="Enter Name Here">
<div id="text2"></div>
<button id="copyName" onclick="document.querySelector('#text2').innerHTML = document.querySelector('#myText').value" value="Copy Name"></button>
JSFiddle: http://jsfiddle.net/3kjqfh6x/1/
You can manipulate the content inside the div from javascript code. Your button should trigger a function (using the onclick event), which would access the specific div within the DOM (using the getElementById function) and change its contents.
Basically, you'd want to do the following:
<!DOCTYPE html>
<html>
<script>
function changeContent() {
document.getElementById("myDiv").innerHTML = "Hi there!";
}
</script>
<body>
<div id="myDiv"></div>
<button type="button" onclick="changeContent()">click me</button>
</body>
</html>
Mark D,
You need to include javascript to handle the button click, and in the function that the button calls, you should send the value into the div. You can call $("#myText").val() to get the text of the text box, and $("#txtDiv").text(txtToAppend) to append it to the div. Please look at the following code snippet for an example.
function submitTxt() {
$("#txtDiv").text($("#myText").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myText" placeholder="Enter Name Here">
<button onclick = "submitTxt()"> Submit </button>
<div id="txtDiv"> </div>
HTML could be:
<input type='text' id='myText' placeholder='Enter Name Here' />
<input type='button' id='btn' value='click here' />
<div id='text2'></div>
JavaScript should be external:
//<![CDATA[
var pre = onload; // previous onload? - window can only have one onload property using this style of Event delegation
onload = function(){
if(pre)pre();
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
var text2 = E('text2'); // example of Element stored in variable
E('btn').onclick = function(){
text2.innerHTML = E('myText').value;
}
}
//]]>
I would recommend using a library like jQuery to do this. It would simplify the event handling and dom manipulation. None the less, I will include vanilla JS and jQuery examples.
Assuming the HTML in the body looks like this:
<form>
<input id="myText" type="text" placeholder="Enter Name Here">
<br>
<input type="submit" id="myButton">
</form>
<div id="text2"></div>
The Vanilla JS example:
//Get reference to button
var myButton = document.getElementById('myButton');
//listen for click event and handle click with callback
myButton.addEventListener('click', function(e){
e.preventDefault(); //stop page request
//grab div and input reference
var myText = document.getElementById("myText");
var myDiv = document.getElementById("text2");
//set div with input text
myDiv.innerHTML = myText.value;
});
When possible avoid using inline onclick property, this can make your code more manageable in the long run.
This is the jQuery Version:
//Handles button click
$('#myButton').click(function(e){
e.preventDefault(); //stop page request
var myText = $('#myText').val(); //gets input value
$('#text2').html(myText); //sets div to input value
});
The jQuery example assumes that you have/are adding the library in a script tag.

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

insert text to selected Textbox use Javascript

I have 2 textBox and 1 button!
I want to insert text to one of these textboxs. When I click to textbox_1 and click button, mytext will appear at textbox_1. When I click to textbox_2 and click button, mytext will appear at textbox_2.
How can I do this by using JavaScript?
Please help me! I'm new on JavaScript!
put id's of the two textboxes as textbox_1 and textbox_2 and put onclick='onCLickButton();' on the <button> tag
and write the following code in the script
var text_to_be_inserted = "sample";
function onCLickButton(){
document.getElementById("textbox_1").value='';
document.getElementById("textbox_2").value='';
if(document.getElementById("textbox_1").focused){
document.getElementById("textbox_1").value=text_to_be_inserted;
}
else if(document.getElementById("textbox_2").focused){
document.getElementById("textbox_2").value=text_to_be_inserted;
}
else{
// do nothing
}
}
Edited
Please accept my apologies actually I am used to use these functions as I have my own js file having these functions.
please add onfocus='onFocusInput(this);' in the <input> tags and add the following code in the script
function onFocusInput(object){
document.getElementById("textbox_1").focused=false;
document.getElementById("textbox_2").focused=false;
object.focused = true;
}
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts to text box when clicked the button";
function DisplayText(){
if(!index){
document.getElementById("txt1").value = text;
document.getElementById("txt2").value = "";
}
else{
document.getElementById("txt2").value = text;
document.getElementById("txt1").value = "";
}
index = index ? false : true;
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="button" value="Change Text" onclick="DisplayText()"/>
</body>
</html>
Take a look at the onFocus() attribute for the INPUT tag - and think about keeping track of what was last given the focus. I'm being a little vague as this sounds a lot like homework.
It isn't the prettiest / most delicate solution, but it works and you can build off it to fulfill your needs.
<script>
var field = 0;
function addText(txt){
if(field === 0) return false;
field.value = txt;
}
</script>
For a form such as
<form>
<input type="text" name="box1" id="box1" onfocus="field=this;" />
<input type="text" name="box2" id="box2" onfocus="field=this;" />
<input type="button" onclick="addText('Hello Thar!');" />
</form>

Categories