I have the following problem when adding list items to an ul using javascript code: I'm trying to add a list item to a ul, which is added and displayed for a fraction of a second before disappearing.
This is the code for adding the item to ul in file1.js:
function isValidForm() {
addContentToUl("item1");
}
function addContentToUl(error) {
var ul = document.getElementById("errorList");
var li = document.createElement("li");
li.appendChild(document.createTextNode(error));
ul.appendChild(li);
}
This is the line of code for calling the function in file2.js:
document.getElementById("myForm").onsubmit = isValidForm;
And the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>My first PIU lab</title>
<link rel="stylesheet" type="text/css" href="BaroiuCezar_Lab1.css">
<script type="text/javascript" src="file1.js"></script>
</head>
<body>
<div>
<form id="myForm" action="">
<ul id="errorList"></ul>
<p>Numele</p>
<input id="idLastname" type="text" name="lastName" />
<p>Prenumele</p>
<input id="IdFirstName" type="text" name="firstName" />
<p>Adresa</p>
<input id="idAddress" type="text" name="address" />
<p>Data nasterii</p>
<input id="idBirthday" type="text" name="birthDate" />
<p>Telefon</p>
<input id="idPhone" type="text" name="phoneNumber" />
<p>Email</p>
<input id="idEmail" type="text" name="email" />
<section>
<span>Culoarea favorita</span>
<input id="idColor" type="color" name="color" />
</section>
<br /><br /><br />
<input type="submit" value="Trimite" />
<input type="submit" value="Reseteaza" />
</form>
<script type="text/javascript" src="file2.js"></script>
</div>
The added item should be displayed in the first ul after the form element.
function isValidForm(e) {
e.preventDefault();//disable default form submission by browser.
addContentToUl("item1");
}
function addContentToUl(error) {
var ul = document.getElementById("errorList");
var li = document.createElement("li");
li.appendChild(document.createTextNode(error));
ul.appendChild(li);
}
Your submit function which is isValidForm should return false to prevent the form from submitting. Like below
function isValidForm() {
addContentToUl("item1");
return false;
}
Related
I am new to HTML and JavaScript. I just made a simple page to add two numbers. The output that I am getting is correct but when I click the sum button the sum is there for a fraction of second and then again the page reloads itself.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
<script>
function get_sum() {
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
</script>
</head>
<body>
<form id="form" onsubmit="return get_sum()">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button type="submit">Sum </button>
</form>
<h1 id="sum"></h1>
</body>
</html>
You need to pass the event and add event.preventDefault(); at the beginning of the function to prevent page from reloading since it's a submit button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
<script>
function get_sum(event) {
event.preventDefault();
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
</script>
</head>
<body>
<form id="form" onsubmit="return get_sum(event)">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button type="submit">Sum </button>
</form>
<h1 id="sum"></h1>
</body>
</html>
The onsubmit must return false to prevent browser from submitting it to server.
Like this
<form id="form" onsubmit="get_sum(); return false;">
You can add an event listener to handle the click after you change the type to "button". Or you can stop the event from propagating to the actual "submit" action. OR, do both to prevent the submit of the form.
Why both? A form can also be submitted by hitting "return/enter" or via script.
This is perhaps a bit of overkill but shows how to handle the events.
function get_sum(event) {
event.preventDefault();
let num_a = parseInt(document.getElementById('first').value);
let num_b = parseInt(document.getElementById('second').value);
document.getElementById('sum').innerText = (num_a + num_b).toString(10);
}
const sumButton = document.getElementById('sum-click');
sumButton.addEventListener("click", get_sum, false);
const form = document.getElementById('form');
form.addEventListener('submit', get_sum);
<form id="form">
<label>First Number: <input type="text" id="first" placeholder="Enter a number" required></label>
<br>
<label>Second Number: <input type="text" id="second" placeholder="Enter a number" required></label>
<button id="sum-values" type="submit">Sum </button>
<button id="sum-click" type="button">Sum (Not submit)</button>
</form>
<h1 id="sum"></h1>
I've written a validator for my HTML although I'm not sure where I'm going wrong.
What I'm trying to do below is determine if there is any text in the "First Name" box altogether. There is underlying css to the code but I believe my issue is surrounding my onsubmit and validate function as nothing in the javascript seems to be running once I click the submit button.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<link rel="stylesheet" type="text/css" href="NewPatient.css">
<script>
function validate() {
var invalid = false;
if(!document.Firstname.value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
Looks like the culprit was your attempt to access Firstname on the document object.
I replaced it with the more standard document.getElementById() method and its working.
Some reading on this: Do DOM tree elements with ids become global variables?
function validate() {
var invalid = false;
if(!document.getElementById('Firstname').value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false;
}
return true;
}
#form-error {
display: none;
}
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate()">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
There are a couple of typos, and I'll suggest something else as well. First, a fix or three in the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<script>
function validate() {
const invalid = document.getElementById("Firstname").value.length == 0;
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
My suggestion is that you also look into built-in HTML form validation attributes. I'm thinking you're reinventing the wheel for things like requiring a non-empty Firstname. Why not this instead of JavaScript?
<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />
And many others, like minlength="", min="", step="", etc.
Plus there's still a JavaScript hook into the validation system with .checkValidity() so you can let the built-in validation do the heavy lifting, and then throw in more of your own custom aspects too.
I have the following HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
I want to get the value that is introduced in value1 and when the submit is clicked to put that value in the output. So I wrote in script.js the following code but somehow it doesn't work.
<script>
window.onload = function(){
var val = document.getElementById('value1').innerHTML;
document.getElementById('result').innerHTML = val;
};
</script>
Any ideas?
You have to use .value property of the input field instead of innerHTML. so it would be:
var val = document.getElementById('value1').value;
and also, since you're executing it when the page loads. There will be no value assigned to the input field with id 'value1'. Therefore, you won't get any result.
You can try adding a button with onClick event to execute this function in place of using window.onload
HTML controls you are working on are textboxes, so they have a value property, not innerHTML.
Use this:
var val = document.getElementById('value1').value;
document.getElementById('result').value= val;
You can't get the value of an input element using the innerHTML attribute. Use value instead:
var val = documento.getElementById('value1').value;
Also you should keep in mind that your function is executed when the page loads, NOT when the form is submitted.
The code is not working, because you are calling this function when the window loads, not when the submit button is clicked. Since there is no form, and thus no page loading going on, I'd recommend switching the <input type="submit" value="Click" /> to a button. They are functionally similar, and visually identical. With the the button, though you could use the onclick attribute to call a function when the button is clicked. See below for an example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<button onclick="printOutput()">Click</button>
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
Then in your script.js you would have,
function printOutput(){
var val = document.getElementById('value1').value;
document.getElementById('result').innerHTML = val;
}
when the submit is clicked to put that value in the output
You have chosen wrong event window.onload, also you need .value instead of .innerHTML
Option 1: using jQuery, as you already have the import
$(function() {
$('input[type="submit"]').on('click', function(e) {
$('#result').val($('#value1').val());
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
Option 2: using plain js
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
document.querySelector('#result').value = document.querySelector('#value1').value;
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
<script>
$( document ).ready(function() {
setTimeout(function(){
var val = document.getElementById('value1').innerHTML;
var generateHere = document.getElementById("result");
generateHere.innerHTML = val;
}, 2000);
});
</script>
Quick question. I am starting learn on local storage HTML5. How can I get value from a form and display that value on another HTML form page?
For example, I have two forms here.
If I fill on form 1 and click submit button, and the value will display on form 2 in readable only.
I tried below:
HTML Form 1:
<html>
<head>
<title>Save Value</title>
<script type="text/javascript">
function saveVal() {
var inputFirst = document.getElementById("name").value;
localStorage.setItem("name", inputFirst);
inputFirst = localStorage.getItem("name");
}
</script>
</head>
<body>
<form action="display.html" method="get">
<label>
First Name:
<input name="name" size="20" maxlength="25" type="text" id="name" />
</label>
<input type="submit" value="submit" onclick="saveVal()"/>
</form>
</body>
</html>
HTML Form 2:
<html>
<head>
<title>Display</title>
<script type="text/javascript">
function result() {
var storedVal = document.getElementById("name");
storedVal.value = localStorage.getItem("name");
}
</script>
</head>
<body>
<form action="#">
<label>
First Name:
<input name="name" size="20" maxlength="25" type="text" id="name" readonly="readonly" />
</label>
</form>
</body>
</html>
In display.html you didn't call function result(),
try this,
<html>
<head>
<title>Display</title>
</head>
<body>
<form action="#">
<label>
First Name:
<input name="name" size="20" maxlength="25" type="text" id="name" readonly="readonly" />
</label>
<script type="text/javascript">
var storedVal = document.getElementById("name");
storedVal.value = localStorage.getItem("name");
</script>
</form>
</body>
</html>
I have below html code
<div id="divTest">
Hello
<input type="text" id="txtID" value="" />
<input type="button" onclick="getForm();" value="Click" />
</div>
And I have below javascript function to get innerHtml value
<script language="javascript" type="text/javascript">
function getForm()
{
var obj = document.getElementById('divTest');
alert(obj.innerHTML);
}
</script>
I am trying to get the complete innerHtml value. When user put some value in "txtId" and when he clicks on button it should show all the innerHtml with txtId value in it. It is working fine in Internet Explorer but failing in Mozilla.
Please suggest what type of changes I need to do in javascript function or I need some Jquery for this.
Thanks.
Best Regards,
I've run across this myself - try using obj.innerHtml (note capitalisation) instead.
I solved my problem by using below jQuery
<script type="text/javascript">
$(document).ready(function()
{
var oldHTML = $.fn.html;
$.fn.formhtml = function() {
if (arguments.length) return oldHTML.apply(this,arguments);
$("input,textarea,button", this).each(function() {
this.setAttribute('value',this.value);
});
$(":radio,:checkbox", this).each(function()
{
if (this.checked) this.setAttribute('checked', 'checked');
else this.removeAttribute('checked');
});
$("option", this).each(function()
{
if (this.selected) this.setAttribute('selected', 'selected');
else this.removeAttribute('selected');
});
return oldHTML.apply(this);
};
$.fn.html = $.fn.formhtml;
});
$(document).ready(function()
{
$('input[type=button]').click(function() {
alert($('#divTest').html());
});
});
</script>
and the html was as below:
<div id="divTest">
Hello
<input type="text" id="txtID" />
<input type="text" id="txtID" />
<input type="text" />
<input type="text" id="Text1" />
<input type="text" id="Text1" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" id="Text5" />
<input type="text" id="Text6" />
</div>
<input type="button" value="Click" />