Change element between cells of a table - javascript

I'm creating a table with two fields, and I'm trying to do:
When I register an user, the username will be displayed, with this username when I click a button, the cell field will be filled with the username and the button will be hidden (ok until now).
When I click on the button of the second cell, this data will be passed to that cell and the past cell will be reset to the first name.
This second part I'm trying but seems impossible, what I can do for solve this?
<script>
var list = document.getElementById('users');
function addUser(){
var username = document.getElementById('username').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username));
list.appendChild(entry);
return false;
}
var hidden = false;
function teste(){
hidden = !hidden;
if(hidden) {
document.getElementById('testebut').style.visibility = 'hidden';
var coe = document.getElementById('username').value;
document.getElementById('lbl1').innerHTML = "user: " + coe;
} else {
document.getElementById('testebut2').style.visibility = 'visible';
}
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<html>
<head>
</head>
<body>
<fieldset>
<form id="myform" onsubmit="return addUser()">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name"/>
<input id="email" type="email" name="email" placeholder="email"/>
<button type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
</fieldset>
<table>
<tr>
<th>User</th>
<th>User</th>
</tr>
<tr>
<td id="lbl1">---<button id="testebut" onClick="teste();">X</button></td>
<td id="lbl2">---<button id="testebut2">X</button></td>
</tr>
</table>
</body>
</html>

I have made several changes to your code to achieve what in my opinion is you needed. Instead of events in HTML I created some event listeners using JavaScript. I hope this is of help to you.
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<fieldset>
<form id="myform" >
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name"/>
<input id="email" type="email" name="email" placeholder="email"/>
<button type="submit" id="addUserBtn">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
</fieldset>
<table>
<tr>
<th>User</th>
<th>User</th>
</tr>
<tr>
<td>
<span id="lbl1">---</span>
<button id="testebut">X</button>
</td>
<td>
<span id="lbl2">---</span>
<button id="testebut2">X</button>
</td>
</tr>
</table>
</body>
</html>
<script>
var list = document.getElementById('users');
if ( document.getElementById( "addUserBtn" ) ) {
document.getElementById( "addUserBtn" ).addEventListener( "click", function( e ) {
//prevent the page from reloading and add the user to the list
e.preventDefault();
addUser();
});
}
function addUser(){
var username = document.getElementById('username').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username));
list.appendChild(entry);
}
//get all the teste buttons
let testeButtons = document.querySelectorAll( "button[id^='testebut']" );
//add event listener to all the teste buttons
for ( let i = 0; i < testeButtons.length; i++ ) {
testeButtons[ i ].addEventListener( "click", function( e ) {
teste( e.target.id );
});
}
function teste( id ){
let resetField = "---";
//this will only get the last username in the list
let userName = document.getElementById('username').value;
//check if clicked button is testebut and that it's not hidden
//then add the user name to the field and reset the other field
if ( id === "testebut" ) {
document.getElementById( "lbl1" ).innerHTML = "user: " + userName;
document.getElementById( "lbl2" ).innerHTML = resetField;
} else if ( id === "testebut2" ) {
document.getElementById( "lbl2" ).innerHTML = "user: " + userName;
document.getElementById( "lbl1" ).innerHTML = resetField;
}
}
</script>

Related

Data inserted into a form disappears on form submit

I'm trying to insert data through the following JavaScript code. The data inserted, however, disappears from the table when I click Submit.
Here's my code:
let myform = document.querySelector("form");
let myFN = document.getElementById("fname");
let myLN = document.getElementById("lname");
let MyPar = document.querySelector("p");
let submit = document.getElementById("submit");
myform.addEventListener("submit", (e) => {
if (myFN.value === "" || myLN.value === "") {
e.preventDefault();
MyPar.textContent = 'you need to fill all';
}
});
myform.addEventListener("submit", function() {
document.getElementById("table").style.display = "block";
// trigger the table form page
let table = document.getElementById("table");
let row = table.insertRow(-1);
let fname1 = row.insertCell(0);
let lname1 = row.insertCell(1);
fname1.innerHTML = document.getElementById("fname").value;
lname1.innerHTML = document.getElementById("lname").value;
});
table {
display: none;
}
table,
td {
border: 1px solid black;
}
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" />
</div>
<div>
<input id="submit" type="submit" />
</div>
</form>
<p></p>
<table id="table">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>
First, you should remove the event listener that checks whether or not the input fields are blank. You instead can use required for the input tags in the HTML because it has a built-in form validation.
Then, all you need to do is remove the if statement around the e.preventDefault() so it is executed every time the button is clicked.
let myform = document.querySelector("form");
let myFN = document.getElementById("fname");
let myLN = document.getElementById("lname");
let MyPar = document.querySelector("p");
let submit = document.getElementById("submit");
myform.addEventListener("submit", (e) => {
e.preventDefault();
});
myform.addEventListener("submit", function() {
document.getElementById("table").style.display = "block";
// trigger the table form page
let table = document.getElementById("table");
let row = table.insertRow(-1);
let fname1 = row.insertCell(0);
let lname1 = row.insertCell(1);
fname1.innerHTML = document.getElementById("fname").value;
lname1.innerHTML = document.getElementById("lname").value;
});
table {
display: none;
}
table,
td {
border: 1px solid black;
}
<form>
<div>
<label for="fname">First name: </label>
<input id="fname" type="text" required />
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" type="text" required />
</div>
<div>
<button id="submit">Submit</button>
</div>
</form>
<table id="table">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</table>

HTML formular JavaScript

I have a problem with JavaScript. When I push the "Add" button I want to create a table with the listings from the form.
So for example:
New course: name: A, content: B => Add
|name|content
| A | B
And every new record comes to the end of the table.
Do you have an idea how can I do this? With PHP I would be easy but I want to do it with JavaScript.
My idea is to add this code into script:
document . addEventListener( 'DOMContentLoaded', registerCallbacks ); function registerCallbacks( ) { var addButton = document.getElementById( 'add‘ ); addButton.addEventListener( 'click', function( evt ){ add( ); evt.preventDefault( ); } );
document.addEventListener('DOMContentLoaded', registerCallbacks);
function registerCallbacks() {
var addButton = document.getElementById('add‘ ); addButton.addEventListener( '
click ', function( evt ){ add( ); evt.preventDefault( ); } );
<html>
<body>
<form id="new">
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"></input><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add"> Add </button>
</form>
<script>
</script>
</body>
</html>
So step one is to activate the button:
// Here we call the function Add() if someone clicks the button.
<button id="add" onclick="Add()"> Add </button>
Now we want to add the Javascript function Add() to our script:
function Add() {
// We request here all the information what the user fill out.
}
So here is a working snippet:
let table = document.getElementById("table");
function Add() {
// We request here all the information what the user fill out.
let name = document.getElementById("name").value,
content = document.getElementById("content").value;
// Add to table
table.innerHTML += "<tr><td>" + name + "</td><td>" + content + "</td></tr>"
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 3px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add" onclick="Add()"> Add </button>
<table id="table">
<tr>
<th>Lecture</th>
<th>Content</th>
</tr>
</table>
Hope this will work
$(document).ready(function() {
$("#add").click(function(){
var name=document.getElementById("name").value;
var content=document.getElementById("content").value;
$("#table").find('tbody').append("<tr><td class='column'>"+name+"</td><td class='column'>"+content+"</td></tr>");
});
});
<html>
<head>
<title>Add New Row</title>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.head {
border: 1px solid ;
background:#AEB6BF;
}
.column {
border: 1px solid ;
background:#EAEDED;
}
</style>
</head>
<body>
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"></input><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add"> Add </button>
<table id="table" class="head">
<thead>
<tr>
<td>Name</td>
<td>Content</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
</script>
</body>
</html>
Here's a way to achieve it:
var add_button = document.getElementById("add");
var name_field = document.getElementById("name");
var content_field = document.getElementById("content");
var table = document.getElementById("table");
add_button.addEventListener("click", function(e) {
e.preventDefault();
table.style = "display: block;";
table.innerHTML += "<tr><td>" + name_field.value + "</td><td>" + content_field.value + "</td></tr>"
});
<head>
<title>HTML Formular Table</title>
</head>
<body>
<form id="new">
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"></input><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add"> Add </button>
</form>
<table id="table" style= "display: none;">
<tr>
<th>Name</th>
<th>Content</th>
</tr>
</table>

jQuery: Script isn't preventing submit function from firing when form has errors

Essentially, I am trying to have my form clear all input fields on submit if the default values are still present. Then if there are default values still present, then the submit process is stopped. The form clears the fields on submit, but wont stop the submit button from executing like its suppose to. Please help me out on this. I wrote this myself, and still trying to figure out why it isn't working.
The jQuery Script Below:
<script type="text/javascript" >
$(document).ready(function(){
$(".forms").each(function(){
var DefaultValue = $(this).value;
$("#Form_1").submit(function(){
if ( CheckInput() == "empty" ){
return false;
}
});
function CheckInput(){
var x = '';
$(".forms").each(function(){
if ($(this).value == DefaultValue){
this.value = '';
var y = "empty";
return y;
}
x = y;
return x;
});
}
});
});
</script>
The HTML code below:
<form id="Form_1">
<table>
<tr>
<td>
<table cellpadding="2" cellspacing="3" width="500px">
<tr>
<td>
<div class="InputContainer">
<input name="FirstName" value="First Name" class="forms" type="text"required="true" ></input>
<div class="InfoBlurp">First Name<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="BirthDate" value="Birth Date(MM/DD/YYYY)" class="forms" type="text" required="true" ></input>
<div class="InfoBlurp">Birth Date(MM/DD/YYYY)<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="Email" value="Email#sample.com" validType="email" class="forms" type="text" required="true"/></input>
<div class="InfoBlurp">Email#sample.com<div class="InfoTip"></div></div></div>
</td>
</tr>
</table>
<input id="Button_1" class="topopup" type="submit" value="" style="background-color: #FFFFFF; border:none; cursor:pointer;">
</form>
Your checkInput method is not returning anything, you are returning values from the each callback function not from the CheckInput method.
$(document).ready(function () {
$(".forms").each(function () {
var DefaultValue = $(this).value;
$("#Form_1").submit(function () {
if (CheckInput() == "empty") {
return false;
}
});
function CheckInput() {
var x = '';
$(".forms").each(function () {
if ($(this).value == DefaultValue) {
this.value = '';
x = "empty";
//return false to stop further iteration of the loop
return false;
}
});
return x;
}
});
});

How to revert change made by DOM?

So I made a simple javascript form validator which creates a box with the error message using DOM. But I can't figure out a way how to reset all these changes when i reset the form using
<button type="reset">
I would like to know how it's done please.
Thanks.
The Code
<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");
if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}
//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>
<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}
.vis{
display: none;
font-size: 12px;
}
</style>
</head>
<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>
<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">
<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">
<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The browser cannot magically figure out what has to be done to reset the custom changes.
However you can listen to the reset event of the form using element.addEventListener.
DEMO
HTML
<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>
JS
//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');
//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form
//hide the errors container
errorsCt.style.display = 'none';
});
});
If you want to reset the form, as if user hadn't made any selections or added any input, then just set all form element values to their default value, or empty.
jsFiddle
<div>
<form action="/echo/html" method="get">
<input type="text" placeholder="username" />
<br/>
<input type="password" placeholder="password" />
<br/>
<input type="checkbox" value="test" data-default="checked" checked="checked"/>
<br/>
<button type="reset" value="reset" onclick="resetForm()">reset</button>
<br/>
</form>
<div id="err">Some error message</div>
</div>
window.resetForm = function () {
var fields = $('input'),
uname, pass, check;
uname = $(fields.get(0));
pass = $(fields.get(1));
check = $(fields.get(2));
$("#err").text("");
uname.val('');
pass.val('');
if (check.attr("data-default") == "checked") {
check.attr("checked", "checked");
} else {
check.removeAttr("checked");
}
}

Simple input validation and adding values to table

I need to add product info from inputs to table by using jQuery library. I am trying for quite some time now, but I don't get anywhere. First I need to enter data to inputs, select appropriate radio button and than validate input fields. If there are no errors, product info should be added to table. I tried with the following code: jsFiddle
Nothing works as intended tho. What am I doing wrong?
JS code:
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function () {
//Check if any of requested inputs is empty
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").val('Missing product name');
break;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").val('Missing price');
break;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
//Check radio buttons and assign values
if ($('input[value = "true"]'.is(':checked')) {
onStack = "Product available";
} else if ('input[value = "false"]'.is(':checked') {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>$productName</td><td>$price</td><td>$onStack</td></tr>");
});
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<body>
<form method="" action="">
<input type="text" id="name" placeholder="Product name" />
<br />
<input type="text" id="price" placeholder="Price" />
<br/>
<input type="radio" name="stack" value="true">Product available
<br />
<input type="radio" name="stack" value="false">Product not available
<br />
<input type="submit" value="Submit">
</form>
<div id="errors"></div>
<br />
<table border="1">
<tr>
<th>Product name</th>
<th>Price</th>
<th>Stack</th>
</tr>
</table>
<div id="sumOnStack">Sum of available products</div>
<div id="SumNotOnStack">Sum of unavailable products</div>
<input type="button" id="resetForm" value="Reset form" />
<br />
</body>
</html>
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function ( e) {
//Check if any of requested inputs is empty
$("#errors").html('');
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").html('Missing product name');
return false;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").html('Missing price');
return false;
} else if($('input[name="stack"]:checked').length == 0) {
$("#errors").html('Missing product availibility');
return false;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
var stack = $('input[name="stack"]:checked');
console.log( $(stack).val() );
//Check radio buttons and assign values
if ($(stack).val() == 'true') {
onStack = "Product available";
} else {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>"+productName+"</td><td>"+ price +"</td><td>"+ onStack +"</td></tr>");
return false;
});
});
Please try this. Hope above code will help u.

Categories