So I can not make the input into a integer. I want to turn this into a int so then it can calculate the age of you. I have been researching but can not find the right answer.
HTML CODE:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>learn</title>
<script src="script.js"></script>
</head>
<form action="/learn.html">
<b>Year Born:</b> <input id="input988744" type="value">
</form>
<button onClick="calculateAge(birthYear);">Summit</button>
<body>
</body>
</html>
Javascript Code:
/*
Function
*/
// var
var birthYear;
birthYear = document.getElementById("input988744");
// function
function calculateAge(birthYearInFun) {
"use strict";
console.log(2018 - birthYearInFun); // make it a number
}
2 things needs to be changed
HTML:Change type of <input> from text to number, number can be negative so can add parameter min="1900" to stop from entering date earlier then 1900
<b>Year Born:</b> <input id="input988744" type="number" min="1900">
Javascript: Need to fetch value of HTML element, thus add .value adter getElementById, as getElementById gives HTML element not its value. To be on safer side use parseInt() or Number() over birthYear
var birthYear;
birthYear = Number(document.getElementById("input988744").value);
or
birthYear = parseInt(document.getElementById("input988744").value);
Both these will make birthYear number.
What you really want it looks like is the input type to be a date... Check out the snippet below
legend {
background-color: #000;
color: #fff;
padding: 3px 6px;
}
.output {
font: 1rem 'Fira Sans', sans-serif;
}
input {
margin: .4rem;
}
label {
display: inline-block;
text-align: right;
width: 20%;
}
<fieldset>
<legend>Choose trip dates</legend>
<div>
<label for="start">Start</label>
<input type="date" id="start" name="trip"
value="2018-07-22"
min="2018-01-01" max="2018-12-31" />
</div>
<div>
<label for="end">End</label>
<input type="date" id="end" name="trip"
value="2018-07-29"
min="2018-01-01" max="2018-12-31"/ >
</div>
</fieldset>
You can access the value of the input field as birthYearInFun.value as Mirodinho said and then if it a string, convert it to a number using parseInt().
birthYear = parseInt(document.getElementById("input988744").value)
Related
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>
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!
I am using input type number in my html. In javascript/jquery I need to check the length of digits and I am using toString().length. But it converts 01 to 1 and length becomes 1. Instead it should print 2 as length.
<input id="exp-mm" maxlength="2" type="number">
Unfortunately, for this use case, you can't use type="number" because you want 01 to not change to 1. Use type="text" and you can have an onChange event to enforce only digits using a regex.
Here's an example of what you're trying to do based on the form validation docs on MDN.
https://jsfiddle.net/xbq3tf3t/1/
HTML:
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation -->
<form>
<label for="month">Expiry month (mm)</label>
<input id="month" required pattern="0?[1-9]|1[0-2]">
<button>Submit</button>
</form>
<div>
Length: <span id="length"></span>
</div>
JavaScript:
document.getElementById('month')
.addEventListener('keyup', event => {
const element = document.getElementById('length');
element.innerText = event.target.value.length;
});
CSS:
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
If you just want to check how many letters/numbers are there in your input field, you can check this way
document.getElementById("exp-mm").value.split("").length
var e = document.getElementById("exp-mm");
document.getElementById("btn").addEventListener("click", function(){
console.log(e.value.length)
})
<input id="exp-mm" maxlength="2" type="number">
<button id="btn">Count</button>
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.
<html>
<head>
<title> Form Validation </title>
<style type="text/css">
fieldset { width: 280px; padding: 6px; }
label { float: left; width: 100px; font: 12px Arial; padding: 5px; }
input { margin-bottom: 5px; }
</style>
</head>
<body>
<form id="inputForm" onsubmit="return validateForm();" action="#">
<fieldset>
<label>First Name:</label><input type="text" name="first_name" /><br />
<label>Surname:</label><input type="text" name="surname" /><br />
<label>Postcode:</label><input type="text" name="postcode" /><br />
<label>Email:</label><input type="text" name="email" /><br />
<input type="submit" name="submit" value="Send form" />
<input type="reset" name="reset" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
function validateForm() {
var form = document.forms['inputForm'];
var formats = {
First_name: /^[a-z]+[\-`\s]?[a-z]+$/i,
Surname: /^[a-z]+[\-`\S]?[a-z]+$/i,
Postcode: /^\d{4}$/,
Email:/^w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/
};
var elCount = form.elements.length;
for(var i = 0; i <elCount; i++) {
var field = form.elements[i];
if(field.type == 'text') {
if(!formats[field.name].test(field.value)) {
alert('Invalid '+field.name.replace('_', ' '));
field.focus();
return false;
}
}
}
}
</script>
</body>
</html>
Hey guys trying to figure out why the code is giving me a error:underfinded formats[fields.Name] but its has been defined. Its just a simple form so I am not sure what I am doing wrong. Sorry for the basic question but I have been looking over it multiple time and can't see it. Cheers again.
Assuming the error you are talking about is on this line:
if(!formats[field.Name].test(field.value)) {
I'd suggest using a lowercase "n" in the "name" property:
if(!formats[field.name].test(field.value)) {
JavaScript is case sensitive.
UPDATE: In addition to what I've already mentioned, but still regarding case sensitivity, your formats object has property names with mixed case, e.g., First_name, but the corresponding input elements have a name attribute in lowercase, e.g., name="first_name", so when you retrieve an element's name and try to use it to look up the property in formats it will return undefined. You need to make those match case.
Fix those errors and it works: http://jsfiddle.net/M4Nzr/