Splitting a Javascript Variable into an html table - javascript

I am unable to split a variable that holds 5 fields from a form into a table in 5 different sections of the same row. I would appreciate any assistance.
// The section below this line is where the variable from the form input
// is inserted, but the role is not split into 5 different cells.
function getInfo() {
var info = document.getElementById("form1");
var text = "";
var i;
for (i=0; i < info.length; i++) {
text += info.elements[i].value;
}
document.getElementById("data").innerHTML = text;
// Log the form input into the console
console.log(text);
}
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
<!-- JQuery styling and CDN files -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- Form HTML -->
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<p>Click the button below to display your entry.</p>
<!-- Javascript button to capture and display the input -->
<button onclick="getInfo()">Try it</button>
<table style="width:100%">
<tr>
<th>First Name</th>
</tr>
<tr id ="data">
</tr>
</table>

If you want the data into different columns, you have to create the columns and append them to a row.
You do not want to concatenate the data into a single var, because you want to keep the data split up into columns.
You could do this:
function getInfo() {
const info = document.getElementById("form1");
const row = document.getElementById("data");
for (let i =0; i < info.length; i++) {
// Make a new column
const col = document.createElement('td');
// Make a new text node
const colText = document.createTextNode(info.elements[i].value);
// Append text to column
col.appendChild(colText);
// Append column to the row (id of data)
row.appendChild(col);
}
}

You need to add the table cell markup to your string, given your current approach.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- JQuery styling and CDN files -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- Custom css -->
<style>
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
</style>
<title>My Web Page</title>
</head>
<body>
<!-- Form HTML -->
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
<tr id ="data">
</tr>
</table>
<!-- Javascript function for the user input -->
<script type="text/javascript">
function getInfo() {
var info = document.getElementById("form1");
var text = "";
var i;
for (i=0; i < info.length; i++) {
text += "<td>"+info.elements[i].value+"</td>";
}
document.getElementById("data").innerHTML = text;
// Log the form input into the console
console.log(text);
}
</script>
<p>Click the button below to display your entry.</p>
<!-- Javascript button to capture and display the input -->
<button onclick="getInfo()">Try it</button>
</body>
</html>

Used the following methods, properties, and API:
HTMLFormControlsCollection
Array.from()
forEach()
.insertCell()
.textContent
Demo
Details are commented in Demo
function distData(e) {
//HTMLFormControlsCollection
var F = document.forms.form1;
var x = F.elements;
//Convert Collection into an array
var fieldArray = Array.from(x);
console.log(fieldArray);
//Reference tr#data
var R = document.getElementById('data');
//Each input in array will...
fieldArray.forEach(function(field, index) {
//Check if input has a value
if (field.value.length > 0) {
//Create a <td> snd insert it into R
var cell = R.insertCell(index);
//Copy the input value into cell
cell.textContent = field.value;
} else {
//if form control has no value ignore it
console.log('field has no value');
}
});
return false;
}
table {
margin: 0 auto 20px
}
table,
td {
border: 3px inset grey
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<style>
div.ui-input-text {
width: 200px
}
button {
width: 200px
}
</style>
</head>
<body>
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br> Last name: <input type="text" name="lname" id="lname1" required><br> Address: <input type="text" name="th>" id="address1" required><br> City: <input type="text" name="city" id="city1"
required><br> State: <input type="text" name="state" id="state1" required><br>
<button onclick='distData()' type='button'>DATA</button>
</form>
<p>Click the button below to display your entry.</p>
<table style="width:100%">
<tr>
<th colspan='2'>Name</th>
<th colspan='3'>Location</th>
</tr>
<tr>
<th>First</th>
<th>Last</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
The section below this line is where the variable from the form input is inserted, but the role is not split into 5 different cells.
<tr id="data">
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</body>
</html>

The problem is that you are concatenating each field into a string; there is no delimiter in the string so there is no logical way to break it up. What you want to do instead is store each field in an array, then you can iterate over that to build up a HTML string, or better yet just use Array.prototype.join() to create the HTML for the cells you are creating.
function getInfo() {
var info = document.getElementById("form1");
var fields = []; // create an empty array
var i;
for (i=0; i < info.length; i++) {
fields.push(info.elements[i].value);
}
document.getElementById("data").innerHTML = '<td>' + fields.join('</td><td>') + '<td>';
}
document.getElementById('try-it').addEventListener('click', getInfo, false);
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<p>Click the button below to display your entry.</p>
<button id="try-it">Try it</button>
<table style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
<tr id ="data">
</tr>
</table>
This will work, but it produces a table that can only have one row of data in it; every time you hit "Try It" the existing data will be replaced. To add more than one row, instead of targeting a particular row and inserting cells into it, create an entire row and append it to the table. Since you are already using jQuery, I'm using it in the below example.
function getInfo() {
// Create an array containing the values of all of the fields.
// First, select all of the input elements inside of the form,
// Then, use .map() to extract their values, finally use .get() to
// turn the jQuery object into an array.
var fields = $('#form1 input').map(function () {
return this.value;
}).get();
// create a new row and append it to the table.
$('#display-table').append('<tr><td>' + fields.join('</td><td>') + '<td></tr>');
}
// instead of using in-line event handlers, attach it in your code.
$('#try-it').on('click', getInfo);
div.ui-input-text { width: 200px !important;}
button { width: 200px !important; }
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<form id="form1">
First name: <input type="text" name="fname" id="fname1" required><br>
Last name: <input type="text" name="lname" id="lname1" required><br>
Address: <input type="text" name="address" id="address1" required><br>
City: <input type="text" name="city" id="city1" required><br>
State: <input type="text" name="state" id="state1" required><br>
</form>
<p>Click the button below to display your entry.</p>
<button id="try-it">Try it</button>
<table id="display-table" style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
</tr>
</table>
More resources
jQuery API reference main page
jQuery learning center
.map()
.append()
.get()
Array.prototype.push

Related

How to delete an object from array on Button click?

I'm trying to perform a static crude operation. When user add a details on textbox it will stores in array of object and then that object print on table. Now I want to delete the row by delete button from array. I tried .splice() but it isn't working. The data is deleting from table but I want to delete it from array. I'm providing my page below:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table With Bootstrap</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body><br><br><br>
<div class="container">
<h1 align="center">Enter Details</h1><br>
<div class="row">
<div class="col-sm-4">
<!--style="border:solid"-->
<div>
<label>Enter ID: </label><br>
<input type="number" class="form-control" id="id" name="id" required/>
<label>Enter Name: </label><br>
<input type="text" class="form-control" id="name" name="name" required/>
<label>Enter City: </label><br>
<input type="text" class="form-control" id="city" name="city" required />
<label>Enter Email: </label><br>
<input type="email" class="form-control" id="email" name="email" required/><br>
<button class="btn btn-success" onClick="printTable();">Submit</button> <button class="btn btn-danger" onClick="resetTable();">Reset Table</button></div>
</div>
<div class="col=sm-4">
<h1 style="color: white">Hello World heyy</h1>
</div>
<div class="col-sm-4" style="float: right;">
<table class="table table-sm table-striped table-hover table-bordered" style="border-radius: 5px;">
<thead class="thead-dark">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>User Email</th>
<th>User City</th>
<th>User Delete</th>
</tr>
</thead>
<tbody id="showResult">
</tbody>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
let data = [];
function resetTable() {
const confirmMessage = confirm("Are you sure want to reset table data? It will delete all data from table. You cannot undo this action.!");
if (confirmMessage) {
window.location.reload();
alert("Table Data Cleared Successfully");
} else {
alert("cancelled.!");
}
}
function printTable() {
const getId = document.getElementById("id").value;
const getName = document.getElementById("name").value;
const getCity = document.getElementById("city").value;
const getEmail = document.getElementById("email").value;
if (getId != '', getName != '', getCity != '', getEmail != '') {
const obj = {
id: getId,
name: getName,
city: getCity,
email: getEmail
}
data.push(obj);
print(data);
$('#id').val("");
$('#name').val("");
$('#city').val("");
$('#email').val("");
} else {
alert("All feilds are Mandatory..");
}
}
function print(data) {
let result = '';
for (let i = 0; i < data.length; i++) {
result += `
<tr id='row'>
<td>${data[i].id}</td>
<td>${data[i].name}</td>
<td>${data[i].email}</td>
<td>${data[i].city}</td>
<td><input type='button' onclick='deleteRow(this);' class='btn btn-danger' value='Delete'/></td>
</tr>`;
document.getElementById('showResult').innerHTML = result;
}
}
function deleteRow(btn) {
var cnfrmMessage = confirm("Are you sure want to Delete selected data? You cannot undo this action.");
if (cnfrmMessage == true) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
} else {
alert("Cancelled..!!");
}
}
</script>
</body>
</html>
I think you forget update your data array.
Change your deleteRow function to
function deleteRow(btn) {
var cnfrmMessage = confirm("Are you sure want to Delete selected data? You cannot undo this action.");
if(cnfrmMessage == true){
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
// update your data (remove item by row id)
data = data.filter((item)=>item.id!==$(row).children()[0].innerText);
}
else{
alert("Cancelled..!!");
}
}
Your array is literally a 'data'. So you need a unique id for delete specific row or do something on this.
Other way, you can compare all fields in that row you want to delete, but it's not a good solution.
You need a way to identify the item in the list going off of the HTML element. Looks like you can use the id column (although usually it would be better to put something like that in an attribute). Then you can use filter:
Add the id to the deleteRow function.
deleteRow(this, ${data[i].id})
// Removes item with id.
var a = [
{id:1},
{id:2},
{id:3},
{id:4},
{id:5},
{id:6},
{id:7},
{id:8},
{id:9}
];
a.filter(item => item.id != deleteId);

Calculate a table column

I am looking to calculate a column within a table that is being created. I need the sum field to add up the values created from the form, which is created new rows for the table upon submit. Any way I can get the to add up the column sum? Each time a function updatetable() is run is creates another table row, and these are the rows I need calculated...currently the column holds a "184" as a holding place for where the calculation would take place.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>The real test</title>
<link rel="stylesheet" href="html_testing.css">
<script type="text/javascript"> <!--
var tabBody, row, cell;
function updateTable(){
tabBody=document.getElementById("joe$");
row=document.createElement("tr");
row.setAttribute("id","js");
cell = document.createElement("td");
cell.innerHTML=document.forms['leds'].elements[2].value;
row.appendChild(cell);
if(tabBody.childNodes.length==17)
tabBody.removeChild(tabBody.childNodes[0])
tabBody.appendChild(row);
}
function updateTable1(){
tabBody=document.getElementById("joe");
row=document.createElement("tr");
cell = document.createElement("td");
cell.innerHTML=document.forms['leds'].elements[3].value;
row.appendChild(cell);
if(tabBody.childNodes.length==17)
tabBody.removeChild(tabBody.childNodes[0])
tabBody.appendChild(row);
}
function myFunctionJoe(){
updateTable();
updateTable1();
}
function moneymoney(){
('#joe$ tr:first td').each(function(){
var $td = $(this);
var colTotal = 0;
$('#joe$ tr:not(:first,.totalColumn)').each(function(){
colTotal += parseInt($(this).children().eq($td.index()).html(),10);
});
$('#joe$ tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});
}
</script>
<body>
<h2>Legion of Roar:</h2>
<form name="leds" id="ledSend" action="" onsubmit="return false;">
Lamp Control: <input type="radio" name="led" value="0" checked />Off
<input type="radio" name="led" value="1" />On<br>
Winning Bid: <input type="text" name="timer" placeholder="Bid..." /><br>
Player Drafted: <input id="name" type="text" name="user" placeholder="Player Name..." /><br>
Player Position: <input id="name" type="text" name="user" placeholder="Position..." /><br>
<br>
<input type="submit" value="Joe" onclick="myFunctionJoe();"/>
<h1>Testing some skills</h1>
<fieldset>
<table border ='1' class="inlineTable">
<thead><tr><th>Joe</th></tr></thead>
<thead><tr><th>200</th></tr></thead>
<tr class="totalColumn">
<td class="totalCol">Spent:</td>
</tr>
<tbody id="joe"><tbody>
</table>
<table border ='1' class="inlineTable">
<thead><tr><th>$</th></tr></thead>
<thead><tr><th>184</th></tr></thead>
<tr class="totalColumn">
<td class="totalCol">Spent:</td>
</tr>
<tbody id="joe$"><tbody>
</table>
</body>
</html>

input-field not refresh after receiving value

The entire process of collecting data from the first input-field and shipping to second input-field2 is working perfectly but so that the value actually goes to the second input-field i must delete some letter from first input-field and re-enter some number so that the value actually goes to second-input.
Gif of doubt.
$(document).ready(function () {
$(function () {
var $cepAddressRouteTransporterGoogleMaps = $('#postal_code');
var $cepAddressRouteTransporter = $('#cepAddressRouteTransporter');
function onChange() {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
};
$('#postal_code')
.change(onChange)
.keyup(onChange);
});
});
First input represents this field postal_code & Second input represents this field cepAddressRouteTransporter.
<form action="transporter/route" method="post" role="form">
<table id="address">
<tr>
<td class="label">Zip code</td>
<td class="wideField">
<input class="field" id="postal_code" name="postal_code">
</td>
</tr>
</table>
<div class="input-field col s6">
<i class="material-icons prefix">directions</i>
<input placeholder="Ex: 18214-780" id="cepAddressRouteTransporter" name="cepAddressRouteTransporter" type="text" class="validate">
<label for="cepAddressRouteTransporter">CEP:</label>
</div>
</form>
Thanks for help!
you have to call your function onChange when the DOM is ready
onChange();
when you update the value, trigger the DOM event.
$('#postal_code').trigger('change');
$(function() {
var $cepAddressRouteTransporterGoogleMaps = $('#postal_code');
var $cepAddressRouteTransporter = $('#cepAddressRouteTransporter');
function onChange() {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
};
$('#postal_code').change(onChange).keyup(onChange);
// fire as soon as DOM is ready
onChange();
var t = window.setInterval(function(){
var n = Math.floor(Math.random() * 100000);
$('#postal_code').val(n);
// when you update the value, trigger the DOM event
$('#postal_code').trigger('change');
},1000);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<form action="transporter/route" method="post" role="form">
<table id="address">
<tr>
<td class="label">Zip code</td>
<td class="wideField">
<input class="field" id="postal_code" name="postal_code" value="90210">
</td>
</tr>
</table>
<div class="input-field col s6">
<i class="material-icons prefix">directions</i>
<input placeholder="Ex: 18214-780" id="cepAddressRouteTransporter" name="cepAddressRouteTransporter" type="text" class="validate">
<label for="cepAddressRouteTransporter">CEP:</label>
</div>
</form>
</body>
</html>
#code_monk Thanks for your help, i've reshaped your recommendation and add a few new things.
$(function () {
var $cepAddressRouteTransporterGoogleMaps = $('#postal_code');
var $cepAddressRouteTransporter = $('#cepAddressRouteTransporter');
function onChange() {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
};
$cepAddressRouteTransporterGoogleMaps.change(onChange).keyup(onChange);
$cepAddressRouteTransporter.change(onChange).keyup(onChange);
onChange();
var refresh = window.setInterval(function () {
$cepAddressRouteTransporter.val($cepAddressRouteTransporterGoogleMaps.val());
}, 3000);
});

Replacing onClick() with addEventListener()

Converting oclick() with addEventListener(), i have tried multiple times, But no Success. Can anyone help please. i have read in the book, that onlick() is not w3 standard, Any help will highly be aprreciated
Before with onclick() working Perfectly:
html code
<!DOCTYPE html>
<html>
<head>
<title>Splitting number</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form id="myForm" action="" name="myForm">
<table border="1">
<tr>
<td>Enter a phone number<br> [in the form (555) 555-5555]</td>
<td><input name="input" type="text" size="40"></td>
</tr>
<tr>
<td><input type="button" value="Split" onclick="parseNumber()"></td>
</tr>
<tr>
<td>Area code:</td>
<td><input name="areaCode" type="text" size="5"></td>
</tr>
<tr>
<td>Number:</td>
<td><input name="number" type="text" size="8"></td>
</tr>
</table>
</form>
</body>
</html>
javascript code:
function parseNumber() {
var myForm = document.getElementById( "myForm" );
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
myForm.areaCode.value = areaCode;
myForm.number.value = tokens2[0] + "-" + tokens2[1];
}
after, Not working:
html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Splitting number</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
Enter a phone number: in the form (555) 555-5555]
<input name="input" type="text" size="40" id="number" ><br>
<input type="button" value="Split" id="myBtn"><br><br>
Area code: <input name="areaCode" type="text" size="5" id="areaCode"><br>
Number: <input name="number" type="text" size="8" id="anotherNumber">
</body>
</html>
javascript code
var completeNumber = document.getElementById("number");
x = document.getElementById( "myBtn" );
function parseNumber() {
x.addEventListener("click", parseNumber);
completeNumber.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
document.getElementById("areaCode").innerHTML = areaCode.toString();
document.getElementById("anotherNumber").innerHTML = tokens2[0].toString() + "-" + tokens2[1].toString();
}
You need to add the event listener outside the function.
The listener is listening (clues in the name) for a mouse 'click' event on that element. When the event happens i.e you click on the element, it calls the function that it is assigned, in your case: parseNumber.
So since you are adding the event listener inside the function, it never gets added (as the function never gets called).
It should all work if you move the lines:
var x = document.getElementById( "myBtn" );
x.addEventListener("click", parseNumber);
outside the function. :)
I thnik no one actually read the question, if you already had a working example then changing onclick to eventListener is no problem:
var parseNum = document.getElementById('parse-number');
function parseNumber() {
var myForm = document.getElementById( "myForm" );
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
myForm.areaCode.value = areaCode;
myForm.number.value = tokens2[0] + "-" + tokens2[1];
}
parseNum.addEventListener("click", parseNumber);
<form id="myForm" action="" name="myForm">
<table border="1">
<tr>
<td>Enter a phone number<br> [in the form (555) 555-5555]</td>
<td><input name="input" type="text" size="40"></td>
</tr>
<tr>
<td><input type="button" value="Split" id="parse-number"></td>
</tr>
<tr>
<td>Area code:</td>
<td><input name="areaCode" type="text" size="5"></td>
</tr>
<tr>
<td>Number:</td>
<td><input name="number" type="text" size="8"></td>
</tr>
</table>
</form>
Change your code to this where eventListener is added outside the bounded function. Otherwise it will repeatedly bind an eventListener to the button.
Also place your script.js on the bottom of the HTML page. Because when the script executed the DOM element is not found since the DOM is not rendered at the script execution time.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Splitting number</title>
</head>
<body>
Enter a phone number: in the form (555) 555-5555]
<input name="input" type="text" size="40" id="number" ><br>
<input type="button" value="Split" id="myBtn"><br><br>
Area code: <input name="areaCode" type="text" size="5" id="areaCode"><br>
Number: <input name="number" type="text" size="8" id="anotherNumber">
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript
var completeNumber = document.getElementById("number");
var x = document.getElementById( "myBtn" );
function parseNumber() {
completeNumber.replace(/\s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
document.getElementById("areaCode").innerHTML = areaCode.toString();
document.getElementById("anotherNumber").innerHTML = tokens2[0].toString() + "-" + tokens2[1].toString();
}
x.addEventListener("click", parseNumber);

JavaScript - How to place asterisk in the right side of the text box?

I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.
This is my code:
[<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>
<style type="text/css">
body { font-family:arial, helvetica, sans-serif; font-weight:bold; font-size:13px; color:#000; text-align:left; margin:3px 0px; }
input { text-align:center; border:2px solid #CCC; }
#wrap { width:400px; height:200px; margin:20px; padding:10px; }
#une { margin-top:10px; }
#reg {margin-top:10px; }
.a13B { color:#F00; }
.cntr { text-align:center; }
</style>
</head>
<body>
<div id="wrap">
<form id="regform" name="registerationform" method="POST">
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" width="300">
<tr>
<td>First Name: </td>
<td class="cntr">
<input type="text" name="fnametxt" size="20"></td>
</tr>
<tr>
<td>Second Name: </td>
<td class="cntr">
<input type="text" name="snametxt" size="20"> </td>
</tr>
<tr>
<td>User Name:</td>
<td class="cntr">
<input type="text" name="unametxt" size="20"> </td>
</tr>
<tr>
<td>Email Address: </td>
<td class="cntr">
<input type="text" name="emailtxt" size="20"> </td>
</tr>
<tr>
<td>Password : </td>
<td class="cntr"><input type="password" name="pwdtxt" size="20"> </td>
</tr>
<tr>
<td>Confirm : </td>
<td class="cntr"><input type="password" name="cpwdtxt" size="20"> </td>
</tr>
</table>
<input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
</form>
<div id="une" class="a13B">
</div>
</div>
<!-- end wrap -->
<script type="text/javascript">
var uneObj=document.getElementById("une"); // object ref to msg line
var currentBrdObj;
//
function regvalidate(formObj)
{ uneObj.innerHTML=""; // clear msg line before resubmitting
// gather object ref to input boxes
var allInputs=document.getElementById("regform").getElementsByTagName("input");
// check if value of box is ""
for(var i=0;i<allInputs.length;i++)
{ if(allInputs\[i\].name !="reg") // ignore submit button
{ if(allInputs\[i\].value=="")
{ uneObj.innerHTML=msg\[i\];
if(currentBrdObj){currentBrdObj.style.border="2px solid #CCC"; }
allInputs\[i\].style.border="2px solid #F00";
currentBrdObj=allInputs\[i\];
allInputs\[i\].onclick=function(){ this.style.border="2px solid #CCC"; }
return;
} } }
// check if password and confirm are the same
if((formObj.pwdtxt.value) != (formObj.cpwdtxt.value))
{ uneObj.innerHTML = msg\[msg.length-1\]; // last msg in array
formObj.pwdtxt.value = ""; formObj.pwdtxt.style.border="";
formObj.cpwdtxt.value = ""; formObj.cpwdtxt.style.border="";
return;
}
// all ok so submit form
uneObj.innerHTML = "All ok so submitting form";
formObj.submit();
}
// -----
var msg =\["*","*",
"*","*",
"*","*"\];
msg\[msg.length\]="Passwords must be equal.<br>Please type a password";
//
</script>
</body>
</html>][1]
#PawanKumar
Here is your code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#submitBtn').on('click', function(e) {
debugger;
e.preventDefault();
var fields = document.getElementsByTagName('input');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('required')) {
if (fields[i].value == "") {
fields[i].classList.add('redBorder');
$(fields[i]).after('*');
} else {
fields[i].classList.remove('redBorder');
}
}
}
});
});
</script>
<style>
.redBorder {
border: 2px solid red;
border-radius: 2px;
}
</style>
</head>
<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>
</html>
Use span element to display asterisk at the end of text box. Try this :
<input type="text" id="name"/> <span style="color:red"> * </span>
Hope this solves your requirement.
Why bother with all that mess?
<input type="text" name="fnametxt" required />*
<input type="email" name="emailtxt" required />*
<input type="submit" value="Register" />
JavaScript required: none at all
With the help of jquery after() method, you can achieve this.
$(fields[i]).after("<span class='redColor'>*</span>");
I have also added code to show red border for required input field.
Note: If you use <form> tag, then HTML5 will automatically does the validation and your script will not execute, so to prevent that use novalidate attribute in the form tag or just remove the form tag.
$(document).ready(function() {
$('#submitBtn').on('click', function(e) {
e.preventDefault();
var fields = document.getElementsByTagName('input');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('required')) {
if (fields[i].value == "") {
fields[i].classList.add('redBorder');
$(fields[i]).after("<span class='redColor'>*</span>");
} else {
fields[i].classList.remove('redBorder');
}
}
}
});
});
.redBorder {
border: 2px solid red;
border-radius: 2px;
}
.redColor{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>

Categories

Resources