I am having trouble pushing data to another HTML page - javascript

I cannot get my values to go to another html page. I validated the fields and after the fields are filled and we click save the data doesnt go to the new html.
In the new html only Welcome is displayed.
This is the first HTML where we put out name
function parse() {
var n = document.getElementById("nam").value;
localStorage.setItem("textvalue", n);
return false;
}
function validations(form) {
function trimfield(str) {
return str.replace(/^\s+|\s+$/g, '');
}
var errors = [];
var n = document.getElementById("nam").value;
if (n == "") {
errors.push("Enter Name \n");
}
if (errors.length > 0) {
var msg = "Errors : \n\n";
for (var i = 0; i < errors.length; i++) {
msg = msg + errors[i];
}
alert(msg);
return false;
}
}
<!DOCTYPE HTML >
<html>
<head>
<title> User Registration Page</title>
<link href="UserRegistration.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<form action="UserInfo.html" method="POST" onsubmit="return validations(this);" onsubmit="return parse();">
<div class="name">
Name : <input type="text" id="nam" name="fullName">
</div>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</body>
</html>
This is the second html that i am having trouble displaying my Name(UserInfo.html)
<html>
<body>
Welcome : <span id= "result"> </span>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
</body>
</html>

Don't use two onsubmit attributes. Aggregate all your functions inside one and then perform it. I've merged the parse function with the validations. It's the same thing. Also, you never submitted your form. That's why the functions also don't get triggered. Use a submit button too. It should be inside the form tag. Not outside
<!DOCTYPE HTML >
<html>
<head>
<title> User Registration Page</title>
<link href="UserRegistration.css" rel= "stylesheet" type="text/css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script>
function trimfield(str) {
return str.replace(/^\s+|\s+$/g,'');
}
function validations(form) {
var errors = [] ;
var n = document.getElementById("nam").value;
if (n == "") {
errors.push("Enter Name \n");
}
if (errors.length > 0) {
var msg = "Errors : \n\n" ;
for (var i = 0 ; i<errors.length; i++ ){
msg = msg + errors[i];
}
alert(msg);
}else{
localStorage.setItem("textvalue", n);
alert(localStorage.getItem("textvalue"));
return false;
}
}
</script>
</head>
<body>
<form action="UserInfo.html" method="POST" onsubmit="validations(this);">
<div class = "name" >
Name : <input type ="text" id="nam" name="fullName" >
</div>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</body>
</html>
Also, no idea where you are calling trimfield. Declare it outside any other functions and use it wherever you want.

I tried to fix every mistakes you have made :
function parse() {
var n = document.getElementById("nam").value;
localStorage.setItem("textvalue", n);
return true;
}
function validations(form) {
function trimfield(str) {
return str.replace(/^\s+|\s+$/g, '');
}
var errors = [];
var n = document.getElementById("nam").value;
if (n == "") {
errors.push("Enter Name \n");
}
if (errors.length > 0) {
var msg = "Errors : \n\n";
for (var i = 0; i < errors.length; i++) {
msg = msg + errors[i];
}
alert(msg);
return false;
}
return true;
}
the html :
<!DOCTYPE HTML >
<html>
<head>
<title> User Registration Page</title>
<link href="UserRegistration.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<form action="UserInfo.html" method="POST" onsubmit="if(validations(this)) return parse(); else return false;">
<div class="name">
Name : <input type="text" id="nam" name="fullName" />
</div>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</body>
</html>

Related

How do I remove a to do list item after it is added

I really tried everything, almost every function in JS. But I cannot remove the list item from the to-do list once it is added. I have tried adding event listeners, onclick=" " etc but nothing works. Can someone please look at my code and tell me what I am doing wrong. Thank You, any help is much appreciated.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</div>
</div>
<script>
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event){
const element = event.target;
if(element.type === "close"){
delete element;
}
}
</script>
</body>
</html>
JS:
$(document).ready(function(){
document.getElementById('addTask').addEventListener("click", function(){
var task = document.getElementById('task').value;
if(task == ""){
alert("You Must Enter A Value!");
}else{
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>' + '<button class="check" >✓</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for(var i = 0; i < button.length;i++){
button[i].addEventListener("click", function(){
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
var check = document.querySelectorAll('.check');
for(var i = 0; i < check.length;i++){
check[i].addEventListener("click", function(){
this.parentNode.style.textDecoration = "line-through";
});
}
});
});
Don't try to concatenate innerHTML strings when you have listeners attached to elements inside, else the listeners will be lost. Instead, append elements properly with appendChild.
delete element won't actually do anything, because element is a variable, not a property of an object - try using .remove() instead, to remove the li (and put the button inside the li so that the HTML is valid).
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.className === "close") {
element.parentElement.remove();
}
}
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task === "") return alert("You Must Enter A Value!");
const li = list.appendChild(document.createElement('li'));
li.textContent = task;
const button = li.appendChild(document.createElement('button'));
button.className = 'close';
button.textContent = '✗';
});
.close {
position: absolute;
left: 150px;
}
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
Your .querySelectorAll() simply needs to target .close rather than close. In addition to this, you'll probably want to target the close button's parent (the item itself), with .parentNode. Note that you probably don't want to hide it, but rather actually simply remove both the <li> and the close icon, so that you can add more items after removal of the item(s). This can be done with:
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
And can be seen working in the following:
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.type === "close") {
delete element;
}
}
$(document).ready(function() {
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task == "") {
alert("You Must Enter A Value!");
} else {
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</body>
</html>
Also note that your stylesheet is missing a closing ", and you have two additional closing </div> that don't match anything in your above code.

Get Items from Textbox to Display after clicking submit

I am trying to get information that I type into a textbox to display in the unordered list I have in my code to the browser. I am also trying to have it display a message after I input 5 items. Please see my code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Hands-on Project 3-4</title>
<link rel="stylesheet" href="styles.css" />
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<header>
<h1>
Hands-on Project 3-4
</h1>
</header>
<article>
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox" />
</fieldset>
<fieldset>
<button type="button" id="button">Submit</button>
</fieldset>
</form>
</article>
<script>
var i = 1;
var listItem = "";
function processInput() {
if (i <= 5) {
listIem = document.getElementById("item" + i).innerHTML = i;
}
}
if (window.addEventListener) {
window.addEventListener("click", processInput, false);
} else if (window.attachEvent) {
window.attachEvent("onclick", processInput);
}
</script>
</body>
</html>
This:
function processInput() {
if (i <= 5) {
listIem = document.getElementById("item" + i).innerHTML = i;
}
}
Should be this:
function processInput() {
if (i <= 5) {
document.getElementById("item" + i).textContent = document.getElementById("toolBox").value;
i++; // increment i here
}
}
Or this (if you want things to be separated):
function processInput() {
if (i <= 5) {
var listItem = document.getElementById("item" + i);
var input = document.getElementById("toolBox");
listItem.textContent = input.value;
i++; // increment i here
}
}
Use .textContent instead of .innerHTML and get the #toolBox input value using .vlaue.
Note: it will be better if you could generate the list items dynamically (check how here).

How to add images that were searched to an array then present them one by one in a slideshow?

I am looking to add images to an array by appending the outputted images based on what was searched. Before I implemented the array code, all of the photos would appear on the page, 15 or so. I hope to add them to an array and them show one at a time by adding a side. That is what I am trying to accomplish now.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="imageSearch.css">
</head>
<body>
<form class="form-inline" id="myForm" action="" method="post">
<div class="form-group">
<input type="text" class="form-control " id="item" name="imageSearch" placeholder="Search for an Image">
</div> <br> <br>
<input class="btn btn-default" type="submit" value="Submit"> <input class="btn btn-default" id="clear" type="button" value="Clear"> <br>
</form>
<div id="output"></div>
<script>
$('#myForm').on('submit', function(e){
e.preventDefault();
search();
return false;
});
function search() {
var images = new Array();
var apiKey = '';
$.ajax(
{
type:'GET',
url:"https://api.gettyimages.com/v3/search/images/creative?phrase=" + $('#item').val(),
beforeSend: function (request)
{
request.setRequestHeader("Api-Key", apiKey);
}})
.done(function(data){
console.log("Success with data")
for(var i = 0;i<data.images.length;i++)
{
images[i].src = " <img src='" + data.images[i].display_sizes[0].uri + "'/>" ;
$("#output").append(images[i]);
}
})
function nextImage(output)
{
var img = document.getElementById("output");
for(var i = 0; i < images.length;i++)
{
if(images[i].src == img.src) // << check this
{
if(i === images.length){
document.getElementById("output").src = images[0].src;
break;
}
document.getElementById("output").src = images[i+1].src;
break;
}
}
}
.fail(function(data){
alert(JSON.stringify(data,2))
});
return false;
}
</script>
<script type="text/javascript">
$("#clear").click(function()
{
$("#output").empty();
});
</script>
</body>
</html>

How to add mutilple dynamic items on listview?

I have two pages.The first page contains form with required fields and also a submit button(with validations).And In the second page Listview should be there. So, when i clicked on the Submit button in first page ,the entire fields should be display on the list.
I have used local storage for saving the data in the second page.It is perfect.But the data is not displaying exactly on the list.And I want to add multiple items dynamically in the firstpage,So that multiple items which are added by me can be seen in second page.
Here are my two pages code.
new.html
<!DOCTYPE HTML >
<html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="./styles/new.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="./js-css/development-bundle/themes/start/jquery.ui.all.css">
<link rel="stylesheet" media="screen" type="text/css" href="js-css/development-bundle/themes/base/jquery.ui.datepicker.css" />
<script type="text/javascript" src="js-css/development-bundle/jquery-1.10.2.js"> </script>
<script type="text/javascript" src="js-css/development-bundle/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="js-css/development-bundle/ui/jquery.ui.datepicker.js"></script>
<script type="text/javascript">
$(function(){
var pickerOpts = {
appendText: "",
defaultDate: "+5",
showOtherMonths: true,
dateFormat: "dd/mm/yy",
};
$("#strtd").datepicker({
minDate: 0
});
$("#sub").datepicker({
maxDate: new Date,
minDate: new Date(2007, 6, 12)
});
$('#strtd').focus(function() {
this.blur();
});
$('#sub').focus(function() {
this.blur();
});
});
function back() {
window.open("file:///android_asset/www/index.html");
}
//form validation
function validateForm() {
localStorage.setItem("RecordName", document.myForm.RecordName.value);
localStorage.setItem("StartedDate", document.myForm.StartedDate.value);
localStorage.setItem("SubmitedDate", document.myForm.SubmitedDate.value);
var x = document.forms["myForm"]["name"].value;
var y= document.forms["myForm"]["strtd"].value;
var z= document.forms["myForm"]["sub"].value;
if (x==null || x=="") {
alert("Record name must be filled out");
return false;
}
else if (y==null || y=="") {
alert("Started Date must be filled out");
return false;
}
else if (z==null || z=="") {
alert("Submitted Date must be filled out");
return false;
}
else {
alert("New Record Created");
}
}
</script>
</head>
<body>
<form name="myForm" id="form" type="get" onsubmit="return validateForm()" action="lead.html">
<div id="top"> New Record</div>
<div>
<h5>Record Name <input type="text" name="RecordName" id="name"></h5>
</div>
<div >
<h5>Started Date <input id="strtd" type="text" name="StartedDate"></h5>
</div>
<div>
<h5>Submitted Date <input id="sub" type="text" name="SubmitedDate"></h5>
</div><br>
<div align="center">
<input type="submit" id="submit" value="Submit" >
</div>
</form>
<div align="center">
<button id="cancel" onclick="back()">Back</button>
</div>
</body>
</html>
and my second page lead.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./styles/lead.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"> </script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
<script>
function mylead1()
{
window.open("file:///android_asset/www/editlead.html");
}
function mylead2()
{
window.open("file:///android_asset/www/editlead.html");
}
function mylead3()
{
window.open("file:///android_asset/www/editlead.html");
}
function onBackKey()
{
window.open("file:///android_asset/www/new.html");
}
</script>
</head>
<body id="lead">
<div id="top" align="center" > Leads </div>
<img id="plus" src="./images/plus.png" onclick="onBackKey()" >
<div data-role="page" style="margin-top:100px;" >
<div data-role="main" id="content" style="min-height:60px;">
<ul id="unorder" data-role="listview" data-theme="a" data-dividertheme="b">
<li id="list" data-role="list-divider">
<label id="label1" > </label><br>
<label id="label2"></label><br>
<label id="label3"></label>
<img id="arrow" src="./images/Arrow#2x.png" style="margin-left:250px" onclick="mylead1()">
</li>
</ul>
</div>
</div>
</body>
<script>
//local storage
document.getElementById("label1").innerHTML= localStorage.getItem("RecordName");
document.getElementById("label2").innerHTML= localStorage.getItem("StartedDate");
document.getElementById("label3").innerHTML= localStorage.getItem("SubmitedDate");
</script>
<script>
$("#submit").click( function() {
$("ul").append("<li></li>").listview("refresh");
li.text("#label1");
$("#unorder").append(li);
$("#unorder").listview("refresh");
})
</script>
</html>
My requirement is to get the added data(in new.html) dynamically on second page(lead.html)
`Please guide me for resolving it.Thanks :)
local storage is working fine , so m not focusing on it.
Here concern is displaying all data from first page in second that too in list format
this is the most simplest way to do this,
ON FIRST PAGE
on form submit suppose you are calling one function name redirect
function redirect()
{
var form = $("form[name='myForm']");
form_data = form.serialize();
window.location = "secondpage.html?"+form_data // eg: secondpage.html?single=Single2&multiple=Multiple&multiple=Multiple3&radio=radio1
}
ON SECOND PAGE
function which will parse url and give parameters as objects
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
var url = window.location.href ; //'www.example.com?ferko=suska&ee=huu';
var parameters = $.parseParams( url.split('?')[1] || '' ); // object { ferko: 'suska', ee: 'huu' }
var li='';
$.each( parameters, function( key, value ) {
// write html code
li += "<li>"+value+"</li>"
});
$("ul").html(li);
<ul>
</ul>

Clear the output area

I have here a working code that lets the user input something and it displays the output right away, but I want to create a function triggered by a button that would clear the output area itself. Is this possible with my code?
Here is my complete code:
<html>
<meta charset="UTF-8">
<head>
<title>Sample Array</title>
<script>var index = 0;</script>
</head>
<body>
Input:
<input type="text" id="input">
<input type="button" value="GO" onClick="press(input.value)">
<p id = "display">
<script>
var sample = new Array();
function press(Number)
{
if ( Number != '' )
{
sample[index] = Number;
document.getElementById("display").innerHTML += sample[index] + "<br>";
index++;
}
else
alert("empty");
document.getElementById('input').value = '';
}
</script>
</body>
</html>
Try this,
Javascript:
function Clean(){
document.getElementById('display').innerHTML='';
}
HTML:
<input type="button" value="Clean" onClick="Clean()"/>
Do this:
Notes:
-I have closed the P element.
-A new button was added "Clean" and you can use JQuery as it is shown below to clean the output (remember to have JQuery referenced in your page).
<html>
<meta charset="UTF-8">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Sample Array</title>
<script>var index = 0;</script>
</head>
<body>
Input:
<input type="text" id="input" />
<input type="button" value="GO" onClick="press(input.value)"/>
<input type="button" value="Clean" onClick="$('#display').html('');"/>
<p id = "display"></p>
<script>
var sample = new Array();
function press(Number)
{
if ( Number != '' )
{
sample[index] = Number;
document.getElementById("display").innerHTML += sample[index] + "<br>";
index++;
}
else
alert("empty");
document.getElementById('input').value = '';
}
</script>
</body>

Categories

Resources