.html() not showing the whole text that contains the ' character - javascript

When i try to edit the value on fields that contain the ' character in them, it cuts the string to that character. For example if I put O'Hara as name a try to edit it, it will give me only the O from O'Hara. Also on a side note is this "valid", correct way to edit the values of the properties on the the contact objects? Thanks in advance.
class Contact{
constructor(id, first, last, email, password, phone) {
this.id = id || "WTF";
this.first = first || this.get_Random_F_name();
this.last = last || this.get_Random_F_name();
this.email = email || (this.get_Random_F_name() + "#hotmail.com");
this.password = password || Math.floor(Math.random() * Math.floor(90000));
this.phone = phone || Math.floor(Math.random() * Math.floor(500));
}
get_Random_F_name(){
let cityIndex = Math.floor(Math.random() * Math.floor(9));
if(cityIndex == 0){
return "O'mara"
}
else if(cityIndex == 1){
return "F'airfax"
}
else if(cityIndex == 2){
return "C'harlie"
}
else if(cityIndex == 3){
return "Evereteze"
}
else if(cityIndex == 4){
return "H'errera"
}
else if(cityIndex == 5){
return "Guerriero"
}
else if(cityIndex == 6){
return "I'mperio"
}
else if(cityIndex == 7){
return "Levitan"
}
else {
return "A'mato"
}
}
}
function dontCoptThatFloppy(id, first, last, email, password, phone) {
let proactiveBitch = ("<tr><td class='td-id'>"+ id +
"</td><td class='f_Name'>"+first+
"</td><td class='l_Name'>"+last+
"</td><td class='e_mail'>"+email+
"</td><td class='pass_in'>"+password+
"</td><td class='phone_in'>"+phone+
"</td><td class='td-three-Btn'><button class='save-Btn'>save</button>"+
"<button class='edit-Btn'>edit</button><button class='del-Btn'>Broken</button></td>"+
"<td class='td-del'><button class='del-row'>Del</button></td>"+"</tr>")
return proactiveBitch;
}
$(document).ready(function(){
let idCounter = 1;
let a_contacts = [];
let a_contacts2 = [];
let a_contacts3 = [];
let contacts_arr_obj = [];
let new_contacts_arr_obj = contacts_arr_obj;
$('#new-row-btn').click(function(){
let newContact = new Contact(idCounter, $("#name-input").val(), $("#lastname-input").val(), $("#email-input").val(), $("#pass-input").val(), $("#phone-input").val());
$("#my-table").append(dontCoptThatFloppy(idCounter, newContact.first, newContact.last, newContact.email, newContact.password, newContact.phone))
a_contacts.push(newContact);
$("#name-input").val("")
$("#lastname-input").val("")
$("#email-input").val("")
$("#pass-input").val("")
$("#phone-input").val("")
idCounter++;
});
$(document).on('click', '.del-row', function (event) {
$(event.target).parent().parent().remove()
});
$(document).on('click', '.edit-Btn', function (event) {
var $row = $(this).closest('tr');
var id = $row.find('.td-id').text();
var fName = a_contacts[id-1].first;
var lName = a_contacts[id-1].last;
var email = a_contacts[id-1].email;
var pass = a_contacts[id-1].password;
var phone = a_contacts[id-1].phone;
let my_input_f_Name = "<input class='in_f_name' type='text' value='"+fName+"'>"
let my_input_l_Name = "<input class='in_l_name' type='text' value='"+lName+"'>"
let my_input_e_mail = "<input class='in_e_mail' type='text' value='"+email+"'>"
let my_input_pass = "<input class='in_pass_in' type='text' value='"+pass+"'>"
let my_input_phone = "<input class='in_phone_in' type='text' value='"+phone+"'>"
$row.find('.f_Name').html(my_input_f_Name)
$row.find('.l_Name').html(my_input_l_Name)
$row.find('.e_mail').html(my_input_e_mail)
$row.find('.pass_in').html(my_input_pass)
$row.find('.phone_in').html(my_input_phone)
let edit = $row.find('.edit-Btn')
let del_btn = $row.find('.del-Btn')
let save_btn = $row.find('.save-Btn')
edit.css('display','none');
del_btn.css('display','none');
save_btn.css('display','block');
});
$(document).on('click', '.save-Btn', function (event) {
var $row = $(this).closest('tr');
var id = $row.find('.td-id').text();
a_contacts[id-1].first = $row.find('.in_f_name').val();
a_contacts[id-1].last = $row.find('.in_l_name').val();
a_contacts[id-1].email = $row.find('.in_e_mail').val();
a_contacts[id-1].password = $row.find('.in_pass_in').val();
a_contacts[id-1].phone = $row.find('.in_phone_in').val();
$row.find('.f_Name').html( a_contacts[id-1].first);
$row.find('.l_Name').html(a_contacts[id-1].last);
$row.find('.e_mail').html(a_contacts[id-1].email);
$row.find('.pass_in').html(a_contacts[id-1].password);
$row.find('.phone_in').html(a_contacts[id-1].phone);
let edit = $row.find('.edit-Btn')
let del_btn = $row.find('.del-Btn')
let save_btn = $row.find('.save-Btn')
edit.css('display','inline');
del_btn.css('display','inline');
save_btn.css('display','none');
});
$(document).on('click', '#sup', function (event) {
console.log(a_contacts);
});
$("#sort").on("change", function(event){
let pickedValue = event.target.value;
let table = $('#my-table')
let rows = table.find('.td-id').toArray()
if (pickedValue === "1"){
a_contacts.sort(function(a, b){
return a.id - b.id;
});
}
else if (pickedValue === "2"){
a_contacts.sort(function(a,b) {
return a.first.localeCompare(b.first);
});
}
else if (pickedValue === "3"){
a_contacts.sort(function(a,b) {
return a.last.localeCompare(b.last);
});
}
else if (pickedValue === "4"){
a_contacts.sort(function(a,b) {
return a.email.localeCompare(b.email);
});
}
else if (pickedValue === "5"){
a_contacts.sort(function(a, b){
return a.password - b.password;
});
}
else if (pickedValue === "6"){
a_contacts.sort(function(a, b){
return a.phone - b.phone;
});
}
else{}
$(tbody).html("");
for (var i = 0; i < rows.length; i++){
$("#my-table").append(dontCoptThatFloppy(a_contacts[i].id, a_contacts[i].first, a_contacts[i].last, a_contacts[i].email, a_contacts[i].password, a_contacts[i].phone))
}
});
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" media="screen" href="CSS/style.css" />
</head>
<body>
<div id="inputs-div">
<input type="text" placeholder="Your Name Sir" id="name-input">
<input type="text" placeholder="Your Last Name Sir" id="lastname-input">
<input type="text" placeholder="Your Email Sir" id="email-input">
<input type="password" placeholder="Your Password Sir" id="pass-input" >
<input type="text" placeholder="Your Phone Number" id="phone-input" >
<button id="new-row-btn">Add Contact</button>
<button id="sup">Console.Log</button>
</div>
<select class="custom-select" id="sort">
<option selected>Choose...</option>
<option value="1">ID</option>
<option value="2">First Name</option>
<option value="3">Last Name</option>
<option value="4">Email</option>
<option value="5">Password</option>
<option value="6">Phone</option>
</select>
<div>
<table id="my-table">
<thead>
<tr id="first-row">
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Password</th>
<th>Phone</th>
<th>Action</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<script src="JS/jquery-3.2.1.js"></script>
<script src="JS/script.js"></script>
</body>
</html>
*{
margin: 0px;
padding: 0px;
}
body{
background-color: black;
color: wheat;
}
input{
display: block;
margin: 2px;
border: 2px solid #ac7b11;
background-color: rgba(44, 42, 42, 0.863);
color: #bebe35;
}
::placeholder {
color: #bebe35;
}
button{
background-color: #1a64a0;
border: 2px solid #1a64a0;
color: white;
border-radius: 3px;
outline:none;
/* text-align: center;
display:table-cell;
vertical-align:middle; */
}
#new-row-btn, #sup{
width: 100px;
height: 30px;
margin: 3px;
}
.del-row{
/* display: flex; */
width: 100%;
height: 100%;
/* margin: 0px auto; */
/* text-align: 0px auto; */
}
.small-Btn, .medium-Btn{
display: none;
}
.del-Btn, .edit-Btn{
background-color: #10b133;
border: 2px solid #10b133;
width: 50%;
height: 100%;
}
.save-Btn{
background-color: #a1b110;
border: 2px solid #a1b110;
display: none;
width: 100%;
height: 100%;
}
th{
height: 30px;
width: 100px;
}
td{
height: 30px;
width: 100px;
}
.td-id{
width: 30px;
text-align: center;
}
#my-table tbody tr td {
background-color: #a35635;
}
#my-table tbody tr td:nth-child(odd) {
background-color: #828e20;
}
.td-del, .td-three-Btn{
background-color: transparent !important;
}
td input{
box-sizing: border-box;
width: 100%;
height: 100%;
margin:0px;
}

When you write something like this:
let my_input_f_Name = "<input class='in_f_name' type='text' value='"+fName+"'>"
if the value of fName is O'hara, the resulting HTML is:
<input class='in_f_name' type='text' value='O'hara'>
The ' in the name matches the ' that starts the value attribute, so it ends the attribute; it's equivalen to writing
<input class='in_f_name' type='text' value='O' hara'>
Since you're using jQuery, you can use its methods to create your elements instead of concatenating strings:
let my_input_f_Name = $("<input>", {
"class": "in_f_name",
type: "text",
value: fName
});

Related

How do I add buttons that accept delete and clear orders on my webpage with the use of arrays?

I have to create a webpage that can add and delete and clear orders inside the textbox with the application of arrays. The conditions are as follows:
1.Initially, there should be no element/value inside the array of the program.
The value/element will be deleted once the Delete Order Button is clicked.
It will only contain a value when the Add Order button is clicked.
If someone inputs a value and clicks "Add Order"
It must add the value inside the array of the program
An alert box shows up saying "Order has been added".
The order should also be displayed in the second cell of the table under the "Order:" text
3.If someone inputs a value and clicks "Delete Order"
The added value in the array must be deleted
An alert box must be displayed saying "Order has been deleted".
The inputted order should also be deleted in the second cell of the table under the "Order:" text.
4.If someone clicks "Clear input"
The content of the textbox should be erased
Although I've learned the concepts of Arrays I don't have an idea on how to apply that into making this website. I've already set up the alerts and layout but was unable to make the orders pop up onto the second cell on the table.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {background-color: #a8f00e;}
table, th, td {
border: 1px solid black;
background-color: #fff714;
text-align: center;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Point of Sale Program</h1>
<table style="width:100%">
<tr>
<th>
<h2> Add Order
<br>
<form action="/action_page.php" method="get">
<input type="text">
<br>
<button onclick="Add()">Add Order</button>
<button onclick="Delete()">Delete Order</button>
<button type="reset" value="Reset">Clear Input</button>
</h2>
</th>
<th>Order</th>
<script>
function Add() {
alert("Order had been added");
}
function Delete() {
alert("Order had been deleted");
}
</script>
</body>
</html>
You define your array like that var itemArray = []
then you add items to your array via itemArray.push('Item Name')
and remove items of an array via the splice() method
to just clear your array you re-declare it like that itemArray = []
Hope that helps getting you started!
Is this the sort of thing you're after? or do you need the form so you can send the information on?
<h1>Point of Sale Program</h1>
<table id="OrdersTable" style="width: 100%;">
<thead>
<tr>
<td><h2>Add Order</h2></td>
</tr>
<tr>
<td>
<input type="text" id="OrderName">
</td>
<td>
<button id="AddButton">Add</button>
<button id="ClearInputButton">Clear</button>
</td>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<td><button onclick="clearAllOrders()">Clear Orders</button></td>
<td></td>
</tr>
</tfoot>
</table>
<script>
// Orders Array
var orders = [];
// Adds order to Array
function addOrder(text){
orders.push(text);
alert("Order has been added");
drawOrders();
}
// Removes order based on position in array
function removeOrder(index){
orders.splice(index,1);
alert("Order has been deleted");
drawOrders();
}
// Removes all orders from the Array
function clearAllOrders(){
orders = [];
drawOrders();
}
// Draw/Redraw the orders into the table
function drawOrders(){
// Select the Body of the table or <tbody></tbody>
var tableBody = document.querySelector("#OrdersTable tbody");
// clear the table body
var body = tableBody.innerHTML = "";
// Then add all the orders into the table body
orders.forEach((order,index)=>{
let deletebutton = document.createElement("button");
deletebutton.innerText = "Delete";
deletebutton.onclick = function(){removeOrder(index)};
let row = document.createElement("tr");
let firstCell = document.createElement("td");
firstCell.innerText = order;
let secondCell = document.createElement("td");
secondCell.appendChild(deletebutton);
row.appendChild(firstCell);
row.appendChild(secondCell);
tableBody.appendChild(row);
});
}
// Attach onclick event to Add button and empty the textbox when order is added
document.querySelector("#AddButton").onclick = function(){
var textInput = document.querySelector("#OrderName");
addOrder(textInput.value);
textInput.value = "";
}
// Attach onclick event to clear input button so when it's clicked the textbox is emptied
document.querySelector("#ClearInputButton").onclick = function(){
document.querySelector('#OrderName').value = "";
}
</script>
const itemTemplateHtml = `<li>
<span data-item>Invalid Item</span>
<button type="button" data-delete-item>Delete Item</button>
</li>`;
let itemTemplate;
function emptyElementNode(elmNode) {
Array
.from(elmNode.childNodes)
.forEach(node => node.remove());
}
function createTemplateFromCode(templateHtml) {
const container = document.createElement('div');
container.innerHTML = templateHtml;
return container.firstElementChild;
}
function logListOrderData(orderList, elmFormOrders) {
// console.clear();
console.log('orderList :', JSON.stringify(orderList));
console.log('elmFormOrders.value :', elmFormOrders.value);
console.log('\n');
}
function updateOrderListFormData(elmOrderList, elmFormOrders) {
const orderList = Array
.from(elmOrderList.children)
.reduce((list, elm) =>
list.concat(
elm.querySelector('[data-item]').dataset.value.trim() || []
), []
);
elmFormOrders.value = orderList.join(',');
logListOrderData(orderList, elmFormOrders);
}
function addOrderListItem(value, elmOrderList, elmFormOrders) {
// value = value.replace((/,/g), "\\,");
const elmListItem = itemTemplate.cloneNode(true);
const elmDataItem = elmListItem.querySelector('[data-item]');
elmDataItem.dataset.value = value;
elmDataItem.textContent = value;
elmListItem
.querySelector('[data-delete-item]')
.addEventListener('click', handleDeleteItemWithBoundContext.bind({
elmListItem,
elmOrderList,
elmFormOrders
}));
elmOrderList.appendChild(elmListItem);
updateOrderListFormData(elmOrderList, elmFormOrders);
}
function handleAddItemWithBoundContext(/*evt*/) {
const { elmOrderItem, elmOrderList, elmFormOrders } = this;
const value = elmOrderItem.value.trim();
elmOrderItem.value = value;
if (value !== '') {
addOrderListItem(value, elmOrderList, elmFormOrders);
}
}
function handleDeleteItemWithBoundContext(/*evt*/) {
const { elmListItem, elmOrderList, elmFormOrders } = this;
elmListItem.remove();
updateOrderListFormData(elmOrderList, elmFormOrders);
}
function handleClearOrdersWithBoundContext(/*evt*/) {
const { elmOrderItem, elmOrderList, elmFormOrders } = this;
elmOrderItem.value = '';
elmFormOrders.value = '';
emptyElementNode(elmOrderList);
updateOrderListFormData(elmOrderList, elmFormOrders);
}
function initializeAddItem(elmAddItem, elmOrderItem, elmOrderList, elmFormOrders) {
elmAddItem.addEventListener('click', handleAddItemWithBoundContext.bind({
elmOrderItem,
elmOrderList,
elmFormOrders,
}));
}
function initializeClearOrders(elmClearOrders, elmOrderItem, elmOrderList, elmFormOrders) {
if (elmClearOrders) {
elmClearOrders.addEventListener('click', handleClearOrdersWithBoundContext.bind({
elmOrderItem,
elmOrderList,
elmFormOrders,
}));
}
}
function initializeOrders() {
const elmOrders = document.querySelector('#orders');
const elmOrderItem = elmOrders.querySelector('[data-order-item]');
const elmAddItem = elmOrders.querySelector('[data-add-item]');
const elmOrdersForm = elmOrderItem && elmAddItem && elmOrders.querySelector('form');
const elmOrderList = elmOrdersForm && elmOrdersForm.querySelector('.order-list');
const elmFormOrders = elmOrdersForm && elmOrdersForm.querySelector('[data-form-orders]');
itemTemplate = elmOrderList && elmFormOrders && createTemplateFromCode(itemTemplateHtml);
if (itemTemplate) {
initializeAddItem(elmAddItem, elmOrderItem, elmOrderList, elmFormOrders);
initializeClearOrders(
elmOrders.querySelector('[data-clear-orders]'),
elmOrderItem, elmOrderList, elmFormOrders
);
updateOrderListFormData(elmOrderList, elmFormOrders);
}
}
/*export default */initializeOrders();
body { background-color: #a8f00e; font-size: x-small; }
h1, h2 { margin: 0; font-size: unset;}
button, textarea, [type="text"] { font-size: x-small; }
article, fieldset, li { position: relative; }
button { position: absolute; right: 5px; }
li button { bottom: 2px; }
article > button { right: 9px; }
form { margin-bottom: 7px; }
ol {
margin: -1px 3px 5px 2px; padding: 0 0 0 8px;
border: 1px solid black;
background-color: #fff714;
}
ol:empty { border: none; }
li { margin: 0 0 0 10px; padding: 4px 0 5px 0; }
#orders { width: 40%; }
.as-console-wrapper {
min-height: 100%!important;
width: 59%;
top: 0;
left: auto!important;
right: 0!important;
}
<h1>Point of Sale Program</h1>
<article id="orders">
<fieldset>
<legend>Place an Order</legend>
<input type="text" data-order-item placeholder="Put an Order Item" />
<button type="button" data-add-item>Add Item</button>
</fieldset>
<form action="/action_page.php" method="get">
<ol class='order-list'></ol>
<input type="hidden" name="order_list" data-form-orders value="" />
</form>
<button type="reset" data-clear-orders>Clear Order List</button>
</article>

Use JS to determine if all form fields are filled and correctly

*Edit: Fixed so that all inputs are now validated on one form. However, I can only add one variable to check if blank, as soon as I add more, none of the submit functions work. I have been trying multiple things.
function validateForm() {
var inputVelocity = document.getElementById("dzCalculator").inputVelocity.value;
var inputYellowPhase = document.getElementById("dzCalculator").inputYellowPhase.value;
var inputRedPhase = document.getElementById("dzCalculator").inputInterPhase.value;
var inputReactionTime = document.getElementById("dzCalculator").inputReactionTime.value;
if(inputVelocity === "" && inputYellowPhase === "" && inputRedPhase === "" && inputReactionTime === ""){
alert("Input all fields to calculate.");
return false;
}
}
I have checked the HTML matches - it does. But I found I could not use onsubmit="return validateForm" as this wouldn't work at all.
This is only 4 of the form values, there are seven all up. But when I can get the four working, I can get them all working.
How can I use JS to make sure that no input is left blank or empty? I already have made it so that it will only accept numbers and decimal points. So no one can add an incorrect field. But currently, they can leave a field blank which means my calculator generates a NaN response.
Also, how can I make sure one of my fields can not accept a number greater than 1 or less than 0. I tried min="0" max="1" in the input tag, but because I have removed spinners, this doesn't work.
So, in summary, I am looking to make sure when a button is clicked that all the form sections are filled in and that one of the fields doesn't accept a number greater that 1 or less than zero.
there are 2 options for this.
You can select all the inputs (inside the form tag) using querySelector and check the value of each input by looping through them.
use this trick selector to get all the invalid inputs
document.querySelectorAll('input:not([value]):not([value=""])');
replace input with more precise selector.
Can you please give more detail about how your form is in multiple places?
For input I think you need to use step attribute
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Reference: javascript_form_validation
Depends when would you like to validate form fields
For example: Form validation on submit
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<html>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Give name to your form using name attribute such as <form name="myForm" ..>
Then using document.forms["myForm"] you can have access to your form
There you can validate your input fields value. return true if validates
This works for me. You can use it, style it however you want or not. You do need JQuery. It has powerful selectors.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
body{
font-size: 12px;
}
.main-container{
display: flex; /* DO NOT CHANGE */
height: 100vh; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
}
.c-message{
display: flex; /* DO NOT CHANGE */
position: fixed; /* DO NOT CHANGE */
top: 0px; /* DO NOT CHANGE */
left: 0px; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
height: 100%; /* DO NOT CHANGE */
}
.c-msgbox{
padding: 30px;
text-align: center;
margin: auto; /* DO NOT CHANGE */
background-color: #e4e4e4;
border-radius: 4px;
border: 1px solid #adadad;
-webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
-moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
}
.standerd-button2{
border: none;
font-family: arial,helvetica,clean,sans-serif;
font-size: 10px;
font-weight: 600;
color: white;
background: #1A709F;
padding: 3px;
text-align: center;
vertical-align: middle;
-webkit-border-radius: 3px;
width: max-content;
min-width: 50px;
margin: 2px;
}
.standerd-button2:hover{
background: crimson;
cursor: default;
}
.f-table {
display: table;
width: max-content;
padding: 5px;
border-spacing: 2px;
}
.f-tablerow {
display: table-row;
}
.f-tablecell{
display: table-cell;
}
.label-cell-r{
text-align: right;
}
.dd-required{
margin: auto;
color: red;
}
input, select{
border: 1px solid lightgrey;
}
</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
<div>
<form id="f1" name="f1">
<div class="f-table">
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="firstname">First Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="firstname" name="firstname" type="text" data-er="First Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="lastname">Last Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="lastname" name="lastname" type="text" data-er="Last Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="company">Company</label>
</div>
<div class="f-tablecell input-cell">
<select id="company" name="company" data-er="Company Name">
<option value="0"> - Select Comapny - </option>
<option value="1">Company 1</option>
<option value="2">Company 2</option>
<option value="3">Company 3</option>
<option value="4">Company 4</option>
</select>
<span class='dd-required'>*</span>
</div>
</div>
</div>
<input id="b1" type="submit" value="Submit" />
</form>
</div>
<div>
<script type="text/javascript">
$.fn.CustomAlert = function (options, callback) {
var settings = $.extend({
message: null,
detail: null,
yesno: false,
okaytext: null,
yestext: null,
notext: null
}, options);
var frm = "";
detail = "<b>" + settings.detail + "</b>";
message = "<b>" + settings.message + "</b>";
if (settings.detail === null) {
detail = "";
};
frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";
if (settings.yesno === false) {
frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
} else {
frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
"<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
};
var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
"<div class='c-msgbox'>" +
"<form>" + frm + "</form>" +
"</div>" +
"</div>";
$(".main-container").append(frmesg);
if (!settings.yesno) {
$("#cmessage #ok").click(function () {
$("#cmessage").remove();
callback(false);
});
} else {
$("#cmessage #yes").click(function () {
$("#cmessage").remove();
callback(true);
});
$("#cmessage #no").click(function () {
$("#cmessage").remove();
callback(false);
});
};
};
$.fn.JsFormCheck = function () {
var MessData = "";
this.find('select, input').each(function () {
if ($(this).attr("data-er")) {
m = $(this).attr("data-er");
switch ($(this).get(0).tagName) {
case "INPUT":
if ($(this).val().length === 0) {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
case "SELECT":
if ($(this).val() === "0") {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
};
};
});
if (MessData.length > 0) {
MessData = "<b>" + MessData + "</b>";
x = $().CustomAlert({message: "<b>Please fill in the following required fields to continue.</b>",
detail: MessData,
okaytext: "Close",
yesno: false});
return true;
} else {
return false;
};
};
$('#f1 #b1').click(function(event){
event.preventDefault();
Error = $("#f1").JsFormCheck();
if(Error === false){
null;
//Do Something
};
});
</script>
</body>

how to hide a div container if input dynamically added with choice in checkbox are empty

how to hide a div container if input dynamically added with choice in checkbox are empty
So here what I looked on the forums but I did not find a subject similar to mine
As I explained, I created a booking form for an evening with dynamic inputs to choose on a checkbox
example: I choose the number of adults / number of children and depending on the number of inputs created creates appear ... until all is well ...
I add a PayPal object api (dynamic payment method depending on choice) from their site
what I would like to do
option 1: it is a "required" on the inputs if the fields are all filled the PayPal button (which is a div) gets gray
or
option 2: hide the button if empty input.
Friends if you could give me a hand this would be super nice thank you !!
/* set global variable i */
var i=0;
const adult_price = 20;
const child_price = 10;
/*
---------------------------------------------
function to remove fom elements dynamically
---------------------------------------------
*/
function updateIds(type) {
if ( type == "adult" ) {
var j=1;
// Replace all id_adult_x by id_adult_j, with "j" an ordered list starting with j=1
$('[id^=id_adult_]').each(function() {
// Replace the LABEL text
document.getElementById("lbl_"+this.id).innerHTML = "<hr>"+"Adulte"+" "+j;
var res = this.id.split("id_adult_").join('');
var spanContent = document.getElementById(this.id).innerHTML;
var strToReplace = new RegExp('_adult_'+res, "gi");
document.getElementById(this.id).innerHTML = spanContent.replace( strToReplace, '_adult_'+j);
this.id = "id_adult_"+j;
j= ++j;
});
} else if ( type == "child" ) {
var j=1;
$('[id^=id_child_]').each(function() {
// Replace the LABEL text
document.getElementById("lbl_"+this.id).innerHTML = "<hr>"+"Enfant"+" "+j;
var res = this.id.split("id_child_").join('');
var spanContent = document.getElementById(this.id).innerHTML;
var strToReplace = new RegExp('_child_'+res, "gi");
document.getElementById(this.id).innerHTML = spanContent.replace( strToReplace, '_child_'+j);
this.id = "id_child_"+j;
j= ++j;
});
}
}
/*
---------------------------------------------
function to remove fom elements dynamically
---------------------------------------------^
*/
function removeElement(parentDiv, childDiv){
if (childDiv == parentDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
if (childDiv.includes("adult")) {
document.getElementById("nbrAdult").value = $("[id^=id_adult_]").length ;
// Calculate the new total price
setTotalPrice();
// Update IDs
updateIds("adult");
}
else if (childDiv.includes("child")) {
document.getElementById("nbrChild").value = $("[id^=id_child_]").length ;
// Calculate the new total price
setTotalPrice();
// Update IDs
updateIds("child");
}
else {
/* do nothing */
}
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
/*
----------------------------------------------------------------------------
functions that will be called upon, when user change the list "Nombre Adulte(s)"
---------------------------------------------------------------------------
*/
function onAdultChange()
{
// Retrieve the number of "Adult" selected by the user
var nbrAdultValue = document.getElementById("nbrAdult").value;
// Count the total number of "Adult" Div that are actually created on the html file
var idAdultCount = $("[id^=id_adult_]").length;
// Calculate the delta btw these variables, in order to create or delete the right number of "Adult" Div
var x = nbrAdultValue - idAdultCount;
// Check if the delta is negative, if so, we must delete the last "x" number of "Adult" Div
if ( x < 0 ) {
// Convert "x" from negative to absolute
x = Math.abs(x);
// alert("This action will remove last "+x+" Adult Fields");
// Remove the last "x" "Adult" Div
for (j = 0; j < x ; j++) {
var max = 0;
$("[id^=id_adult_]").each(function() {
var res = this.id.split("id_adult_").join('');
max = Math.max(res, max);
});
removeElement("myForm","id_adult_"+max);
}
}
else {
// Create "x" new "Adult" Div
for (j = 0; j < x; j++) {
i = ++i;
var r = document.createElement('span');
r.setAttribute("id", "id_adult_"+i);
document.getElementById("myForm").appendChild(r);
var l = document.createElement("LABEL");
l.setAttribute("id", "lbl_id_adult_"+i);
l.innerHTML = "Adulte "+i;
document.getElementById("id_adult_"+i).appendChild(l);
lastNameFunction("adult_"+i);
firstNameFunction("adult_"+i);
emailFunction("adult_"+i);
telFunction("adult_"+i);
var g = document.createElement("IMG");
g.setAttribute("src", "delete.jpg");
g.setAttribute("onclick", "removeElement('myForm','id_adult_"+ i +"')");
document.getElementById("id_adult_"+i).appendChild(g);
}
}
// Calculate the new total price
setTotalPrice();
// Update IDs
updateIds("adult");
}
/*
----------------------------------------------------------------------------
functions that will be called upon, when user change the list "Nombre Enfant(s)"
---------------------------------------------------------------------------
*/
function onChildChange()
{
// Retrieve the number of "Child" selected by the user
var nbrChildValue = document.getElementById("nbrChild").value;
// Count the total number of "Child" Div that are actually created on the html file
var idChildCount = $("[id^=id_child_]").length;
// Calculate the delta btw these variables, in order to create or delete the right number of "Child" Div
var x = nbrChildValue - idChildCount;
// Check if the delta is negative, if so, we must delete the last "x" number of "Child" Div
if ( x < 0 ) {
// Convert "x" from negative to absolute
x = Math.abs(x);
// alert("This action will remove last "+x+" Child Fields");
// Remove the last "x" "Child" Div
for (j = 0; j < x ; j++) {
var max = 0;
$("[id^=id_child_]").each(function() {
var res = this.id.split("id_child_").join('');
max = Math.max(res, max);
});
removeElement("myForm","id_child_"+max);
}
}
else {
// Create "x" new "Child" Div
for (j = 0; j < x; j++) {
i = ++i;
var r = document.createElement('span');
r.setAttribute("id", "id_child_"+i);
document.getElementById("myForm").appendChild(r);
var l = document.createElement("LABEL");
l.setAttribute("id", "lbl_id_child_"+i);
l.innerHTML = "Enfant "+i;
document.getElementById("id_child_"+i).appendChild(l);
lastNameFunction("child_"+i);
firstNameFunction("child_"+i);
var g = document.createElement("IMG");
g.setAttribute("src", "delete.jpg");
g.setAttribute("onclick", "removeElement('myForm','id_child_"+ i +"')");
document.getElementById("id_child_"+i).appendChild(g);
}
}
// Calculate the new total price
setTotalPrice();
// Update IDs
updateIds("child");
}
/*
----------------------------------------------------------------------------
functions that will create an input field for the lastName
---------------------------------------------------------------------------
*/
function lastNameFunction(type)
{
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
y.setAttribute("id","nom-de-famille");
y.setAttribute("placeholder","Nom");
y.setAttribute("Name","lastname_"+type);
document.getElementById("id_"+type).appendChild(y);
document.getElementById("nom-de-famille").required=true;
}
/*
----------------------------------------------------------------------------
functions that will create an input field for the firstName
---------------------------------------------------------------------------
*/
function firstNameFunction(type)
{
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
y.setAttribute("placeholder","Prenom");
y.setAttribute("Name","firstname_"+type);
document.getElementById("id_"+type).appendChild(y);
}
/*
----------------------------------------------------------------------------
functions that will create an input field for the Email
---------------------------------------------------------------------------
*/
function emailFunction(type)
{
var y = document.createElement("INPUT");
y.setAttribute("type", "email");
y.setAttribute("placeholder", "Email");
y.setAttribute("Name","email_"+type);
document.getElementById("id_"+type).appendChild(y);
}
/*
----------------------------------------------------------------------------
functions that will create an input field for the phone number
---------------------------------------------------------------------------
*/
function telFunction(type)
{
var y = document.createElement("INPUT");
y.setAttribute("type", "tel");
y.setAttribute("placeholder", "Tel");
y.setAttribute("Name","tel_"+type);
document.getElementById("id_"+type).appendChild(y);
}
/*
---------------------------------------------
function that calculate the total price
---------------------------------------------
*/
function setTotalPrice()
{
document.getElementById("totalPrice").value = document.getElementById("nbrAdult").value*adult_price + document.getElementById("nbrChild").value*child_price;
}
/*
---------------------------------------------
function that create the Items List formatted for Paypal
---------------------------------------------
*/
function getJsonItemsList()
{
var itemsList = [];
var j=0;
$('[id^=id_adult_]').each(function() {
itemsList.push({ "name":"Adulte "+(j+1) , "description": document.getElementsByName
("lastname_adult_"+(j+1))[0].value
+ " " + document.getElementsByName("firstname_adult_"
+(j+1))[0].value + " " + document.getElementsByName
("email_adult_"+(j+1))[0].value
+ " " + document.getElementsByName("tel_adult_"
+(j+1))[0].value , "quantity": "1", "price": + adult_price , "currency":"EUR" });
j= ++j;
});
var h=0;
$('[id^=id_child_]').each(function() {
itemsList.push({ "name":"Enfant "+(h+1) ,
"description": document.getElementsByName("lastname_child_"+(h+1))[0].value
+ " " + document.getElementsByName("firstname_child_"+(h+1))[0].value , "quantity": "1", "price":
+ child_price , "currency":"EUR" });
h= ++h;
});
if ( j == "0" && h == "0") {
itemsList ="' '";
}
return itemsList ;
}
/*
-----------------------------------------------------------------------------
functions that will be called upon, when user click on the Reset Button
------------------------------------------------------------------------------
*/
function resetElements(){
document.getElementById('myForm').innerHTML = '';
document.getElementById("nbrAdult").value = "0";
document.getElementById("nbrChild").value = "0";
document.getElementById("totalPrice").value = "0";
i = 0;
}
.three {
width: 80%;
border: solid 1px lightgray;
margin-top: 30px ;
margin-bottom: 30px ;
margin-left: auto;
margin-right: auto;
background-color: #FFFFFF;
}
.jta-before-form {
text-align: center;
}
.jta-form-layout {
line-height: 30px;
margin: 20px;
}
#mainform > .jta-form-content {
padding: 10px;
}
#myForm {
display: inline;
padding: 10px;
}
input {
width: 40%;
padding: 12px 20px;
margin: 20px;
box-sizing: border-box;
border-radius: 4px;
display: inline-block;
}
input:focus {
background-color: lightgoldenrodyellow;
border-radius: 4px;
}
#lbl_id_adult_1,
#lbl_id_adult_2,
#lbl_id_adult_3,
#lbl_id_adult_4,
#lbl_id_adult_5,
#lbl_id_adult_6,
#lbl_id_adult_7,
#lbl_id_adult_8,
#lbl_id_adult_9 {
margin: 15px 0px 15px 0px ;
border-bottom: solid 1px lightgray;
display: block;
}
#id_adult_1> img,
#id_adult_2> img,
#id_adult_3> img,
#id_adult_4> img,
#id_adult_5> img,
#id_adult_6> img,
#id_adult_7> img,
#id_adult_8> img,
#id_adult_9 > img {
float: right;
}
#lbl_id_child_1,
#lbl_id_child_2,
#lbl_id_child_3,
#lbl_id_child_4,
#lbl_id_child_5,
#lbl_id_child_6,
#lbl_id_child_7,
#lbl_id_child_8,
#lbl_id_child_9 {
margin: 15px 0px 15px 0px ;
border-bottom: solid 1px lightgray;
display: block;
}
#id_child_1> img,
#id_child_2> img,
#id_child_3> img,
#id_child_4> img,
#id_child_5> img,
#id_child_6> img,
#id_child_7> img,
#id_child_8> img,
#id_child_9 > img {
float: right;
}
#totalPrice {
border: solid 1px;
border-radius: 20px;
width: 150px;
margin-top: 40px;
margin-left: 10px;
display: inline-block;
text-align: center;
}
#paypal-button-container {
width: 100%;
text-align: center;
margin-bottom: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Create Dynamic form Using JavaScript - Demo Preview</title>
<meta name="robots" content="noindex, nofollow" />
<script src="js/repas-annuel-form.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="form-style.css">
</head>
<body>
<div class ="main_content">
<div class="three">
<div class="jta-before-form">
<span id="jta-form-title" class="jta-form-title">
<h3>reservation</h3></span>
<div class="">Les champs marqués d’un astérisque * sont obligatoires</div>
</div>
<div class="jta-form-layout">
<form action="#" type="sbubmit" method="get" id="mainform" >
<div class="jta-before-form-content" >
<div class="label" >
<label for="nbrAdult" >Nombre Adulte(s)</label>
</div>
<select id="nbrAdult" onchange="onAdultChange()">
<option value="0" selected=>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</div>
<div class="label">
<label for="nbrChild">Nombre Enfant(s)</label>
</div>
<select id="nbrChild" onchange="onChildChange()" >
<option value="" >0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</div>
</div>
<div class="jta-form-content ">
<span id="myForm"></span>
</div>
<div class="jta-after-form-content">Prix Total (Euro)
<INPUT id="totalPrice" type="text" disabled="disabled" placeholder="0" Size=8></INPUT>
</div>
</form>
<div class="jta-after-form">
<div name="button-paypal" id="paypal-button-container"></div>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
// Render the PayPal button
paypal.Button.render({
// Set your environment
env: 'production', // sandbox | production
// Specify the style of the button
style: {
layout: 'vertical', // horizontal | vertical
size: 'medium', // medium | large | responsive
shape: 'pill', // pill | rect
color: 'silver' // gold | blue | silver | white | black
},
// Specify allowed and disallowed funding sources
//
// Options:
// - paypal.FUNDING.CARD
// - paypal.FUNDING.CREDIT
// - paypal.FUNDING.ELV
funding: {
allowed: [
paypal.FUNDING.CARD,
],
disallowed: [
paypal.FUNDING.CREDIT,
],
},
// Enable Pay Now checkout flow (optional)
commit: true,
// PayPal Client IDs - replace with your own
// Create a PayPal app: https://developer.paypal.com/developer/applications/create
client: {
sandbox: 'AXnE7qNrnFxL4IsXrCSFP_mQPvjPNdGo_UA1pHvcw0p_hnmrLQR3_XOlqRTGe7POwHj8urXcd1DmmwWo',
production: 'Afe_0oViyEcryagJtFBf34Gkf_hbTgsIjPBkCKIdyD5jYNQF_Kyu3s1nawS46kTMBRoT25STeSnNkFF7'
},
// Set up a payment
payment: function(data, actions) {
return actions.payment.create({
transactions: [{
amount: {
total: document.getElementById("totalPrice").value,currency: 'EUR'},
description: 'Reservation - Repas Annuel 2018.',
item_list: { items: getJsonItemsList() }
}],
note_to_payer: 'Contact us for any questions on your order.'
});
},
onAuthorize: function (data, actions) {
return actions.payment.execute()
.then(function () {
window.alert('Merci pour votre réservation !');
});
}
}, '#paypal-button-container');
</script>
</script>
</div>
</body>
</html>
I am going to go out on a limb here and say all this ID management is pretty messy, difficult to maintain and frankly really unnecessary here. Use classes instead and make life a lot simpler for yourself.
I modified your markup to use a pair of hidden cloned input groups that I append to the form.
I removed a good bit of excess code - still pretty verbose but that is to allow you to see what is happening on each action.
I did NOT wire up the reset but that should be easy if you have the button somewhere.
I removed a good bit of markup for extra jQuery and unknown js etc.
I found and fixed a few (more than a few maybe) typos as well.
/* set global variable i */
//var i = 0;
const adult_price = 20;
const child_price = 10;
/*
---------------------------------------------
function to remove form elements dynamically
---------------------------------------------
*/
function updateIds() {
let adults = ".adult-container";
let children = ".child-container"
let containers = $('#myForm').find('.container-group');
containers.each(function() {
let containerDiv = $(this);
let idx = 0;
if (containerDiv.is(adults)) {
idx = $(adults).index($(this)) + 1;
}
if (containerDiv.is(children)) {
idx = $(children).index($(this)) + 1;
}
containerDiv.find('.numerator').html(idx);
});
}
/*
---------------------------------------------
function to remove form elements dynamically
---------------------------------------------^
*/
function removeElement(event) {
var parentDiv = $(event.delegateTarget);
let containerDiv = $(this).closest('.container-group');
if (containerDiv.is('.adult-container')) {
containerDiv.remove();
document.getElementById("nbrAdult").value = $('#myForm').find('.adult-container').length;
}
if (containerDiv.is('.child-container')) {
containerDiv.remove();
document.getElementById("nbrChild").value = $('#myForm').find('.child-container').length;
}
// Calculate the new total price
setTotalPrice();
updateIds();
$('#mainform').trigger('setpaypal');
}
/*
----------------------------------------------------------------------------
functions that will be called upon, when user change the list "Nombre"
---------------------------------------------------------------------------
*/
function onSelectChange(e) {
let containerSel = $(this).data('target');
let nbrValue = this.value;
let formid = "#myForm";
let myform = $(formid);
let items = myform.find(containerSel);
let itemsCount = items.length;
// Calculate the delta
var x = nbrValue - itemsCount;
// If the delta is negative, delete x
if (x < 0) {
let el = items.slice(x).remove();
} else {
// Create "x" new
let j = 0;
let clonex = $('#holder').find(containerSel).eq(0);
for (j; j < x; j++) {
let c = clonex.clone(true);
c.appendTo(formid);
}
}
updateIds();
setTotalPrice();
$('#mainform').trigger('setpaypal');
}
/*
---------------------------------------------
function that calculate the total price
---------------------------------------------
*/
function setTotalPrice() {
document.getElementById("totalPrice").value = document.getElementById("nbrAdult").value * adult_price + document.getElementById("nbrChild").value * child_price;
}
/*
---------------------------------------------
function that create the Items List formatted for Paypal
---------------------------------------------
*/
function getJsonItemsList() {
var itemsList = [];
var selAdultTarget = $('#nbrAdult').data('target');
var adults = $(selTarget);
adults.each(function() {
let item = {
"name": $(this).find('.type-text') + " " + $(this).find('.numerator').text(),
"description": $(this).find('.nom-de-famille').val() + "," + $(this).find('.firstname-input').val() + " " + $(this).find('.email-input').val() +
" " + $(this).find('.tel-input').val(),
"quantity": "1",
"price": +adult_price,
"currency": "EUR"
};
itemsList.push(item);
});
var selChildTarget = $('#nbrChild').data('target');
var children = $(selChildTarget);
children.each(function() {
let item = {
"name": $(this).find('.type-text') + " " + $(this).find('.numerator').text(),
"description": $(this).find('.nom-de-famille').val() + "," + $(this).find('.firstname-input').val(),
"quantity": "1",
"price": +child_price,
"currency": "EUR"
};
itemsList.push(item);
});
if (!!children.length && !!adults.length) {
itemsList = "' '";
}
return itemsList;
}
/*
-----------------------------------------------------------------------------
functions that will be called upon, when user click on the Reset Button
------------------------------------------------------------------------------
*/
function resetElements() {
// the select change events do this in a controlled way
// document.getElementById('myForm').innerHTML = '';
document.getElementById("nbrAdult").value = "0";
document.getElementById("nbrChild").value = "0";
//when you change the selects they do this, i not needed any more
//document.getElementById("totalPrice").value = "0";
// i = 0;
}
function setPayPal() {
// put other custom stuff here
let showhide = !$('#myForm').find('.container-group').length;
// hide if we have none, show if we have some
$('.length paypal-button-container')
.toggleClass('hidden', showhide);
}
$(function() {
$('#myForm').on("click", ".remove-group", removeElement);
$('#mainform').on('change', "#nbrAdult, #nbrChild", onSelectChange);
$('#mainform').on('setpaypal', setPayPal);
});
.three {
width: 80%;
border: solid 1px lightgray;
margin-top: 30px;
margin-bottom: 30px;
margin-left: auto;
margin-right: auto;
background-color: #FFFFFF;
}
.numerator {
margin-left: 1em;
}
.jta-before-form {
text-align: center;
}
.jta-form-layout {
line-height: 30px;
margin: 20px;
}
#mainform>.jta-form-content {
padding: 10px;
}
#myForm {
display: inline;
padding: 10px;
}
input {
width: 40%;
padding: 12px 20px;
margin: 20px;
box-sizing: border-box;
border-radius: 4px;
display: inline-block;
}
input:focus {
background-color: lightgoldenrodyellow;
border-radius: 4px;
}
#myForm .group-container .adult-label,
#myForm .group-container .child-label {
margin: 15px 0px 15px 0px;
border-bottom: solid 1px lightgray;
display: block;
}
#myForm img {
float: right;
}
#myForm .group-container .adult-label,
#myForm .group-container .child-label {
margin: 15px 0px 15px 0px;
border-bottom: solid 1px lightgray;
display: block;
}
#totalPrice {
border: solid 1px;
border-radius: 20px;
width: 150px;
margin-top: 40px;
margin-left: 10px;
display: inline-block;
text-align: center;
}
#paypal-button-container {
width: 100%;
text-align: center;
margin-bottom: 20px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div class="main_content">
<div class="three">
<div class="jta-before-form">
<span id="jta-form-title" class="jta-form-title">
<h3>reservation</h3></span>
<div class="">Les champs marqués d’un astérisque * sont obligatoires</div>
</div>
<div class="jta-form-layout">
<form action="#" type="submit" method="get" id="mainform">
<div class="jta-before-form-content">
<div class="label">
<label for="nbrAdult">Nombre Adulte(s)</label>
</div>
<select id="nbrAdult" data-target='.adult-container'>
<option value="0" selected=>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div class="label">
<label for="nbrChild">Nombre Enfant(s)</label>
</div>
<select id="nbrChild" data-target='.child-container'>
<option value="">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</div>
<div class="jta-form-content ">
<span id="myForm"></span>
</div>
<div class="jta-after-form-content">Prix Total (Euro)
<input id="totalPrice" type="text" disabled="disabled" placeholder="0" Size=8 />
</div>
</form>
<div class="jta-after-form">
<div name="button-paypal" id="paypal-button-container">Paypal Pal</div>
</div>
<div id="holder" class="hidden">
<div class="adult-container container-group">
<hr /><label class="adult-label"><span class="type-text">Adulte</span><span class="numerator"></span></label><input type="text" class="nom-de-famille" placeholder="Nom" name="lastname_adult" required=""><input type="text" class="firstname-input"
placeholder="Prenom" name="firstname_adult" /><input type="email" class="email-input" placeholder="Email" name="email_adult" /><input type="tel" class="tel-input" placeholder="Tel" name="tel_adult" /><img class="remove-group" src="delete.jpg"
/></div>
<div class="child-container container-group">
<hr /><label class="child-label"><span class="type-text">Enfant</span><span class="numerator"></span></label><input type="text" class="nom-de-famille" placeholder="Nom" name="lastname_child" /><input type="text" placeholder="Prenom" name="firstname_child"
/><img src="delete.jpg" /></div>
</div>
</body>
You can accomplish this by adding an event listener to your form that listens for keypresses. The listener will listen to all the dynamically created fields and the input elements in them.
var filledInputs = []
$("document").ready(function() {
$("#myForm").on("keypress", function(e) {
var elem = e.target.name + " " + e.target.id
if (e.target.value.length > 0) {
if (filledInputs.indexOf(elem) === -1) { filledInputs.push(elem) }
} else {
var elemIndex = filledInputs.indexOf(elem)
if (elemIndex !== -1) { filledInputs.splice(elemIndex, 1) }
}
})
})
EDITTED NOTE: there are two global variables to keep track of all the available inputs in the form, "allInputElements", and the ones that are currently filled "filledInputs". You need to increase "allInputElements" by the number of inputs elements for a field that's being added to the form during it's creation (4 for adults, 2 for children). The code above will add and remove names of the inputs to filledInputs whenever the user types in one.
function onAdultChange() {
// ...
if (x < 0) {
// ...
for (j = 0; j < x; j++) {
// ...
removeElement("myForm", "id_adult_" + max);
// decrease the global variable when removing input elements
allInputElements -= 4
}
} else {
for (j = 0; j < x; j++) {
// ...
document.getElementById("id_adult_" + i).appendChild(g);
// increase the global variable when adding input elements
allInputElements += 4
}
}
// ...
}
// ...
function onChildChange() {
// ...
if (x < 0) {
// ...
for (j = 0; j < x; j++) {
// ...
removeElement("myForm", "id_child_" + max);
// decrease the global variable when adding input elements
allInputElements -= 2
}
} else {
for (j = 0; j < x; j++) {
// ...
document.getElementById("id_child_" + i).appendChild(g);
// increase the global variable when adding input elements
allInputElements += 2
}
}
}
Aswell as setting allInputElements and filledInputs back to 0 when you clear the form of all input elements:
function resetElements() {
// ...
allInputElements = 0
filledInputs = []
}
PS: if "$(document).ready" doesn't work, move your jQuery to the very bottom of your HTML body element.
EDIT: your options for "disabling" the paypal button are to hide it with css' "display: none" or, the better alternative is to simply check if all inputs are filled before running your paypal code.
if (filledInputs.length === allInputElements) {
// paypal code
}
// else nothing happens

Cannot get table height to contstrain with in div

I've played around with a number of options, but I can't keep the table height from growing as I add lines dynamically.
This is a small section, part of a more complex page. Basically I have several div tags within the larger container div.
As more lines are added the table pushes the button below outside the boundaries of the div. Run the code snippet to observe the problem.
function onBodyLoader(obj) {
g.c.assignEventListners();
}
var g = {};
g.formClass = function() {
/*
----------------------------------
Properties for formClass
----------------------------------
*/
this.tr;
this.td;
this.elist = [];
/*
----------------------------------
Methods for formClass
----------------------------------
*/
this.assignEventListners = function() {
this.tbody = document.getElementById('emailDist');
g.sbAddELine = document.getElementById('sbAddELine');
g.sbAddELine.addEventListener("click", function(evt) {
g.c.addBlank();
}, false);
/*event listener for all links on the email list body*/
g.dataUpdate = document.querySelector("#emailDist");
g.dataUpdate.addEventListener("click", g.c.tableBodyRouter, false);
};
this.tableBodyRouter = function(e) {
/*
called from clicks on keyTable or task links
*/
if (e.target !== e.currentTarget)
if (e.target.id.indexOf('eRemove') > -1)
g.c.removeEmail(e);
e.stopPropagation();
};
this.redrawElist = function() {
/*delete current table*/
while (this.tbody.rows.length > 1)
this.tbody.deleteRow(1);
/*redraw table*/
for (var i = 0; i < this.elist.length; i++) {
this.rowLayout();
}
};
this.addBlank = function() {
/*add blank to this.elist array*/
this.elist.push({
eEmail: '',
eFirst: '',
eLast: '',
});
this.rowLayout();
}
this.removeEmail = function(e) {
var x = e.target.id.substr(7);
this.elist.splice(x, 1);
this.redrawElist();
};
this.rowLayout = function() {
var rowCnt = this.tbody.rows.length - 1;
this.tr = this.tbody.insertRow(this.tbody.rows.length);
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="text" id="eFirst' + rowCnt + '" maxlength="20" size="20" value=""/>';
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="text" id="eLast' + rowCnt + '" maxlength="20" size="20" value="" />';
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="text" id="eEmail' + rowCnt + '" maxlength="50" size="50" value="" />';
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="button" id="eRemove' + rowCnt + '" value="Remove" ">';
document.getElementById("eFirst" + rowCnt).focus();
document.getElementById("eFirst" + rowCnt).select();
}
}
g.c = new g.formClass;
table {
height: 60%;
max-height: 60%;
width: 100%;
display: inline-table;
border-style: none;
}
tbody {
font-size: 10pt;
display: block;
height: 90%;
overflow-y: scroll;
}
#container {
position: absolute;
width: 98%;
top: 40px;
height: 90%;
}
#dataEntryDiv {
border: medium groove;
position: absolute;
top: 0.5em;
height: 95%;
padding-left: 1em;
padding-right: 1em;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email List</title>
</head>
<body id="intactRolesBody" onLoad="onBodyLoader(this);">
<form id='intactRolesForm' method="post" action="" onSubmit="return false;">
<div id="container">
<div id="dataEntryDiv">
<input type="button" id='sbAddELine' value="Add non-company contact"><br>
<p>Email Distribution List</p>
<table>
<tbody id='emailDist'>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>email</th>
<th>remove from list</th>
</tr>
</tbody>
</table>
<input type="button" id='SaveEmailList' value="Save email List">
</div>
</div>
</form>
</body>
</html>
This is the basic behavior of a table. it shrinks and expand acording to its content.
What you can do to manage height is to reset the display.
it can be anything but table/inline-table/table-cell/table-row/.. . nor inline.
You used inline-table, inline-block might be fine:
function onBodyLoader(obj) {
g.c.assignEventListners();
}
var g = {};
g.formClass = function() {
/*
----------------------------------
Properties for formClass
----------------------------------
*/
this.tr;
this.td;
this.elist = [];
/*
----------------------------------
Methods for formClass
----------------------------------
*/
this.assignEventListners = function() {
this.tbody = document.getElementById('emailDist');
g.sbAddELine = document.getElementById('sbAddELine');
g.sbAddELine.addEventListener("click", function(evt) {
g.c.addBlank();
}, false);
/*event listener for all links on the email list body*/
g.dataUpdate = document.querySelector("#emailDist");
g.dataUpdate.addEventListener("click", g.c.tableBodyRouter, false);
};
this.tableBodyRouter = function(e) {
/*
called from clicks on keyTable or task links
*/
if (e.target !== e.currentTarget)
if (e.target.id.indexOf('eRemove') > -1)
g.c.removeEmail(e);
e.stopPropagation();
};
this.redrawElist = function() {
/*delete current table*/
while (this.tbody.rows.length > 1)
this.tbody.deleteRow(1);
/*redraw table*/
for (var i = 0; i < this.elist.length; i++) {
this.rowLayout();
}
};
this.addBlank = function() {
/*add blank to this.elist array*/
this.elist.push({
eEmail: '',
eFirst: '',
eLast: '',
});
this.rowLayout();
}
this.removeEmail = function(e) {
var x = e.target.id.substr(7);
this.elist.splice(x, 1);
this.redrawElist();
};
this.rowLayout = function() {
var rowCnt = this.tbody.rows.length - 1;
this.tr = this.tbody.insertRow(this.tbody.rows.length);
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="text" id="eFirst' + rowCnt + '" maxlength="20" size="20" value=""/>';
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="text" id="eLast' + rowCnt + '" maxlength="20" size="20" value="" />';
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="text" id="eEmail' + rowCnt + '" maxlength="50" size="50" value="" />';
this.td = this.tr.insertCell(this.tr.cells.length);
this.td.innerHTML = '<input type="button" id="eRemove' + rowCnt + '" value="Remove" ">';
document.getElementById("eFirst" + rowCnt).focus();
document.getElementById("eFirst" + rowCnt).select();
}
}
g.c = new g.formClass;
table {
height: 60%;
max-height: 60%;
width: 100%;
display: inline-block;/*... or block : do not use table display if you need to constrain height */
border-style: none;
}
tbody {/* this CSS could have been set to table directly :) */
font-size: 10pt;
display: block;
height: 90%;
overflow-y: scroll;
}
#container {
position: absolute;
width: 98%;
top: 40px;
height: 90%;
}
#dataEntryDiv {
border: medium groove;
position: absolute;
top: 0.5em;
/*left: 37em; removed for demo */
height: 95%;
padding-left: 1em;
padding-right: 1em;
}
<body id="intactRolesBody" onLoad="onBodyLoader(this);">
<form id='intactRolesForm' method="post" action="" onSubmit="return false;">
<div id="container">
<div id="dataEntryDiv">
<input type="button" id='sbAddELine' value="Add non-company contact"><br>
<p>Email Distribution List</p>
<table>
<tbody id='emailDist'>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>email</th>
<th>remove from list</th>
</tr>
</tbody>
</table>
<input type="button" id='SaveEmailList' value="Save email List">
</div>
</div>
</form>
</body>
Note: You did use display:block on tbody, you could have apply this directly to the table element and reset tbody to display:table :) (defaut is table-row-group )
Add
#dataEntryDiv {
overflow: auto;
}
To get a simplified version of the situation, I would suggest writing something like this - instead of putting in the code from your actual project. This way, you can get away from trying to 'fix' something - and possibly see a better way to build the layout - or at least make the use-case more specific.
https://stackoverflow.com/help/how-to-ask
markup
<section class="table-wrapper">
<header>
I'm a table wrapper thing
</header>
<main>
<table>
<!-- populate this -->
</table>
</main>
<footer>
<button>button (add row)</button>
</footer>
</section>
styles
.table-wrapper {
height: 300px; /* arbitrary */
border: 2px solid red;
}
.table-wrapper main {
height: 260px; /* likely you'd use flexbox or percentages or JS */
border: 2px solid blue;
overflow: auto;
}
js
var $table = $('.table-wrapper').find('table');
var $moreButton = $('.table-wrapper').find('button');
var counter = 0;
function addRow() {
counter = counter + 1;
$table.prepend('<tr><td>row and data ' + counter + '</td></tr>');
}
addRow();
// populate some things to start
$moreButton.on('click', function() {
addRow();
});
https://jsfiddle.net/sheriffderek/b6z4ep46/

How to assign a class or ID to a table within a JavaScript function?

I have to use HTML, CSS and JavaScript (so no jQuery).
I have created a table that receives JSON data via API. I have a function to show/hide each of the table rows by clicking a check box. I already included the JavaScript function, but I cannot figure out where to place a class or id, so I can connect the function to each of the table rows. Generally, I would add a class to <td> for example, like this: <td class="example"> but in this case it won't work. The code breaks when I do this.
I did search online for hours, but wasn't able to find an answer. I'm not looking for finished code, but rather a hint/help how to achieve this.
This table is created using:
body {
background: white;
}
h1 {
color: black;
font-size: 35px;
text-align: center;
font-family: 'Quicksand', sans-serif;
}
h2 {
font-family: 'Quicksand', sans-serif;
margin-left: 3.3em;
}
table, th , td {
border: none;
border-collapse: collapse;
padding: 15px;
margin-left: 5em;
margin-top: -25em;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
#form {
font-family: 'Quicksand', sans-serif;
margin-left: 5em;
}
#googleMap {
margin-left: 45em;;
margin-right: auto;
}
#chkbox_display {
margin-left: 5em;
margin-top: 3em;
font-family: 'Quicksand', sans-serif;
}
.hidden {
display: none;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<title>Weather App</title>
</head>
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>
<h2>Please enter the following information:</h2>
<form id="form" onsubmit ="return fetchUrl()">
Enter your City:<br>
<input id="weather_city" placeholder="Entere here..."><br>
How to display values: <br>
<select id="weather_scale">
<option value="Metric">Metric Units (Celcius/mm)</option>
<option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
</select><br>
Number of days to show weather:<br>
<select id="weather_numberOfDays">
<option value="1">Today only</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="4">4 days</option>
<option value="5">5 days</option>
</select>
<br><br>
<button onclick="initialize">Submit</button>
</form>
<div id="chkbox_display">
<form action="#">
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Max. Temp.</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Min. Temp</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Rainfall</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Pressure</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Humidity</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Wind Speed</label>
</form>
</div>
<script>
function initAutocomplete() {
weather_city = new google.maps.places.Autocomplete(
(document.getElementById('weather_city')),
{types: ['geocode']});
weather_city.addListener('place_changed');
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>
<script>
var longitude;
var latitude;
function initalize(arr) {
var lon = arr.city.coord.lon;
var lat = arr.city.coord.lat;
var mapProp = {
center:new google.maps.LatLng(lat,lon),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
</script>
<div id="googleMap" style="width:600px;height:480px;"></div>
<section>
<div id="table">
<!--
<tr>
<td class="hidden">example</td>
<td class="hidden"></td>
<td class="hidden"></td>
</tr>
-->
</div>
</section>
<script>
function getJson(request) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", request, true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
}
function fetchUrl() {
var form = document.getElementById("form");
var city = form.weather_city.value;
var value = form.weather_scale.value;
var days = form.weather_numberOfDays.value;
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
getJson(url);
return false;
}
function myFunction(response) {
var arr = JSON.parse(response);
initalize(arr);
var i;
var out = "<table>";
for(i = 0; i < arr.list.length; i++) {
out += "<tr><td>" +
new Date(arr.list[i].dt * 1000) +
"</td></tr>" +
"<tr><td>" +
getIcon(arr.list[i].weather[0].icon) +
"</td><td>" +
arr.list[i].weather[0].description +
"</td><tr>" +
"</tr><td>" +
"Min. Temperature" +
"</td><td>" +
arr.list[i].temp.min +
"</td><tr>" +
"</tr><td>" +
"Max. Temperature" +
"</td><td>" +
arr.list[i].temp.max +
"</td><tr>" +
"</tr><td>" +
"Pressure" +
"</td><td>" +
arr.list[i].pressure +
"</td><tr>" +
"</tr><td>" +
"Windspeed" +
"</td><td>" +
arr.list[i].speed +
"</td><tr>" +
"</tr><td>" +
"Humidity" +
"</td><td>" +
arr.list[i].humidity +
"</td><tr>" +
"</tr><td>" +
"Predicted Rainfall" +
"</td><td>" +
arr.list[i].rain +
"</td><td>";
}
out += "</table>";
document.getElementById("table").innerHTML = out;
}
function getIcon(s) {
return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
</script>
<script>
//function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
function showHide() {
var checkbox = document.getElementById("chkbox");
var hiddenInput = document.getElementsByClassName("hidden");
for(var i = 0; i !=hiddenInput.length; i++) {
if(checkbox.checked) {
hiddenInput[i].style.display = "inline";
} else {
hiddenInput[i].style.display = "none";
}
}
}
</script>
</body>
</html>
The simplest means of achieving this, given the current approach, is to convert the HTML of the <td> opening tags from:
"<tr><td>"
to:
"<tr><td class='example'>"
And then use CSS to style the relevant elements, for example:
.example {
color: #f90;
}
Or, once you've assigned the string of innerHTML, you could simply add this line:
// retrieves the collection of <td> elements from within the
// element with the id of 'table', and uses Array.from() to
// convert that collection into an Array.
// Then iterates over the array of elements using
// Array.prototype.forEach():
Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
// within the anonymous function the 'td' argument is a reference
// to the current array-element of the array over which we're
// iterating.
// here we use the Element.classList API to add the 'example'
// class-name to the existing (if any) class-names of the <td>
// elements:
td.classList.add('example');
});
body {
background: white;
}
h1 {
color: black;
font-size: 35px;
text-align: center;
font-family: 'Quicksand', sans-serif;
}
h2 {
font-family: 'Quicksand', sans-serif;
margin-left: 3.3em;
}
table, th , td {
border: none;
border-collapse: collapse;
padding: 15px;
margin-left: 5em;
margin-top: -25em;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
#form {
font-family: 'Quicksand', sans-serif;
margin-left: 5em;
}
#googleMap {
margin-left: 45em;;
margin-right: auto;
}
#chkbox_display {
margin-left: 5em;
margin-top: 3em;
font-family: 'Quicksand', sans-serif;
}
.hidden {
display: none;
}
.example {
color: #f90;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<title>Weather App</title>
</head>
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>
<h2>Please enter the following information:</h2>
<form id="form" onsubmit ="return fetchUrl()">
Enter your City:<br>
<input id="weather_city" placeholder="Entere here..."><br>
How to display values: <br>
<select id="weather_scale">
<option value="Metric">Metric Units (Celcius/mm)</option>
<option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
</select><br>
Number of days to show weather:<br>
<select id="weather_numberOfDays">
<option value="1">Today only</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="4">4 days</option>
<option value="5">5 days</option>
</select>
<br><br>
<button onclick="initialize">Submit</button>
</form>
<div id="chkbox_display">
<form action="#">
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Max. Temp.</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Min. Temp</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Rainfall</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Pressure</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Humidity</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Wind Speed</label>
</form>
</div>
<script>
function initAutocomplete() {
weather_city = new google.maps.places.Autocomplete(
(document.getElementById('weather_city')),
{types: ['geocode']});
weather_city.addListener('place_changed');
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>
<script>
var longitude;
var latitude;
function initalize(arr) {
var lon = arr.city.coord.lon;
var lat = arr.city.coord.lat;
var mapProp = {
center:new google.maps.LatLng(lat,lon),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
</script>
<div id="googleMap" style="width:600px;height:480px;"></div>
<section>
<div id="table">
<!--
<tr>
<td class="hidden">example</td>
<td class="hidden"></td>
<td class="hidden"></td>
</tr>
-->
</div>
</section>
<script>
function getJson(request) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", request, true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
}
function fetchUrl() {
var form = document.getElementById("form");
var city = form.weather_city.value;
var value = form.weather_scale.value;
var days = form.weather_numberOfDays.value;
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
getJson(url);
return false;
}
function myFunction(response) {
var arr = JSON.parse(response);
initalize(arr);
var i;
var out = "<table>";
for(i = 0; i < arr.list.length; i++) {
out += "<tr><td>" +
new Date(arr.list[i].dt * 1000) +
"</td></tr>" +
"<tr><td>" +
getIcon(arr.list[i].weather[0].icon) +
"</td><td>" +
arr.list[i].weather[0].description +
"</td><tr>" +
"</tr><td>" +
"Min. Temperature" +
"</td><td>" +
arr.list[i].temp.min +
"</td><tr>" +
"</tr><td>" +
"Max. Temperature" +
"</td><td>" +
arr.list[i].temp.max +
"</td><tr>" +
"</tr><td>" +
"Pressure" +
"</td><td>" +
arr.list[i].pressure +
"</td><tr>" +
"</tr><td>" +
"Windspeed" +
"</td><td>" +
arr.list[i].speed +
"</td><tr>" +
"</tr><td>" +
"Humidity" +
"</td><td>" +
arr.list[i].humidity +
"</td><tr>" +
"</tr><td>" +
"Predicted Rainfall" +
"</td><td>" +
arr.list[i].rain +
"</td><td>";
}
out += "</table>";
document.getElementById("table").innerHTML = out;
Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
td.classList.add('example');
});
}
function getIcon(s) {
return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
</script>
<script>
//function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
function showHide() {
var checkbox = document.getElementById("chkbox");
var hiddenInput = document.getElementsByClassName("hidden");
for(var i = 0; i !=hiddenInput.length; i++) {
if(checkbox.checked) {
hiddenInput[i].style.display = "inline";
} else {
hiddenInput[i].style.display = "none";
}
}
}
</script>
</body>
</html>
This does, of course, assume that you're correct that you need to append class-names to the elements; with no explanation of the problem you're trying to solve by adding the class-names it's hard to offer better advice.
I suggest you to use 'knockoutjs' for filling in the table by returned Json data. For your purpose it is really suitable. Its absolutely easy to learn. If you interested in this approach you may ask me questions in comments. And i will trying to help you to solve your particular problem.
Reference: Knockout tutorial

Categories