I have to make a div triangle like this, with looping in JavaScript. Anyone know how to make this?
*Input using <select> tag. Thanks!
Check this
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var container = $("#html2");
$("#CreateDiv").change(function () {
$('#html2').html('');
var strBlocksHTML = '';
var selectedvalue = $("#CreateDiv option:selected").val();
for (var i = 0; i <= selectedvalue; i++) {
for (var n = 0; n < i ; n++) {
strBlocksHTML += '<div id="pdfDiv" style=" background-color:red; display:inline-block; width:50px; height:50px; margin:2px 5px; border:2px solid #ccc;"> </div>';
}
strBlocksHTML += '<div></div>';
}
$('#html2').append(strBlocksHTML);
})
});
</script>
</head>
<body style="text-align:center">
<div>
<select id="CreateDiv">
<option value="0"> Select</option>
<option value="1"> One</option>
<option value="2"> Two</option>
<option value="3"> There</option>
<option value="4"> Four</option>
<option value="5"> Five</option>
</select>
</div>
<br />
<br />
<div id="html2" style="text-align:center">
</div>
</body>
</html>
Simple double loop. First loop for rows, second for single div.
var levels = 5;
var output = '';
for (var row = 1; row <= levels; row++) {
output += '<div class="row">';
for (var i = 0; i < row; i++) {
output += '<div class="item"></div>'
}
output += '</div>';
}
document.write(output);
.row {
text-align: center;
}
.item {
display: inline-block;
width: 40px;
height: 40px;
border: 1px solid green;
background: gray;
}
Related
I want to implement a button which changes the background colour and text colour instantly. The colours are predefined in an array.
Code Snippet
<?php
include 'src/wordlist.php';
include 'src/colorcodes.php';
$result1 = $one[array_rand($one)] . " " . $two[array_rand($two)];
$colormix1 = $colors[array_rand($colors)];
$colormix2 = $colors[array_rand($colors)];
if ($colormix1 == $colormix2) {
$colormix2 = $colors[array_rand($colors)];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body style="background: <?php echo $colormix2; ?>;">
<div class="table_1">
<table>
<tr>
<th>
HEADER
</th>
</tr>
<tr>
<td>
<p style="color: <?php echo $colormix1; ?>;">» <?php echo $result1; ?>. «</p>
</td>
</tr>
</table>
</div>
</body>
</html>
How can I achieve this with only JavaScript?
Thanks in advance!
//EDIT:
I found a solution:
function changeBackground() {
var colormix1 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
if (colormix1 == colormix2) {
var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
}
document.getElementById("quote").style.color = colormix1;
document.getElementById("footer").style.background = colormix1;
document.getElementById("ft-button").style.backgroundColor = colormix1;
document.getElementById("ft-button").style.color = colormix2;
document.getElementById("background").style.background = colormix2;
}
</script>
By calling the elements by their Id it worked just fine.
It is fairly simple to achieve this in JS. Please refer DOM API for more details
Run this Code Snippet for a demo
function changeBackground(value) {
var bgElement = document.getElementsByClassName('background')[0];
var textElement = document.getElementsByClassName('text')[0];
if (bgElement) {
bgElement.style.background = value;
}
if (textElement) {
textElement.style.color = value;
}
}
.background {
width: 100vw;
height: 100vh;
background: #000;
}
.dropdown {
width: 150px;
height: 32px;
margin: 16px;
}
.text {
font-size: 16px;
color: #000;
margin: 16px;
}
<div class="text">
This is some text
</div>
<div class="background">
<select class="dropdown" onchange="changeBackground(value)">
<option value="#F44336">Red</option>
<option value="#E91E63">Pink</option>
<option value="#9C27B0">Purple</option>
<option value="#673AB7">Deep purple</option>
<option value="#3F51B5">Indigo</option>
<option value="#FFFFFF">White</option>
<option value="#000000">Black</option>
</select>
</div>
I am new in Json and javascript . What I want is a select tag with option, thus by selecting the options - that particular object will be fetched from JSON and will be displayed , I have used Nested JSON .
data.json:
var data = {
"abc":{
"color":["rgb(4,45,97)","rgb(255,122,0)"],
"font":"Interface Thin",
"logo":"<img src='logo.png' width='200' height='150'>"
}
}
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="data.json"></script>
</head>
<body>
<!--document.getElementById('color').innerHTML += '<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.AllenandHanburys[j]+';height:100px"></div>'-->
<p id="demo"></p>
<p id="color"></p>
<p id="logo"></p>
<select id="brand" onChange="run()">
<option>Select Option</option>
<option value="abc">abc</option>
</select>
</body>
<script>
var i;
function run() {
var brand_name=document.getElementById('brand').value;//
for(x in data)
{
if(x==brand_name)
{
for(j in data.brand_name)
{
document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>";
if(j=='color')
{
for(i=0;i<data.abc.color.length;i++)
{
document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>";
}
}
}
}
}
}
</script>
</html>
this line is wrong,
for(j in data.brand_name) //because `brand_name` property is not exist in the object
change it to
for(j in data[brand_name]) //data[brand_name] will parsed as data['abc'] which is same as data.abc
Here's the demo
var data = {
"abc":{
"color":["rgb(4,45,97)","rgb(255,122,0)"],
"font":"Interface Thin",
"logo":"<img src='logo.png' width='200' height='150'>"
}
}
var i;
function run() {
var brand_name=document.getElementById('brand').value;//
for(x in data)
{
if(x==brand_name)
{
for(j in data[brand_name])
{
document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>";
if(j=='color')
{
for(i=0;i<data.abc.color.length;i++)
{
document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>";
}
}
}
}
}
}
<p id="demo"></p>
<p id="color"></p>
<p id="logo"></p>
<select id="brand" onChange="run()">
<option>Select Option</option>
<option value="abc">abc</option>
</select>
I have to create table by clicking button where as table contains columns and rows specified by user. After that,we have to fill each table cell by performing onclick with the color listed in the drop down list menu.
The below code snippet is to create table with user's input. I don't know to proceed further. How to perform this ?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
.highlighted {
background: red;
}
table{
width:500px;
height:500px;
}
table td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
table tr{
height:100px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable" });
var rows = new Number($("#rows").val());
var cols = new Number($("#columns").val());
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
for (var j = 0; j < cols; j++) {
$('<td></td>').text("").appendTo(row);
}
}
console.log("TTTTT:"+mytable.html());
mytable.appendTo("#matrixTableId");
}
</script>
</head>
<body>
Enter Rows <input type='text' id='rows'><br>
Enter Cols <input type='text' id='columns'><br>
<input type="button" onclick="createTable();" name="save" value="Form Matrix" /><br>
Choose Color: <select id="dropDown">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<br><br>
<div id="matrixTableId">
</div>
</body>
</html>
Try this : You can add a click event handler for all td and set background-color as a value from dropDown.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
.highlighted {
background: red;
}
table{
width:500px;
height:500px;
}
table td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
table tr{
height:100px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable" });
var rows = new Number($("#rows").val());
var cols = new Number($("#columns").val());
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
for (var j = 0; j < cols; j++) {
$('<td></td>').text("").appendTo(row);
}
}
console.log("TTTTT:"+mytable.html());
mytable.appendTo("#matrixTableId");
}
$(function(){
$(document).on("click","table tr td", function(){
var color = $('#dropDown').val();
$(this).css('background-color', color);
});
});
</script>
</head>
<body>
Enter Rows <input type='text' id='rows'><br>
Enter Cols <input type='text' id='columns'><br>
<input type="button" onclick="createTable();" name="save" value="Form Matrix" /><br>
Choose Color: <select id="dropDown">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<br><br>
<div id="matrixTableId">
</div>
</body>
</html>
You should handle onclick event of td and set background of clicked td to select value
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
.highlighted {
background: red;
}
table{
width:500px;
height:500px;
}
table td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
table tr{
height:100px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable" });
var rows = new Number($("#rows").val());
var cols = new Number($("#columns").val());
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
for (var j = 0; j < cols; j++) {
var $td = $('<td></td>');
$td.text("").appendTo(row);
$td.click(function(){
$(this).css('background',$('#dropDown').val());
});
}
}
console.log("TTTTT:"+mytable.html());
mytable.appendTo("#matrixTableId");
}
</script>
</head>
<body>
Enter Rows <input type='text' id='rows'><br>
Enter Cols <input type='text' id='columns'><br>
<input type="button" onclick="createTable();" name="save" value="Form Matrix" /><br>
Choose Color: <select id="dropDown">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<br><br>
<div id="matrixTableId">
</div>
</body>
</html>
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
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help?
Here is my jsfiddle http://jsfiddle.net/clbacon70/x6kjqbop/1/
var gc_fSandwichPrice = 5.99; // Price for each sandwich
var gc_fExtrasPrice = 1.50; // Price for each extra item
// GLOBAL VARS
// Global object vars
var divErrors;
var radSandwich;
var radSize;
var chkExtras;
// Other global vars
var g_fTotal;
var g_sSandwich;
var g_sSize;
var g_sExtras;
window.addEventListener('load', Init);
function Init() {
document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0";
var spanExtrasPrice = document.getElementById("spanExtrasPrice");
var btnCalculateTotal = document.getElementById("btnCalculateTotal");
divErrors = document.getElementById("divErrors");
radSandwich = document.getElementsByName('radSandwich');
radSize = document.getElementsByName('radSize');
chkExtras = document.getElementsByName('chkExtras');
spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2);
btnCalculateTotal.addEventListener('click', CalculateTotal);
} // function Init()
function CalculateTotal() {
divErrors.innerHTML = '';
if (radSandwich[0].checked) {
g_sSandwich = radSandwich[0].value;
} else if (radSandwich[1].checked) {
g_sSandwich = radSandwich[1].value;
} else if (radSandwich[2].checked) {
g_sSandwich = radSandwich[2].value;
} else if (radSandwich[3].checked) {
g_sSandwich = radSandwich[3].value;
} else {
divErrors.innerHTML = "Select a Sandwich";
return;
}
if (radSize[0].checked){
g_fTotal = radSize[0].title;
} else if (radSize[1].checked) {
g_fTotal = radSize[1].title;
} else if (radSize[2].checked) {
g_fTotal = radSize[2].title;
} else {
divErrors.innerHTML = "Please choose a size";
return;
}
if (chkExtras[0].checked) {
g_sExtras = chkExtras[0].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
if (chkExtras[1].checked) {
g_sExtras = g_sExtras + ',' + chkExtras[1].value;
g_fTotal = g_fTotal + gc_fExtrasPrice; }
if (chkExtras[2].checked) {
g_sExtras = g_sExtras +', ' + chkExtras[2].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
var textTotal = document.getElementById('textTotal');
textTotal.value = g_fTotal;
} // function CalculateTotal
function ProcessOrder() {
} // function ProcessOrder
* {
margin: 0;
padding: 0;
}
body {
background-color: #333;
}
#divWrapper {
background-color: #efe;
width: 40em;
border: solid black;
border-radius: 0 0 20px 20px;
border-width: 0 1px 1px 1px;
margin: 0 auto;
padding: 2em 1em;
}
h2 {
font-style: italic;
font-size: 1.3em;
color: #666;
margin-top: 0px;
}
input {
margin-right: 0.3em;
}
h3, p {
margin: 0.5em 0;
}
div#divErrors {
font-size: 110%;
color: white;
background: #f00;
margin-bottom: 0.5em;
}
#divPaymentInfo {
margin: 10px 0 20px 0;
padding-bottom: 10px;
border: solid black;
border-width: 1px 0;
}
#divCreditCardInfo {
font-size: .8em;
visibility: hidden;
margin-left: 1em;
display: inline;
}
#divOrder {
background: white;
min-height: 10em;
width: 25em;
border: 1px solid black;
margin: 0.5em 0;
padding: 10px;
}
<body>
<div id="divWrapper">
<form name="frmMain">
<h1 id="h1Title">Deli Form</h1>
<h2>Part 1</h2>
<h3>Sandwich</h3>
<label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br>
<label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br>
<label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br>
<label><input type="radio" name="radSandwich" value="ReelMeat®">ReelMeat®</label><br>
<br>
<h3>Size</h3>
<label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>
<label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>
<label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label>
<br><br>
<h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3>
<label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br>
<label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br>
<label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br>
<br><br>
Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total">
<br><br>
<div id="divErrors"></div>
<div id="divPaymentInfo">
<h2>Part 2</h2>
<strong>Customer's Name:</strong> <input type="text" id="txtName">
<br><br>
<strong>Payment:</strong>
<select id="selPayment">
<option value="Cash" selected="selected">Cash</option>
<option value="Check">Check</option>
<option value="Credit Card">Credit Card</option>
</select>
<div id="divCreditCardInfo">
Card Number: <input type="text" id="txtCreditCardNbr" size="20">
Month: <input type="text" id="txtMonth" size="2"> Year:
<select id="selYear">
<option value="" selected="selected"></option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2010">2017</option>
<option value="2011">2018</option>
</select>
</div><!-- divCreditCardInfo -->
</div><!-- divPaymentInfo -->
<input type="button" id="btnProcessOrder" value="Process Order">
<div id="divOrder"></div>
<input type="reset" value="Reset">
</form>
</div> <!-- divWrapper -->
</body>
You have a typo in your javascript. You are attempting to fetch an html element with id textTotal, when the field you're interesting in is actually given the id txtTotal.
Fix that typo and it will work.
var textTotal = document.getElementById('textTotal');
Your selector is wrong. The element id of your textbox is txtTotal
so the following should work:
var textTotal = document.getElementById('txtTotal');
Here's a fixed copy of your jsFiddle: http://jsfiddle.net/dcseekcw/
What I fixed:
You were passing in $ along with values you were trying to add as floats. Removed them from your title values and only put it back in after the total is calculated.
Put in parseFloat so values could be added together instead of being concatenated as strings.
Initialised your g_fTotal and chkExtras variables.
Put in some basic checking so that radSize doesn't cause problems when it's not selected.
You have to add brackets after 'Init'.
window.addEventListener('load', Init());
And also there was a typo in the end of CalculateTotal function.
Here is working example:
http://jsfiddle.net/x6kjqbop/3/