Adding Javascript functions to forms - javascript

I'm learning JavaScript in school and have some homework labs. I created some forms and I'd like the buttons to accomplish some things when I press it, I'll just ask for help on the first couple buttons, as I just need examples so I can work on the harder ones on my own. Here's what I need for the first couple buttons:
JavaScript function hello( ) that gets the name and year of birth entered into the corresponding text boxes, and outputs the string “Hello [name] you were born in [year]”. The string will be output inside the paragraph element.
Call the hello( ) function from the Hello button.
JavaScript function calcAge( ) that gets the year of birth from the textbox, and computes the age of the person. Compute the age by subtracting the year of birth from the current year. Then output the string “You are [age] years old”. The string will be output inside the paragraph element.
Call the calcAge( ) function from the Calc Age button.
Thank you in advance for any help. I'm taking an independent study course and having a hard time. Here's my html for the forms.
<html>
<head>
<title>Forms Page</title>
<style>
form {
width: 500px; margin: 0px auto;
border:1px solid khaki; background-color: antiquewhite;
border-collapse:collapse; padding: 10px; margin-bottom: 20px;
}
form h2 { margin: 0; }
input {
margin:5px;
}
</style>
</head>
<body>
<h1>Practice Manipulating Forms #1</h1>
<form id='calcForm'>
<h2>Calc Form</h2>
<span>Name:</span>
<input type='text' name='name' id='name' ><br>
<span>Year of Birth:</span>
<input type='text' name='yob' id='yob' ><br>
<input type='button' name='btnCalc' id='btnHello' value='Hello' >
<input type='button' name='btnCalc' id='btnCalc' value='Calc Age' >
<p id='pForm'></p>
</form>
<form id='listForm'>
<h2>List Form</h2>
<span>Item:</span>
<input type='text' name='item' id='item' ><br>
<input type='button' name='btnAdd' id='btnAdd' value='Add to List' >
<input type='button' name='btnClear' id='btnClear' value='Clear List' >
<input type='button' name='btnShow' id='btnShow' value='Show List' >
<p id='pList'></p>
</form>
</body>
</html>

Add an onclick attribute to the appropriate buttons to trigger the function.
onclick="hello()"
onclick="calcAge()"
Then the scripts:
function hello(){
var name = document.getElementById("name").value;
document.getElementById("pForm").innerHTML = "Hello "+name;
}
function calcAge(){
var yob = document.getElementById("yob").value;
var date = new Date();
var year = date.getFullYear();
var age = year - yob;
var alreadyOutput = document.getElementById("pForm").innerHTML;
document.getElementById("pForm").innerHTML = alreadyOutput+" and you are "+age;
}
Please use indentations and I highly recommend https://www.w3schools.com/jsref/ since you don't seem to know any js.

Related

Change the CSS when there is a required element

I'm a student developer and I'd like to make a message appear when I click on the submit button but there's still a select required
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<p class="messagerequire">Test, If there is a require to submit I appear ! </p>
Here it has the style display:none and I thought I would do that if the form doesn't validate because of a requirement, it changes the CSS.
I've been searching since this morning for answers, but I haven't found or understood.
<input type="submit" name="register" value="register">
Thanks you
Simply check if the select input is invalid in your submit handler, then change the display property for that p element (in this case the first element that has the class). Not the most elegant solution but the simplest in your case:
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', function() {
document.getElementsByClassName('messagerequire')[0].style.display = 'block';
})
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<p class="messagerequire">Test, If there is a require to submit I appear !</p>
<input type="submit" id="submit">
A better approach in my view would be to have two classes for showing and hiding the error and dynamically toggling the p elements' class instead of modifying it's styles.
you code should be something like below. becuase you are using input type=submit so before submit it should validate.
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.getElementById('error').style.display='block';
return false;
}
}
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<form name="myForm" action="/page.php" onsubmit="return validateForm()" method="post">
<p class="messagerequire" id='error'>Test, If there is a require to submit I appear ! </p>
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
You need to use JavaScript to achieve this.
function submitThis(){
let name = document.getElementById("name").value;
if(name.length === 0){
document.getElementsByClassName("error")[0].innerText = "Cannot leve name empty.";
//Removing(hinding) the error after 5 seconds.
setTimeout(()=>{
document.getElementsByClassName("error")[0].innerText = "";
}, 5000);
}
}
.error {
color: red;
}
<input type="text" palceholder="Name" id="name" required />
<br>
<br>
<p class="error"></p>
<br>
<br>
<button onclick="submitThis()">SUBMIT</button>
Please you try it.
$('#submit').click(function(){
$('.messagerequire').css('display','block');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<body>
<p class="messagerequire">Test, If there is a require to submit I appear !</p>
<input type="submit" id="submit">
</body>

How to display entered text in an textbox?

I would like to enter a text in an input field and have it displayed in a text box.
I think it's easy. I need one Input for enter a text, a button and a textbox to show my text. But my code doesn't work.
This is my code:
<!DOCTYPE html>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
function ausgabe(){
var text=document.getElementById("text");
var Wiedergabe=document.getElementById("Wiedergabe");
var Text=text.value;
Wiedergabe.value=Text
}
</script>
<div class="Webview">
<div class="message_container" id="myForm" ></div>
<form class="send_container">
<input type="text">
<button type="submit"
value="Nachricht absenden"
onclick="ausgabe">
</form>
</div>
#charset "UTF-8";
.Webview{
height: 400px;
width: 300px;
}
.message_container{
height: 80%;
width: 100%;
border:5px solid green;
}
.send_container{
height: 20;
width: 100%;
}
.send_container input{
width: 70%;
height:20%
border:2px solid #1CE615;
}
.send_container button{
width: 30%;
height:20%;
}
I think you somehow did some misconceptions about id and naming, you are trying to access elements with wrong names - a solution can be the following:
<input id="textField" type="text">
<p>
<input type="button" id="theButton" value="click me!"
onclick="document.getElementById('div').innerHTML =
document.getElementById('textField').value" />
</p>
<h3><div id="div"></div></h3>
I found few issues in your code, let me summarize that here:
For input element for user provided text you had the <input type="text"> which should have an id attribute as well in order to catch by getElementById.
In order to find an aim element, you need to also provide a proper id or class. I guess with the message_container you can achieve that by using document.getElementsByClassName('message_container')[0]. Then you can set the value of that element with innerHTML property.
So based on my explanation I think this solution can work for you:
const ausgabe = () => {
const textInput = document.getElementById("text");
const messageContainer = document.getElementsByClassName('message_container')[0];
messageContainer.innerHTML = textInput.value;
}
<div class="Webview">
<div class="message_container" id="myForm"></div>
<form class="send_container">
<input id="text" type="text" />
<button type="button" onclick="ausgabe()">Nachricht absenden</button>
</form>
</div>
I hope this helps!

How to get input from multiple text boxes

I'm just starting to play around with JavaScript and Jquery and have hit a roadblock. I want users to be able to add & subtract boxes and fill it with input. Here's my html
<body>
<h1>Math Grades</h1>
<div id="mathGrades">
<input style="height:50px; width:50px; font-size:16pt; text-align: center" type='number' id="fooBar">
<input style="height:50px; width:50px; font-size:16pt; text-align: center" type='number' id="fooBar">
</div>
<button type="button" id="addBox">+</button>
<button type="button" id="subtractBox">-</button>
<br>
<button type="button" id="getGrades">Submit Grades</button>
<script src="calcjq.js"></script>
Here's my code:
$(document).ready(function() {
var addMathBox = document.getElementById("addBox");
addMathBox.addEventListener('click', addBox, false);
var subtractMathBox = document.getElementById("subtractBox");
subtractMathBox.addEventListener('click', subtractBox, false);
var getScores = document.getElementById("getGrades");
getScores.addEventListener('click', getUserGrades, false);
function getUserGrades(){
var userGrades = document.getElementById("fooBar").value;
console.log(userGrades);
}
function subtractBox(){
$('#fooBar').remove()
}
function addBox(){
$('#mathGrades').append('<input style="height:50px; width:50px; font-size:16pt; text-align: center" type="number" id="fooBar">')
};
});
How can I make sure to gather all of the input without knowing how many boxes they'll add and fill?
EDIT
Finally found a way to do this:
var mathGrades = $("input[class='mathGrades']")
.map(function(){return parseInt($(this).val(), 10);}).get();
First of all, and you probably know this but I wanted to point it out any way, your id attribute should be unique for each element. So make sure it's not foobar for all of them.
What you could do to solve your problem is add a unique class, i.e. mathGrades, to each input and then use the following code to collect all of the data and do as you please with it.
var mathGrades = document.getElementsByClassName('mathGrades');
var m, v;
for(m in mathGrades) {
v = $(mathGrades[m]).val(); // takes value and converts to string i.e. "1"
$(mathGrades[m]).val(v+1); // assigns new value "1" + "1" = "11"
}
In your javascript you could change the function addBox to:
function addBox() {
$('#mathGrades').append('<input style="height:50px; width:50px; font-size:16pt; text-align: center" type="number" class="mathGrades">')
};

While typing in a text input field, printing the content typed in a div

I have a website where there is a empty box and a input text box. I want to be able to type something in that input box and have it be printed on the empty box.
HTML
<div class='printchatbox'></div>
which is the empty box and
<input type='text' name='fname' class='chatinput'>
which is the input box.
CSS
.printchatbox
{border-width:thick 10px;border-style: solid;
background-color:#fff;
line-height: 2;color:#6E6A6B;font-size: 14pt;text-align:left;float: middle;
border: 3px solid #969293;width:40%;}
If anyone could tell me how to do this I would greatly appreciate it. Thanks
You use the onkeyup event
Searching with ids is a lot easier. Add ids to your elements as follows:
<div class='printchatbox' id='printchatbox'></div>
<input type='text' name='fname' class='chatinput' id='chatinput'>
JS
var inputBox = document.getElementById('chatinput');
inputBox.onkeyup = function(){
document.getElementById('printchatbox').innerHTML = inputBox.value;
}
Here is a Live example
http://jsfiddle.net/3kpay/
<div class='printchatbox' id='printchatbox'></div>
<input type='text' name='fname' class='chatinput'
onkeyUp="document.getElementById('printchatbox').innerHTML = this.value" />
There are many ways to get this done, possibly the easiest is to use jQuery. In the example below I am using the jQuery keyUp() function to listen for keyboard events, then writing the updated value to the .printChatBox
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
</head>
<body>
<div class='printchatbox'>CHANGE ME</div>
<input type='text' name='fname' class='chatinput'>
<script type="script/javascript">
$('.chatinput').keyup(function(event) {
newText = event.target.value;
$('.printchatbox').text(newText);
});
</script>
</body>
</html>
I've posted a working example here: http://jsbin.com/axibuw/1/edit
In your HTML,
<div id='printchatbox'></div>
<br>
<input type='text' id='fname' class='chatinput' onkeyup="annotate()">
In JS,
function annotate(){
var typed= document.getElementById("fname").value;
document.getElementById("printchatbox").innerHTML= typed;
}
Click here for LIVE DEMO
Angular JS does this in two lines of code :
Just import Angular JS as you import other libraries :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js">
Then, on you first div (where you are copying from):
<input type="text" ng-model="myID"> </input>
Then, on the place where you will show the content : just write :
<div> {{myID}}</div>
This is the best solution I have ever found !

Is it possible to update a url link based on user text input?

For instance, I know that it is possible to do something in Javascript that allows users to update text based on user text input:
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
}
</script>
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText2()' value='Change Text'/>
View the above code in action at: tizag.com/javascriptT/javascript-innerHTML.php
However, instead of the above code, I would like to know if it's possible to do something similar for a url link. Below I've placed a step by step example of what I would like to happen upon the user inputing text:
Original Link:
http://www.google.com/search?q=
User Input in Text Field:
espn
User clicks button to submit text in text field
Final Link:
http://www.google.com/search?q=espn
Thanks for your help...BTW...if you can't tell I'm a bit of a novice so detail is appreciated.
Here's one in plain JS that updates as you type:
<a id="reflectedlink" href="http://www.google.com/search">http://www.google.com/search</a>
<input id="searchterm"/>
<script type="text/javascript">
var link= document.getElementById('reflectedlink');
var input= document.getElementById('searchterm');
input.onchange=input.onkeyup= function() {
link.search= '?q='+encodeURIComponent(input.value);
link.firstChild.data= link.href;
};
</script>
Note:
no inline event handler attributes (they are best avoided);
assigning both keyup and change, to try to get keyboard updates as they happen and ensure that all other updates get caught eventually;
the use of encodeURIComponent(), necessary in case the search term has any non-ASCII or URL-special characters in;
setting the search property of a Location (link) object to avoid having to write out the whole URL again;
setting the data of the Text node inside the link to reflect the full URL afterwards. Don't set innerHTML from user input as it may have HTML-special characters like & and < in.
#1: you need some forms
#2: you need to catch when the form is submitted
#3: based on the form's submission change the url
Here is a demo: http://jsfiddle.net/maniator/K3D2v/show/
here is the code: http://jsfiddle.net/maniator/K3D2v/embedded/
HTML:
<form id="theForm">
<input id='subj'/>
<input type='submit'/>
</form>
JS:
var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');
theForm.onsubmit = function(e){
location = "http://jsfiddle.net/maniator/K3D2v/show/#"
+ encodeURIComponent(theInput.value);
return false;
}
I'd suggest using a cross browser library such as jQuery rather than straight JavaScript. With jQuery, you'd add a click handler for your button, grab the value of the input, build your URL, and set window.location to go to the new url
jsFiddle
HTML
<input type="text" id="q" />
<input type="button" id="submit" value="submit" />
JavaScript
$(function () {
$('#submit').click(function() {
var url = "http://www.google.com/search?q=";
url += $('#q').val();
window.location = url;
});
});
You could try this;
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
</script>
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' value='Enter Search String Here' />
<input type='button' onclick='changeText2()' value='Change Link'/>
Check it out here
This is the solution I deviced in a matter of seconds:
<input type="text" name="prog_site" id="prog_site" value="http://www.edit-me.com" />
Open URL
No complex javascript, no extra quotes nor functions required. Simply edit the ID tag to your needs and it works perfectly.
I think this might be useful:
.btn {
border: none;
outline: 0;
display: inline-block;
padding: 10px 25px;
color: black;
background-color: #ddd;
text-align: center;
cursor: pointer;
}
.btn:hover {
background-color: #555;
color: white;
}
.textinput {
line-height: 2.5em;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
</head>
<body>
<form action='#' method='post'>
<label for='ytid'>Please enter your YouTube Video ID:</label>
<br>
<br>
<iframe
href='#'
width='287.5'
height='250'
frameborder='0'
allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture'
allowfullscreen
src='https://www.youtube.com/embed/'
id='ytvid'
></iframe>
<br>
<br>
<input
type='text'
class='textinput'
size='50'
id='ytid'
name='ytid'
placeholder='m4jmapVMaQA'
minlength='1'
maxlength='11'
onchange='document.getElementById("ytvid").src = "https://www.youtube.com/embed/" + this.value'
>
<br>
<br>
<button type='submit' class='btn'>Generate Subtitles »</button>
</form>
</body>
</html>
WARNING:
This code snippet might not run well in Stack Overflow.
This way, the video updates every time there is a change in the text input.
I'm actually making a YouTube Video subtitle generator, so I just copy pasted my code here.
www.google.com/search?q=<br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
var input=document.getElementById('userInput').value;//gets the value entered by user
//changing the href of tag <a> by concatenatinng string "www.google.com/search?q=" and input (user input)
document.getElementById("link").href = "www.google.com/search?q="+input;
//changing the text from "www.google.com/search?q=" to "www.google.com/search?q=" + user input
document.getElementById("link").innerHTML = "www.google.com/search?q="+input;
}
Clicking the button calls the function changeText2. Which performs the task.

Categories

Resources