I need to create a web page as shown below
Below is my current code
function validate() {
var form = document.getElementsByTagName('form')[0];
if (form.tickets.value <= form.childrens.value) {
alert("No of tickets should be greater than the no of children");
return false;
} else if (new Date(form.showdate.value) < new Date()) {
alert("Show date and time should be either current date or future date");
return false;
}
var ticketFare = (form.tickets.value - form.childrens.value) * 200 + form.childrens.value * 100;
alert("Your approximate ticket amount is " + ticketFare + "INR");
return true;
}
.item img {
height: 200px;
width: 200px;
-webkit-transition: all 2s ease;
-moz-transition: all 2s ease;
-ms-transition: all 2s ease;
transition: all 2s ease;
}
.item img:hover {
width: 300px;
height: 300px;
}
<html>
<body>
<h1><b>Movie Ticket Booking</b></h1>
<form action="thankyou.html" onsubmit="alert(validate());">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" placeholder="Enter the name" pattern="[A-za-z\s]+" required> </td>
</tr>
<tr>
<td>Movie Name</td>
<td><input type="text" name="moviename" autocomplete="on" list="movies" required>
<datalist id="movies">
<option value="Irada"></option>
<option value="Rangoon"></option>
<option value="Logan"></option>
<option value="Fist Fight"></option>
</datalist>
</td>
</tr>
<tr>
<td>Circle</td>
<td><input type="text" name="circle" autocomplete="on" list="circles" required>
<datalist id="circles">
<option value="Silver"></option>
<option value="Gold"></option>
<option value="Platinum"></option>
</datalist></td>
</tr>
<tr>
<td>Phone no</td>
<td><input type="text" name="phone" placeholder="Enter mobile # here" pattern="[\d]{10}" required> </td>
</tr>
<tr>
<td>Show date and time</td>
<td><input type="datetime-local" name="showdate" required></td>
</tr>
<tr>
<td>No of tickets</td>
<td><input type="number" name="tickets" min="1" max="10" required></td>
</tr>
<tr>
<td>No of children's</td>
<td><input type="number" name="childrens" min="1" max="5" required></td>
</tr>
<tr>
<td><input type="submit" value="Book My Show"></td>
<td><input type="reset" name="reset"></td>
</tr>
<tr>
<td>
<div class="item">
<img src="contactus.jpg" width="254" height="54">
</div>
</td>
</tr>
</table>
</form>
</body>
Error:
Have provided all the inputs correctly, but the ticket calculation is wrong or The javaScript method is not returning any boolean value
change form.tickets.value to form.getElementsByAttribute('name','tickets')[0].value
You should do the same to the rest of your form elements (showdate, childrens..)
Related
I'm having a very hard time adding HTML to a webpage the way I want to. I'm currently working on a resume creator webpage, but when I click the remove school button while more than 2 schools are listed, the associated javascript removes every school except for the first one. The removeChild function is not working as it is supposed to. My code is listed below. Specifically, if you run the code, then click add school twice, and then click remove school, it will remove Schools 2 and 3, while it should only remove school 3. So something is wrong with my removeSchool function I would think. But nothing is wrong as far as I can tell.
Also, if anyone has any idea of a better way of doing what I'm trying to do, please let me know.
const schools = document.getElementById("schools");
var num_schools = 1;
var add_school_button = `<button id="addschool" onclick="addSchool();">Add School</button>`;
var remove_school_button = `<button id="removeschool" onclick="removeSchool();">Remove School</button>`;
var new_school_html = `<table id="school[]">
<tr>
<td colspan="2" align="center">School []</td>
</tr>
<tr>
<td><label for="schoolname[]">School Name: </label></td><td><input type="text" id="schoolname[]" size="50" /></td>
</tr>
<tr>
<td><label for="schoollocation[]">Location: </label></td><td><input type="text" id="schoollocation[]" size="50" /></td>
</tr>
<tr>
<td><label for="schoolyear[]">Year Graduated: </label></td><td><input type="text" id="schoolyear[]" size="50" /></td>
</tr>
<tr>
<td><label for="schooldegree[]">Degree Earned: </label></td><td><input type="text" id="schooldegree[]" size="50" /></td>
</tr>
</table>`;
function addSchool() {
schools.removeChild(document.getElementById("addschool"));
if (num_schools > 1) {
schools.removeChild(document.getElementById("removeschool"));
}
num_schools++;
schools.innerHTML += new_school_html.replace(/\[\]/g, num_schools.toString());
schools.innerHTML += add_school_button;
schools.innerHTML += remove_school_button;
}
function removeSchool() {
schools.removeChild(document.getElementById("school" + num_schools.toString()));
num_schools--;
if (num_schools == 1) {
schools.removeChild(document.getElementById("removeschool"));
}
}
div {
border: 1px solid black;
}
.maincol {
width: 50%;
}
.maincol>* {
margin-left: 20px;
}
.maincol>h2 {
margin-left: 0px;
}
#schools>table {
margin-bottom: 20px;
}
<h1>Resume Creator</h1>
<form>
<div class="maincol">
<h2>Identifying Information</h2>
<table>
<tr>
<td><label for="name">Full Name: </label></td>
<td><input type="text" id="name" name="name" size="50" /></td>
</tr>
<tr>
<td><label for="address">Address: </label></td>
<td><input type="text" id="address" name="address" size="50" /></td>
</tr>
<tr>
<td><label for="email">Email Address: </label></td>
<td><input type="text" id="email" name="email" size="50" /></td>
</tr>
<tr>
<td><label for="phone">Phone Number: </label></td>
<td><input type="text" id="phone" name="phone" size="50" /></td>
</tr>
</table>
</div>
<div class="maincol">
<h2>Skills</h2>
<p>Enter a comma-separated list of skills. E.g. Guest Services, Loss Prevention, Product Promotion, Etc.</p>
<textarea id="skill_list" rows=4 cols=90></textarea>
</div>
<div class="maincol">
<h2>Education</h2>
<div id="schools">
<table id="school1">
<tr>
<td colspan="2" align="center">School 1</td>
</tr>
<tr>
<td><label for="schoolname1">School Name: </label></td>
<td><input type="text" id="schoolname1" size="50" /></td>
</tr>
<tr>
<td><label for="schoollocation1">Location: </label></td>
<td><input type="text" id="schoollocation1" size="50" /></td>
</tr>
<tr>
<td><label for="schoolyear1">Year Graduated: </label></td>
<td><input type="text" id="schoolyear1" size="50" /></td>
</tr>
<tr>
<td><label for="schooldegree1">Degree Earned: </label></td>
<td><input type="text" id="schooldegree1" size="50" /></td>
</tr>
</table>
<button id="addschool" onclick="addSchool();">Add School</button>
</div>
</div>
</form>
I's thinking of using DOM remove method instead of removeChild method. Since you are already using getElementById so remove will do just fine.
function removeSchool() {
document.getElementById("school" + num_schools.toString()).remove(); // here changed removeChild method to remove
num_schools--;
if (num_schools == 1) {
document.getElementById("removeschool").remove(); // here changed removeChild method to remove
}
}
Remove DOM Element
IDs must be unique
Use type="button" or use preventDefault (you are submitting your form now on each click)
Delegate
Using
<button type="button" class="addschool">
<button type="button" class="removeschool">
and
document.getElementById("schools").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("removeschool")) {
tgt.closest("table").remove();
}
else if (tgt.classList.contains("addschool")) addSchool();
})
Also look into
clone templates
Here is a clone example. I renumber the schools whenever I add or remove one
I moved the add outside schools and remove to the header
const schools = document.getElementById("schools");
const firstSchool = document.getElementById("school1");
const renum = () => schools.querySelectorAll(".num").forEach((school,i) => school.innerText = (i+1))
function addSchool() {
const newSchool = firstSchool.cloneNode(true);
newSchool.querySelector(".removeschool").removeAttribute("hidden")
schools.appendChild(newSchool)
renum()
}
schools.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("removeschool")) {
tgt.closest("table").remove();
renum()
}
})
document.getElementById("addschool").addEventListener("click",addSchool);
div {
border: 1px solid black;
}
.maincol {
width: 50%;
}
.maincol>* {
margin-left: 20px;
}
.maincol>h2 {
margin-left: 0px;
}
#schools>table {
margin-bottom: 20px;
}
<h1>Resume Creator</h1>
<form>
<div class="maincol">
<h2>Identifying Information</h2>
<table>
<tr>
<td><label for="name">Full Name: </label></td>
<td><input type="text" id="name" name="name" size="50" /></td>
</tr>
<tr>
<td><label for="address">Address: </label></td>
<td><input type="text" id="address" name="address" size="50" /></td>
</tr>
<tr>
<td><label for="email">Email Address: </label></td>
<td><input type="text" id="email" name="email" size="50" /></td>
</tr>
<tr>
<td><label for="phone">Phone Number: </label></td>
<td><input type="text" id="phone" name="phone" size="50" /></td>
</tr>
</table>
</div>
<div class="maincol">
<h2>Skills</h2>
<p>Enter a comma-separated list of skills. E.g. Guest Services, Loss Prevention, Product Promotion, Etc.</p>
<textarea id="skill_list" rows=4 cols=90></textarea>
</div>
<div class="maincol">
<h2>Education</h2>
<div id="schools">
<table id="school1">
<tr>
<td colspan="2">School <span class="num">1</span><span style="float:right"><button type="button" hidden class="removeschool" >Remove</button></span></td>
</tr>
<tr>
<td><label for="schoolname1">School Name: </label></td>
<td><input type="text" id="schoolname1" size="50" /></td>
</tr>
<tr>
<td><label for="schoollocation1">Location: </label></td>
<td><input type="text" id="schoollocation1" size="50" /></td>
</tr>
<tr>
<td><label for="schoolyear1">Year Graduated: </label></td>
<td><input type="text" id="schoolyear1" size="50" /></td>
</tr>
<tr>
<td><label for="schooldegree1">Degree Earned: </label></td>
<td><input type="text" id="schooldegree1" size="50" /></td>
</tr>
</table>
</div>
<button type="button" id="addschool">Add School</button>
</div>
</form>
You need to specify for each button type = "button" so that it doesn't reload the page every time you press it. Like so :
<button id="removeschool" type = "button" onclick="removeSchool();">Remove School</button>.
Although I would suggest you put your buttons outside the table so that you don't have to add them with javascript every time you add/delete a school. (for the delete button just hide it when you have only one school and display it when you have multiple schools).
Also I think its better in the future to use classes instead of just adding plain strings to the HTML body. Your code would be cleaner and easier to edit.
So I've created a UWP application in Visual Studio that uses a webview to load a local html file. The html file uses Javascript to validate the user's input and will display a message box if the user enters incorrect data into any of the fields after clicking a button. The file works just fine when I run it in a web browser, but when it's run through the webview, the Javascript ceases to function (Where no message box is displayed for any incorrect data entered).
This is the code that creates the URI and navigates to the HTML content:
Uri myUri = new Uri("ms-appx-web:///Register_js.html");
webView1.Navigate(myUri);
I'm not sure why Javascript doesn't work when I load a local file but works perfectly fine when I load google.com (which would obviously use Javascript).
Does anyone know how I can get Javascript to work for a local file?
Edit: here is the code of the HTML file I'm trying to load:
<!DOCTYPE html>
<html>
<head>
<title>User Registration Form</title>
<script language="JavaScript" type="text/javascript">
function ValidateForm()
{
var regExp=/\d{4}-\d{2}-\d{2}/;
if (document.newUserForm.firstname.value=="")
{ alert("Firstname field cannot be blank.");
document.newUserForm.firstname.focus();
return false;}
if (document.newUserForm.surname.value=='')
{
alert('Surname field cannot be blank.');
document.newUserForm.surname.focus();
return false;
}
if (!regExp.test(document.newUserForm.DOB.value) )
{
alert('The Field is not correctly formatted!');
document.newUserForm.DOB.focus();
return false;
};
if (document.newUserForm.homePhone.value=='')
{
alert('Home Phone field cannot be blank.');
document.newUserForm.homePhone.focus();
return false;
}
if (isNaN(document.newUserForm.homePhone.value))
{
alert('Home Phone field must be a number.');
document.newUserForm.homePhone.focus();
return false;
}
if (document.newUserForm.roomNo.value=='')
{
alert('Room No. field cannot be blank.');
document.newUserForm.roomNo.focus();
return false;
}
if (document.newUserForm.workPhone.value=='')
{
alert('Work Phone field cannot be blank.');
document.newUserForm.workPhone.focus();
return false;
}
if (document.newUserForm.fax.value=='')
{
alert('Fax field cannot be blank.');
document.newUserForm.fax.focus();
return false;
}
if (document.newUserForm.emailAddress.value=='')
{
alert('Email Address field cannot be blank.');
document.newUserForm.emailAddress.focus();
return false;
}
if (document.newUserForm.password.value=='')
{
alert('Password field cannot be blank.');
document.newUserForm.password.focus();
return false;
}
if (document.newUserForm.password.value.length<5)
{
alert('Password field must be at least five characters.');
document.newUserForm.password.focus();
return false;
}
if (document.newUserForm.confirmPassword.value=='')
{
alert('Confirm Password field cannot be blank.');
document.newUserForm.confirmPassword.focus();
return false;
}
if (document.newUserForm.password.value!=document.newUserForm.confirmPassword.value)
{
alert('Password fields do not match.');
document.newUserForm.confirmPassword.focus();
return false;
}
if (document.newUserForm.gender.value=="male")
{
alert('Gender is male.');
return false;
}
return true;
}
</script>
</head>
<body>
<h2><strong>New User Details</strong></h2>
<form name="newUserForm" method="post" action="registerUserDisplay.php" onsubmit="return ValidateForm();">
<table style="width: 500px; border: 0px;" cellspacing="1" cellpadding="1">
<tr>
<td colspan="2"><strong>Personal Details</strong></td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>First Name</td>
<td>
<input name="firstname" type="text" style="width: 200px;" maxlength="100" />*
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Surname</td>
<td>
<input name="surname" type="text" style="width: 200px;" maxlength="100" />*
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Gender</td>
<td>
<input name="gender" id="gM" type="radio" value="M" /><label for="gM">Male</label>
<input name="gender" id="gF" type="radio" value="F" checked="checked" /><label for="gF">Female</label>
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td><input name="bender" id="gB" type="radio" value="B" /><label for="gB">Bender</label></td>
<td>D.O.B.<small> (YYYY-MM-DD)</small></td>
<td>
<input name="DOB" type="text" style="width: 100px;" maxlength="10" />
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Home Address</td>
<td>
<textarea name="homeAddress" cols="30" rows="5"></textarea>
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Home Phone</td>
<td>
<input name="homePhone" type="text" style="width: 150px;" maxlength="15" />*
</td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2"><strong>Work Details</strong></td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Position</td>
<td>
<select name="positionID">
<option value="1" selected="selected">Permanent</option>
<option value="2">Full-Time</option>
<option value="3">Part-Time</option>
<option value="4">Casual</option>
<option value="5">Volunteer</option>
</select>
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Room No.</td>
<td>
<input name="roomNo" type="text" style="width: 50px;" maxlength="5" />*
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Work Phone</td>
<td>
<input name="workPhone" type="text" style="width: 150px;" maxlength="15" />*
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Fax</td>
<td>
<input name="fax" type="text" style="width: 150px;" maxlength="15" />*
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Mobile</td>
<td>
<input name="mobilePhone" type="text" style="width: 150px;" maxlength="15" />
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Email Address</td>
<td>
<input name="emailAddress" type="text" style="width: 200px;" maxlength="200" />*
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Department</td>
<td>
<select name="deptID">
<option value="1" selected="selected">Accounts</option>
<option value="2">Human Resources</option>
<option value="3">Help Desk</option>
<option value="4">Management Information Systems</option>
<option value="5">Public Relations</option>
<option value="6">Communications</option>
</select>
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Password</td>
<td>
<input name="password" type="password" style="width: 200px;" maxlength="20" />*
</td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>Confirm Password</td>
<td>
<input name="confirmPassword" type="password" style="width: 200px;" maxlength="20" />*
</td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr style="background-color: #FFFFFF;">
<td>
<input type="reset" name="reset" value="Reset" />
<input type="submit" name="submit" value="Submit" />
</td>
<td>
<div align="right">* indicates required field</div>
</td>
</tr>
</table>
</form>
</body>
</html>
I want to construct some input forms that can calculate automatically. Provide below is my input forms.
var form = document.forms.myform,
pv1 = form.pv1,
pv2 = form.pv2,
output = form.pvtotal;
window.calculate = function () {
var p1 = parseInt(pv1.value, 10) || 0,
p2 = parseFloat(pv2.value) || 0;
output.value = (p1 + p2).toFixed(2);
};
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
th {
color: black;
background: #f9f9f9;
font-size: 16px;
}
input[type=number]{
width: 50px;
}
</style>
<form action="" name="myform" onkeyup="calculate()">
<table>
<thead>
<tr>
<th colspan="3">PREV DAY STOCK</th>
<th colspan="3">CULL</th>
<th colspan="3">MORTALITY</th>
<th colspan="3">CURRENT STOCK</th>
</tr>
<tr>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="pv1"></td>
<td><input type="number" name="pv2"></td>
<td><input type="number" name="pvtotal"></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name="" readonly></td>
<td><input type="number" name="" readonly></td>
<td><input type="number" name="" readonly></td>
</tr>
</tbody>
</table>
</form>
As you can see and try, i just provide the sum for previous stock. The main problem is I want all the column be automatic calculated except for the CURRENT STOCK column which i want this column calculated by:
(PREVIOUS STOCK - CULL - MORTALITY = CURRENT STOCK
Then, the other problem whenever i add one row below, all the script did not function anymore. I don't know why. I hope you guys can help me through this.
Below is my expected output:
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
th {
color: black;
background: #f9f9f9;
font-size: 16px;
}
input[type=number]{
width: 50px;
}
div.scrollmenu {
overflow: auto;
}
h4 {
text-decoration: underline;
text-align: center;
line-height: 1.6;
}
<form action="dailyprod_action.php" method="post" name="myform" onkeyup="calculate()">
<table>
<thead>
<tr>
<th colspan="3">PREV DAY STOCK</th>
<th colspan="3">CULL</th>
<th colspan="3">MORTALITY</th>
<th colspan="3">CURRENT STOCK</th>
</tr>
<tr>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="" value="1000"></td>
<td><input type="number" name="" value="1000"></td>
<td><input type="number" name="" value="2000"></td>
<td><input type="number" name="" value="200"></td>
<td><input type="number" name="" value="200" ></td>
<td><input type="number" name="" value="400"></td>
<td><input type="number" name="" value="200"></td>
<td><input type="number" name="" value="200"></td>
<td><input type="number" name="" value="400"></td>
<td><input type="number" name="" value="600" readonly></td>
<td><input type="number" name="" value="600" readonly></td>
<td><input type="number" name="" value="1200" readonly></td>
</tr>
<tr>
<td><input type="number" name="" value="2000"></td>
<td><input type="number" name="" value="2000"></td>
<td><input type="number" name="" value="4000"></td>
<td><input type="number" name="" value="400"></td>
<td><input type="number" name="" value="400" ></td>
<td><input type="number" name="" value="800"></td>
<td><input type="number" name="" value="400"></td>
<td><input type="number" name="" value="400"></td>
<td><input type="number" name="" value="800"></td>
<td><input type="number" name="" value="1700" readonly></td>
<td><input type="number" name="" value="1700" readonly></td>
<td><input type="number" name="" value="3400" readonly></td>
</tr>
</tbody>
</table>
</form>
You can develop my sample script and try
$("#pds_v1").keyup(function(){
var pds_v1 = $("#pds_v1").val();
var pds_v2 = $("#pds_v2").val();
var total= parseInt(pds_v2) + parseInt(pds_v1);
$("#pds_sum").val(total);
});
$("#pds_v2").keyup(function(){
var pds_v1 = $("#pds_v1").val();
var pds_v2 = $("#pds_v2").val();
var total= parseInt(pds_v2) + parseInt(pds_v1);
$("#pds_sum").val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<table>
<tr>
<td><input type="number" name="" id="pds_v1"></td>
<td><input type="number" name="" id="pds_v2"></td>
<td><input type="number" name="" id="pds_sum"></td>
</tr>
</table>
I suggest you use JQuery as that will make your life easier, also there's not much difference between Javascript and JQuery syntax, so it'll be easy for you to learn if you know Javascript.
I moved your onkeyup event listener to the tr tag so you'll be able to do calculate() on every row. I also added this parameter on the calculate() function to get the element that fired that function and get all child from that element to change the output field of that row (the one that fired calculate() function).
Try this code below (this is only inputs for Previous Stock):
function calculate(elem) {
pv1 = $(elem).children()[0].children;
pv2 = $(elem).children()[1].children;
out = $(elem).children()[2].children;
var p1 = parseInt($(pv1).val(), 10) || 0;
var p2 = parseFloat($(pv2).val()) || 0;
$(out).val((p1 * p2).toFixed(2));
}
$('#add_field').click(function() {
$('#table_body').append(`
<tr onkeyup="calculate(this)" onchange="calculate(this)">
<td><input type="number" name="pv1" id="pv1"></td>
<td><input type="number" name="pv2" id="pv2"></td>
<td><input type="number" name="pvtotal" id="output"></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name="" readonly></td>
<td><input type="number" name="" readonly></td>
<td><input type="number" name="" readonly></td>
</tr>
`)
})
$('#remove_field').click(function() {
var len = ($('#table_body').children()).length - 1;
$('#table_body').children()[len].remove();
})
table,
th,
td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
th {
color: black;
background: #f9f9f9;
font-size: 16px;
}
input[type=number] {
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" name="myform">
<table>
<thead>
<tr>
<th colspan="3">PREV DAY STOCK</th>
<th colspan="3">CULL</th>
<th colspan="3">MORTALITY</th>
<th colspan="3">CURRENT STOCK</th>
</tr>
<tr>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
<th>M</th>
<th>F</th>
<th>Total</th>
</tr>
</thead>
<tbody id="table_body">
<!-- I'm moving your event listener to the <tr> tag -->
<tr onkeyup="calculate(this)" onchange="calculate(this)">
<td><input type="number" name="pv1" id="pv1"></td>
<td><input type="number" name="pv2" id="pv2"></td>
<td><input type="number" name="pvtotal" id="output"></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name="" readonly></td>
<td><input type="number" name="" readonly></td>
<td><input type="number" name="" readonly></td>
</tr>
</tbody>
</table>
</form>
<button type="button" id="add_field">Add Field</button>
<button type="button" id="remove_field">Remove Field</button>
I'm working on an application that has 2 tables on the left side and a row on the right side, on the table when the user selects any number, the values are dynamically added on the rows on the right side.
This works as expected but I'm trying to add CSS where if the user hovers on the input on the row (on the right side) it changes to green and the corresponding value/td on the table background color immediately changes to green.
Here is my attempt:
// window.onload = function () { alert("Js working!") };
let currentInput = 1;
let bonusInput = 1;
$("#table1").on('click', function(event) {
let num = event.target.textContent;
$("#inp" + currentInput++).attr("value", num);
});
// bonus input:
$("#table2").on('click', function(event) {
let bon = event.target.textContent;
$("#bonus" + bonusInput++).attr("value", bon);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Table on the left -->
<div style="width: 140px; float: left;">
<table id="table1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!--2nd table-->
<div style="width: 140px; float: left; margin-left: 12px;">
<table id="table2">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!-- Input values to populate dynamically-->
<div style="width: 600px; float: right;">
<div>
<input type="text" size="4" id="inp1" value="">
<input type="text" size="4" id="inp2" value="">
<input type="text" size="4" id="inp3" value="">
<input type="text" size="4" id="inp4" value="">
<input type="text" size="4" id="inp5" value=""> +
<input style="margin-left: 20px;" type="text" size="4" id="bonus1" value="">
</div>
<div style="margin-top: 5px;">
<input type="text" size="4" id="inp7" value="">
<input type="text" size="4" id="inp8" value="">
<input type="text" size="4" id="inp9" value="">
<input type="text" size="4" id="inp10" value="">
<input type="text" size="4" id="inp11" value=""> +
<input style="margin-left: 20px;" type="text" size="4" id="bonus2" value="">
</div>
</div>
Here is the screenshot of the result:
You could use JavaScript instead:
// window.onload = function () { alert("Js working!") };
let currentInput = 1;
let bonusInput = 1;
$("#table1").on('click', function(event) {
let num = event.target.textContent;
$("#inp" + currentInput++).attr("value", num);
});
//Bonus input
$("#table2").on('click', function(event) {
let bon = event.target.textContent;
$("#bonus" + bonusInput++).attr("value", bon);
});
$('#result input').hover(function() {
var key = parseInt(this.id.replace(/(inp|bonus)/gm, ''), 10);
var dir = this.id.indexOf('bonus') >= 0 ? '1' : '2';
var row = (key > 6 || this.id == 'bonus2') ? 1 : 0;
var col = key % 6;
$('td').attr('style', '');
$('input').attr('style', '');
var table = '1';
if (dir == 1) table = '2';
var compare_key = this.value;
$('#table' + table + ' td').each(function() {
if (this.innerText.trim() == compare_key) {
$(this).css('background-color', 'green').css('color', 'white');
}
});
$(this).css('background-color', 'green').css('color', 'white');
});
* {
font-size: 15px;
}
td {
text-align: center;
border: 2px solid red;
line-height: 3.5rem;
width: 200px;
cursor: pointer;
}
td:hover {
background-color: green;
color: white;
}
#table1 td {}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Draggable Bootstrap nav-tabs with jQuery UI</title>
<meta name="description" content="Draggable Bootstrap nav-tabs with jQuery UI">
<!-- include bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<!--Table on the left -->
<div style="width: 140px; float: left;">
<table id="table1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!--2nd table-->
<div style="width: 140px; float: left; margin-left: 12px;">
<table id="table2">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!-- Input values to populate dynamically-->
<div id="result" style="width: 600px; float: right;">
<div>
<input type="text" size="4" id="inp1" value="">
<input type="text" size="4" id="inp2" value="">
<input type="text" size="4" id="inp3" value="">
<input type="text" size="4" id="inp4" value="">
<input type="text" size="4" id="inp5" value=""> +
<input style="margin-left: 20px;" type="text" size="4" id="bonus1" value="">
</div>
<div style="margin-top: 5px;">
<input type="text" size="4" id="inp7" value="">
<input type="text" size="4" id="inp8" value="">
<input type="text" size="4" id="inp9" value="">
<input type="text" size="4" id="inp10" value="">
<input type="text" size="4" id="inp11" value=""> +
<input style="margin-left: 20px;" type="text" size="4" id="bonus2" value="">
</div>
</div>
<!-- include jQuery -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<!-- include jQuery UI -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- include bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>
I'm sure there is more efficient ways to do this. I've just played around with classes. You can try the code snippet.
// window.onload = function () { alert("Js working!") };
let currentInput = 1;
let bonusInput = 1;
$("#table1").on('click', function(event) {
let num = event.target.textContent;
$("#inp" + currentInput++).attr("value", num);
});
//Bonus input
$("#table2").on('click', function(event) {
let bon = event.target.textContent;
$("#bonus" + bonusInput++).attr("value", bon);
});
$(".leftCell").mouseover(function() {
var val = $(this).val();
if (val != "") {
var cell = $('#table1').find('.' + val)
cell.css("background-color", "green")
}
});
$(".leftCell").mouseout(function() {
var val = $(this).val();
if (val != "") {
var cell = $('#table1').find('.' + val)
cell.css("background-color", "white")
}
});
$(".rightCell").mouseover(function() {
var val = $(this).val();
if (val != "") {
var cell = $('#table2').find('.' + val)
cell.css("background-color", "green")
}
});
$(".rightCell").mouseout(function() {
var val = $(this).val();
if (val != "") {
var cell = $('#table2').find('.' + val)
cell.css("background-color", "white")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 140px; float: left;">
<table id="table1">
<tbody>
<tr>
<td class="1">1</td>
<td class="2">2</td>
</tr>
<tr>
<td class="3">3</td>
<td class="4">4</td>
</tr>
<tr>
<td class="5">5</td>
<td class="6">6</td>
</tr>
<tr>
<td class="7">7</td>
<td class="8">8</td>
</tr>
<tr>
<td class="9">9</td>
<td class="10">10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!--2nd table-->
<div style="width: 140px; float: left; margin-left: 12px;">
<table id="table2">
<tbody>
<tr>
<td class="1">1</td>
<td class="2">2</td>
</tr>
<tr>
<td class="3">3</td>
<td class="4">4</td>
</tr>
<tr>
<td class="5">5</td>
<td class="6">6</td>
</tr>
<tr>
<td class="7">7</td>
<td class="8">8</td>
</tr>
<tr>
<td class="9">9</td>
<td class="10">10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!-- Input values to populate dynamically-->
<div style="width: 600px; float: right;">
<div>
<input type="text" class="leftCell" size="4" id="inp1" value="">
<input type="text" class="leftCell" size="4" id="inp2" value="">
<input type="text" class="leftCell" size="4" id="inp3" value="">
<input type="text" class="leftCell" size="4" id="inp4" value="">
<input type="text" class="leftCell" size="4" id="inp5" value=""> +
<input style="margin-left: 20px;" type="text" size="4" id="bonus1" class="rightCell" value="">
</div>
<div style="margin-top: 5px;">
<input type="text" class="leftCell" size="4" id="inp7" value="">
<input type="text" class="leftCell" size="4" id="inp8" value="">
<input type="text" class="leftCell" size="4" id="inp9" value="">
<input type="text" class="leftCell" size="4" id="inp10" value="">
<input type="text" class="leftCell" size="4" id="inp11" value=""> +
<input style="margin-left: 20px;" type="text" size="4" id="bonus2" class="rightCell" value="">
</div>
</div>
Okay so I already know I can get the entire HTML document's markup (minus the DOCTYPE) using:
document.documentElement.outerHTML
however that will only get me the original source markup, and not the current state of the DOM, which is really what I am looking for. For my immediate needs I really just want to preserve the state of a form within the document (think of it in terms of an an auto-save).
Please note this is not being used in a standard website/webapp format, so posting, submitting, etc. really isn't an option. I need a pure JavaScript way to acquire an HTML string representation of the current DOM tree, so an external caller can save it to disk for later use.
Now I know I can manually iterate through all the form elements, grabbing each and every value, and doing a string replacement on the result of the above outerHTML (via regular expressions), to build an HTML string that mirrors the current DOM, but I was hoping there was an easier way to do this (maybe something built in). Like a DOM to HTML parser/writer.
However so far I have not found a built in way to do this. Just wanted to reach out and see if anyone else has needed to do this. And ask if my above proposed method the best way to approach this particular problem, before I begin implementing it.
Here is a sample HTML page in which I tried the supplied function:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function getFormState() {
// this could be set outside this function if calling multiple times
var theForm = document.forms[0];
console.log(theForm);
var theData = new FormData(theForm);
console.log(theData);
// get the state of the form as an iterator of key/value pairs
var state = theData.entries();
console.log(state);
// convert the iterator into an array of key/value pairs
var stateArray = Array.from(state);
console.log(stateArray);
// Use JSON.stringify to change the key/value pair array state into a string
var stateString = JSON.stringify(stateArray);
console.log(stateString);
return stateString;
}
</script>
<style>
#header {
background: #ffffff;
position: fixed;
width: 100%;
height: 30px;
padding: 5px 0px 0px 0px;
top: 0;
z-index: 1;
}
#content{
margin-top: 40px;
}
body, input, select, textarea {
font-family: monospace;
font-size: 10pt;
font-weight: bold;
}
td {
padding: 8px 8px 8px 8px;
}
input:not([type="button"]):not([type="checkbox"]):not([type="color"]):not([type="file"]):not([type="image"]):not([type="radio"]):not([type="range"]):not([type="reset"]):not([type="submit"]), select, textarea {
-webkit-transition: all 0.30s ease-in-out;
-moz-transition: all 0.30s ease-in-out;
-ms-transition: all 0.30s ease-in-out;
-o-transition: all 0.30s ease-in-out;
outline: none;
padding: 3px 0px 3px 3px;
margin: 5px 1px 3px 0px;
border: 1px solid #DDDDDD;
}
input:not([type="button"]):not([type="checkbox"]):not([type="color"]):not([type="file"]):not([type="image"]):not([type="radio"]):not([type="range"]):not([type="reset"]):not([type="submit"]):focus, select:focus, textarea:focus {
box-shadow: 0 0 5px rgba(81, 203, 238, 1);
padding: 3px 0px 3px 3px;
margin: 5px 1px 3px 0px;
border: 1px solid rgba(81, 203, 238, 1);
}
</style>
<title>HTML5 FormData Test</title>
</head>
<body>
<form id="frmForm">
<div id="header">
<button type="button" onclick="getFormState()">getFormState</button>
<hr>
</div>
<div id="content">
<table border="1">
<tr>
<td>Button</td>
<td><input id="btnButton" type="button" value="Button"></td>
</tr>
<tr>
<td>Checkbox</td>
<td><input id="chkCheckbox" type="checkbox"></td>
</tr>
<tr>
<td>Color</td>
<td><input id="clrColor" type="color" value="#000000"></td>
</tr>
<tr>
<td>Datalist</td>
<td>
<input id="txtDatalist" type="text" list="choices" value="">
<datalist id="choices">
<option value="One"></option>
<option value="Two"></option>
<option value="Three"></option>
</datalist>
</td>
</tr>
<tr>
<td>Date</td>
<td><input id="calDate" type="date" value=""></td>
</tr>
<tr>
<td>Datetime (Deprecated)</td>
<td><input id="calDateTime" type="datetime" value=""></td>
</tr>
<tr>
<td>Datetime (Local)</td>
<td><input id="calDateTimeLocal" type="datetime-local" value=""></td>
</tr>
<tr>
<td>Disabled</td>
<td><input id="txtDisabled" type="text" value="Disabled" disabled=""></td>
</tr>
<tr>
<td>E-Mail</td>
<td><input id="txtEMail" type="email" value=""></td>
</tr>
<tr>
<td>File</td>
<td><input id="binFile" type="file" value=""></td>
</tr>
<tr>
<td>Hidden</td>
<td><input id="txtHidden" type="hidden" value="HIDDEN"></td>
</tr>
<tr>
<td>Image (Submit)</td>
<td><input id="btnImage" type="image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAVCAIAAABpKDERAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAJcSURBVEhLzZVNTxpBGMcHvkEjbZFkT3BoUmNSsSc/QXdBLL23IRyQmkhjzNbGO4nUbUwQ15geeiC9QDct3V3itSdE7YuSniBRGynQ8BXcPs/s4HLYAk2q3d+Bed7zn5md4KpUKo1GgzgSv9/vyufz0WiUBRyGoihuw9mgvgunwvQ5GTdcMzOdB2hzs6N0KgPOr7p+o5/HhXOWuDbw/Jhpw/RSt9vdXYWi1V2w3jwaZ4nrZOj7xU1YFVVpLCZJsTFAeinhEiu0MLFHHcaTIo0BUN8PK24V6ASKtEcLbWH6BkGovstPAMxS2kh29Ock/Z2rfZWF0ukpJqafdRi1bUFNiEX8GPZfPUgL2zUzSMgL/XX0JkTX784TGaOdmjyb5uPFNk6w5y/PD92VmXt0vcN58BM5OjnHROtd7BZlYl7DFtpjNVtW9dMaIaXkBK1NlnqldjB9A4G5OKJHz7uMmr8HG5NJbUX9CXzb4nsNwRmRaMlJr9dLs6kgjWKr+BFLTXYewqH+iaH66Mb7AA98vHa6IobRPjsihOfwAR28faqbQaOpyBk+d9g0WZyi/QbHhQnJyErTdIcw4H73N3w+Xxgug6yFwYorcI9UHybZikph9cwmRKIvBKFsi9sUUR0kb0cSy2bQhE648ETkL5shKx5X2jjQDtDmkmU5FArhjv85n7Nc5Dhb3ZkbB+cwy81llt//SAXN5CioqnqF/2+ds2NreLPfGRXocOVyOUGAx38V/PqwcD+Fr5mypJwsTjF7NDRNQ308Dy/Oiei6Pvz9/l9c5XK5Xq8zwQ4jEAj8BmbeP4OPzU0kAAAAAElFTkSuQmCC"></td>
</tr>
<tr>
<td>Month</td>
<td><input id="calMonth" type="month" value=""></td>
</tr>
<tr>
<td>Number</td>
<td><input id="numNumber" type="number" min="0" max="10" step="1" required="" value=""></td>
</tr>
<tr>
<td>Password</td>
<td><input id="txtPassword" type="password" value=""></td>
</tr>
<tr>
<td>Radio</td>
<td>
<input id="radRadio1" type="radio" name="radRadio" value="1">One<br>
<input id="radRadio2" type="radio" name="radRadio" value="2">Two<br>
<input id="radRadio3" type="radio" name="radRadio" value="3">Three
</td>
</tr>
<tr>
<td>Range</td>
<td><input id="numRange" type="range" min="0" max="10" value="5"></td>
</tr>
<tr>
<td>Readonly</td>
<td><input id="txtReadonly" type="text" value="Readonly" readonly=""></td>
</tr>
<tr>
<td>Reset</td>
<td><input id="btnReset" type="reset"></td>
</tr>
<tr>
<td>Search</td>
<td><input id="txtSearch" type="search" placeholder="search text" value=""></td>
</tr>
<tr>
<td>Select</td>
<td>
<select id="sltSelect">
<option value="" disabled="" selected=""><Select></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</td>
</tr>
<tr>
<td>Select (Multiple)</td>
<td>
<select id="sltMultiSelect" multiple="">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</td>
</tr>
<tr>
<td>Submit</td>
<td><input id="btnSubmit" type="submit"></td>
</tr>
<tr>
<td>Telephone</td>
<td><input id="txtTelephone" type="tel" value=""></td>
</tr>
<tr>
<td>Textbox</td>
<td><input id="txtTextbox" type="text" value=""></td>
</tr>
<tr>
<td>Textarea</td>
<td><textarea id="txtTextarea"></textarea></td>
</tr>
<tr>
<td>Time</td>
<td><input id="calTime" type="time" value=""></td>
</tr>
<tr>
<td>URL</td>
<td><input id="txtURL" type="url" value=""></td>
</tr>
<tr>
<td>Week</td>
<td><input id="calWeek" type="week" value=""></td>
</tr>
</table>
</div>
</form>
</body>
</html>
which returns the following:
I am able to manually iterate over all the inputs to get what I need, in fact that is my current solution, but the FormData solution seemed like a much cleaner approach, it's just not returning the expected data.
In fact the only input that ever seems to populate is the RadioButton.