<div> gets an automatic width without initialization in html - javascript

I created a maze that gets the height and width values from user. I gave a background color to maze object, but I want the background width to be the same size as the width of the maze. If the maze's width is getting bigger the background gets bigger as well. How can I do that? this is my html code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
.mze
{
color: Blue;
text-align: center;
background-color: Yellow;
width: 100%;
}
.prompt
{
background-color: Yellow;
color: Red;
}
</style>
<script src="mazegenerator.js"></script>
<title>Maze</title>
</head>
<body>
<div id="maze">
<form style="text-align: center" name="forma1">
<br/>
<label>
HEIGHT: </label>
<input type="text" id="height" name="height" autofocus="autofocus"
maxlength="2" size="6" value="" />
<label>
WIDTH: </label>
<input type="text" id="width" name="width" maxlength="2" size="6" value="" />
<br/>
<br/>
<span id="prompt"></span>
<br/>
<input type="button" alt="submit" onclick="CreateMaze();"
value="Generate" style="margin-top: 10px;">
</form>
</div>
<div id="Mzobj" align="center">
<pre id="out" class="mze"></pre>
</div>
</body>
</html>
this is the js part where I get the value from user:
function CreateMaze(){
//gets the value of Height & Width from user
var a = parseInt(document.getElementById("height").value);
var b = parseInt(document.getElementById("width").value);
//Values of Height and Width can't be zero
if (a == 0) {
document.getElementById('prompt').innerHTML = "<b>height</b> is invalid";
document.getElementById('prompt').className = "prompt";
return;
}
if (b == 0) {
document.getElementById('prompt').innerHTML = "<b>width</b> is invalid";
document.getElementById('prompt').className = "prompt";
return;
}
//Width can't be smaller than height
if (a > b) {
document.getElementById('prompt').innerHTML = "not possible";
document.getElementById('prompt').className = "prompt";
}
else {
document.getElementById('prompt').innerHTML = "";
document.getElementById('prompt').className = "";
}
document.getElementById('out').innerHTML = display(maze(a,b));
}
//Display the maze
function display(m) {
var text= [];
for (var j= 0; j<m.x*2+1; j++) {
var line= [];
if (0 == j%2)
for (var k=0; k<m.y*4+1; k++)
if (0 == k%4)
line[k]= '+';
else
if (j>0 && m.verti[j/2-1][Math.floor(k/4)])
line[k]= ' ';
else
line[k]= '-';
else
for (var k=0; k<m.y*4+1; k++)
if (0 == k%4)
if (k>0 && m.horiz[(j-1)/2][k/4-1])
line[k]= ' ';
else
line[k]= '|';
else
line[k]= ' ';
if (0 == j) line[1]=line[3]=' ',line[2]= 'S';
if (m.x*2-1 == j) line[4*m.y]= 'E';
text.push(line.join('')+'\r\n');
}
return text.join('');
this is the image of what I get:

As long as the width entered by the user is in pixels you can add the following code at the end of your 'CreateMaze()` function...
document.getElementById("Mzobj").setAttribute("style", "width:" + b + "px");
If not then you will need to figure out how to convert the entered width to a measurement that will work in an HTML page. If it is the number of characters across then you need to figure out how many units that a character in the font takes up and calculate it. var width = <number units per character> * <number of characters> The link below should help with units.
http://desource.uvu.edu/dgm/2740/IN/steinja/lessons/05/l05_03.html?m=1

Related

Generate Header for txt file

I am generating a default header for a given file and I want the sender ID to have 4 characters and the sender Name to have 45 characters. if they are less than 4 and 45 respectfully, I need to enter spaces to have the 4 or 45 characters. How can I do this?
In the figure below as you can see there are not filled in the necessary spaces for when I do blank file. And even if I write something on the sender ID or the sender Name nothing is added.
What am I doing wrong?
function download(fileName, text) {
let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("generate").addEventListener("click", function(){
// Generate .txt file header
//force 4 chars
let id = document.getElementById("senderID");
if (id.textContent.length < 4) {
id.textContent += ' ';
}
//force 45 chars
let name = document.getElementById("senderName");
if (name.textContent.length < 45) {
name.textContent += ' ';
}
let header = "HDRPB" + id.textContent + name + "01.10";
let body = document.getElementById("fileContents").textContent;
let text = header;
let fileName = document.getElementById("fileName").value + ".txt";
download(fileName, text);
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/site.css">
<title>Generator</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-2 p-0 mt-2">
<label for="senderID" class="font-weight-bold">Sender ID:</label>
<input id="senderID" type="text" maxlength="4" size="4"/>
</div>
<div class="col-6 p-0 mt-2">
<label for="senderName" class="font-weight-bold">Sender Name:</label>
<input id="senderName" type="text" maxlength="45" size="45"/>
</div>
</div>
<div class="row mt-5">
<div class="col-10">
<label for="fileName" class="font-weight-bold">File Name:</label>
<input id="fileName" type="text"/>
</div>
<div class="col-2">
<button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
</div>
</div>
<div id="fileContents" class=""></div>
</div>
<script src="js/app.js"></script>
</body>
</html>
Consider the following code:
function genId(seed) {
var result = new Array(4);
for (var i = 0; i < 4; i++) {
result[i] = seed[i] || " ";
}
return result.join("");
}
function genName(seed) {
var result = new Array(45);
for (var c = 0; c < 45; c++) {
result[c] = seed[c] || " ";
}
return result.join("");
}
document.getElementById("genHead").addEventListener("click", function() {
var i = document.getElementById("hid").value;
var n = document.getElementById("hname").value;
var header = genId(i) + genName(n);
document.getElementById("results").innerHTML = header;
});
#results {
font-family: monospace;
border: 1px solid #ccc;
display: inline-block;
}
<p>ID: <input type="text" id="hid" /></p>
<p>Name: <input type="" id="hname" /></p>
<button id="genHead">Generate Header</button>
<div id="results"></div>
In this example, I am creating an Array of the specific number of characters. String is considered an Array of Characters anyway. I am using $nbsp; to represent spaces in HTML but you can use ' ' or " ".
There will always be a result due to result[c] = seed[c] || " "; If seed has a character in that position, it will be entered into result at the same position. Otherwise it will enter the No Break Space or the character you want.
You can also do this:
function formatText(t, n, c) {
if(t == undefined){
return "";
}
if(n == undefined){
n = 45;
}
if(c == undefined){
c = " ";
}
var r = new Array(n);
for (var i = 0; i < n; i++) {
r[i] = t[i] || c;
}
return r.join("");
}
Then use like so:
var i = formatText("12", 4, " ");
var n = formatText("test", 45, " ");
Hope this helps.

Show Character Limit From Textarea On Cloned Row

[EDIT] Revising original question for better clarity
This section of this form allows the user to add as many rows as necessary, and works. My problem is that I cannot figure out how to make the character count work on the textarea of the cloned rows.
(Thanks to zer00ne for the all the awesome help here. Great, concise coding! Also provided a jQuery character count in a fraction of lines compared to my former Javascript code.)
Here's a fiddle: https://jsfiddle.net/RationalRabbit/2vmqk26b/4/
CSS
textarea,
output,
button {font-size:inherit;}
output:nth-of-type(n+2) {margin-left:3px;}
.msg {border:none;}
.clearfix:before,
.clearfix:after {display:table; content: "";}
.clearfix:after {clear:both;}
.RowDeleteButton {float:right; font-family:arial, sansserif; font-size:14px; display:inline-block; text-decoration:none; color:#AC0F0F; font-weight:900; cursor:pointer;}
.RowDeleteButton:hover, .RowDeleteButton:focus {color:#FF0000;}
HTML
<fieldset>
<div class="parent-group">
<div class="form-group">
<input id="Name" name="Name[]" size="20" value="" />
<input type="checkbox" id="HM" name="HM[]" value="X" />
<textarea class="txt" id="TA" rows="1" cols="30" name="TA[]" maxlength="100"></textarea>
<input class='msg' name="Output" id="Output" size="3" readonly value="100" />
<input type="text" name="Location[]" id="Location" size="30" value="" />
<div class="form-group RowDelete">
<a class="RowDeleteButton" id="DeleteRow" href="javascript:void(0)"> X </a>
</div>
<div class="Clear"></div>
</div>
</div>
<div class="clearfix"></div>
<div id="container"></div>
<div class="form-group">
<a id="AddRow" href="javascript:void(0)"><span style="color:#0F61AC;">Add Row</span></a>
</div>
</fieldset>
jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
// onkeyup invoke charCount
$('.txt').on('keyup', charCount);
// onclick...
$('#DeleteRow').closest('.form-group').hide();
$('#AddRow').on('click', function (e)
{
var len = $('.child-border').length;
$('.parent-group').clone(true, false).find(':input').each(function (idx, ele)
{
ele.name = ele.name + len;
ele.id = ele.id + len;
ele.value = '';
}).end().find('.form-group').toggle(true).end()
.toggleClass('parent-group child-border').hide()
.appendTo('#container').slideDown('slow');
});
$('#container').on('click', '[id^=DeleteRow]', function(e)
{
var jsonData = $(this).closest('.child-border, .parent-group')
.find(':input:not(button)').get()
.reduce(function (acc, ele)
{
acc[ele.name || ele.id] = ele.value;
return acc;
}, {});
$(this).closest('.child-border, .parent-group').remove();
console.log(jsonData);
});
function charCount(e)
{
// Get the text
var chars = this.value;
// Get maxlength as a number
var charMax = Number(this.getAttribute('maxlength'));
// Number of chars typed
var charDone = chars.length;
// Chars remaining is 100 - chars typed
var charToGo = charMax - charDone;
// Display chars remaining
$(this).next('.msg').val(charToGo);
}
</script>
2nd Update
I already said what the issue was in Update 1:
$('.parent-group').clone(true, false).find(':input')
🔺
The second parameter should be true
This will allow the clone() method to keep registered events on the clone. Notice I had said the same thing on the 1st Update, but I failed to change the code in Demo 2.
Demo 3 is a heavy modification of the most currently updated OP code. It is fully functional and it retains registered events on clones just like Demo 2. Added features are: local/sessionStorage, sends data to a live test server, and displays server response.
Demo 4 is OP code and one simple change...want to take a wild guess as to what that might be?.
1st Update
When cloning, use the first parameter to determine whether the clone keeps the registered event handlers the original node has.
$('#original').clone(true, true);
See Demo 2
Not sure what you mean by "one row". This demo is streamlined compared to OP code. I added auto height instead of cloning rows.
Details commented in demo
Demo 1
// On keyup...
$('#txt').on('keyup', function() {
// Get the text
var chars = this.value;
// if there are any linebreaks...
if (chars.match(/\n/g)) {
/* The value of rows attribute equals
|| the number of line breaks +2
*/
this.rows = chars.match(/\n/g).length + 2;
}
/* Get value of maxlength attribute convert
|| to number
*/
var charMax = Number(this.getAttribute('maxlength'));
// Number of chars typed
var charDone = chars.length;
// Chars remaining is 100 - chars typed
var charToGo = charMax - charDone;
// Display chars remaining
$('#msg').val(charToGo + ' characters remaining');
});
<textarea id='txt' rows="1" cols="30" maxlength="100"></textarea><br>
<output id='msg' for='txt'></output>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Demo 2
// onkeyup invoke charCount
$('.txt').on('keyup', charCount);
// onclick...
$('button').on('click', function() {
/* clone the first .txt and .msg
|| true: keep registered events
|| false: copy content
|| set .val('') to blank
|| add to fieldset
*/
$('.txt:first').clone(true, true).val('').appendTo('fieldset');
$('.msg:first').clone(true, true).val('').appendTo('fieldset');
});
function charCount(e) {
// Get the text
var chars = this.value;
// Get maxlength as a number
var charMax = Number(this.getAttribute('maxlength'));
// Number of chars typed
var charDone = chars.length;
// Chars remaining is 100 - chars typed
var charToGo = charMax - charDone;
// Display chars remaining
$(this).next('.msg').val(charToGo + ' characters remaining');
}
textarea,
output,
button {
font-size: inherit
}
output {
display: inline-block;
vertical-align: top;
}
output:nth-of-type(n+2) {
margin-left: 3px
}
button {
margin-left: 90%
}
<button type='button'>Add</button>
<fieldset>
<textarea class='txt' rows="1" cols="30" maxlength="100"></textarea>
<output class='msg'></output>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Demo 3
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title></title>
<style>
textarea,
output,
button {
font-size: inherit;
}
output:nth-of-type(n+2) {
margin-left: 3px;
}
.msg {
border: none;
}
.clearfix:before,
.clearfix:after {
display: table;
content: "";
}
.clearfix:after {
clear: both;
}
.del {
float: right;
margin-top: .5px;
font-family: arial, sansserif;
font-size: 14px;
display: inline-block;
text-decoration: none;
color: #AC0F0F;
font-weight: 900;
cursor: pointer;
}
.del:hover,
.del:focus {
color: #FF0000;
}
main {
display: table;
}
</style>
<script>
/* Global counter variable */
var counter = 0;
</script>
</head>
<body>
<main class="main-group">
<!--This form submits to a live test server, the [target] attribute value
is that of an iframe's name attribute. By targeting the iframe the
form can display the test server's response in the iframe
-->
<form id='main' action='https://httpbin.org/post' method='post' target='response'>
<!--The original fieldset is cloned-->
<fieldset id='set' class="form-group">
<button id="del" class='ui del' type='button'> X </button>
<input id='ID' name='ID' class='data' type='hidden'>
<input id="name" name="name" class='data name' size="25">
<input id="chx" name="chx" class='data chx' type="checkbox" value="X">
<br>
<textarea id="txt" name="txt" class='data txt' rows="1" cols="30" maxlength="100"></textarea>
<output class='ui msg'></output>
<br>
<input id="loc" name="loc" class='data loc' size="30">
</fieldset>
</form>
<nav class="btn-group">
<a id="add" href="#/" class='ui'> <b style="color:#0F61AC;">Add Row</b> </a>
<!--This submit button must use the [form] attribute with the ID of the
form to be accociated with-->
<input type='submit' form='main' class='ui'>
</nav>
<iframe src='about:blank' name='response' class='ui'></iframe>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Click...
$('#add').on('click', function(e) {
// Increment counter
counter++;
/* clone fieldset#set true: clone descendants /
|| TRUE: KEEP EVENTS ON CLONES
|| Gather all of the .data in clone then on each clone...
*/
var dupe = $('#set').clone(true, true);
dupe[0].id = 'set' + counter;
dupe.find('.data').each(function(idx, ele) {
// Set all .data with name and id, the counter suffix makes them unique
ele.name = this.name + counter;
ele.id = this.id + counter;
// Clear all data in each .data
ele.value = '';
// Cool animation and append clone to form#main
}).end().find('.form-group').toggle(true).end().hide().appendTo('#main').slideDown('slow');
// Clear .ui of data
dupe.find('output').val('');
dupe.find(':checkbox').prop('checked', false);
});
// Clicking any button.del...
$('.del').on('click', function(e) {
// Define arrays
var jsonData = [];
var JSONKeys = [];
// This collects all accossiated .data of ,del
var dataRow = $(this).nextAll('.data').toArray();
// This map() will create an object literal and add it to an array
jsonData = dataRow.map(function(data, idx) {
var D = {};
D.k = data.id;
D.v = data.value;
return D;
});
console.log(jsonData);
// Proceedure to timestamp data
var stamp = new Date();
var jKey = stamp.toJSON();
// Fill an array of keys for future reference
JSONKeys.push(jKey);
/* Store JSON data in sessionStorage (can be localStorage also) */
setData(jKey, jsonData);
// Save an index of the jsondata
setData('JSONKeys', jKey);
// if there's only one fieldset, reset the form if user tries to delete it
if ($('fieldset').is(':only-child')) {
$('#main')[0].reset();
} else {
// Remove fieldset
$(this).parent('.form-group').remove();
}
});
// onkeyup invoke charCount
$('.txt').on('keyup', charCount);
function charCount(e) {
// Get the text
var chars = this.value;
// Get maxlength as a number
var charMax = Number(this.getAttribute('maxlength'));
// Number of chars typed
var charDone = chars.length;
// Chars remaining is 100 - chars typed
var charToGo = charMax - charDone;
// Display chars remaining
$(this).next('.msg').val(charToGo);
}
function setData(dataKey, dataVal) {
sessionStorage.setItem(dataKey, JSON.stringify(dataVal));
}
function getData(dataKey) {
return JSON.parse(sessionStorage.getItem(dataKey));
}
</script>
</body>
</html>
Demo 4
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title></title>
</head>
<body>
<fieldset>
<div class="parent-group">
<div class="form-group">
<input id="Name" name="Name[]" size="20" value="" />
<input type="checkbox" id="HM" name="HM[]" value="X" />
<textarea class="txt" id="TA" rows="1" cols="30" name="TA[]" maxlength="100"></textarea>
<input class='msg' name="Output" id="Output" size="3" readonly value="100" />
<input type="text" name="Location[]" id="Location" size="30" value="" />
<div class="form-group RowDelete">
<a class="RowDeleteButton del" href="javascript:void(0)"> X </a>
</div>
<div class="Clear"></div>
</div>
</div>
<div class="clearfix"></div>
<div id="container"></div>
<div class="form-group">
<a id="AddRow" href="javascript:void(0)"><span style="color:#0F61AC;">Add Row</span></a>
</div>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
// onclick...
$('#DeleteRow').closest('.form-group').hide();
$('#AddRow').on('click', function(e) {
var len = $('.child-border').length;
$('.parent-group').clone(true, true).find(':input').each(function(idx, ele) {
ele.name = ele.name + len;
ele.id = ele.id + len;
ele.value = '';
}).end().find('.form-group').toggle(true).end()
.toggleClass('parent-group child-border').hide()
.appendTo('#container').slideDown('slow');
});
$('.del').on('click', function(e) {
var jsonData = $(this).closest('.child-border, .parent-group')
.find(':input:not(button)').get()
.reduce(function(acc, ele) {
acc[ele.name || ele.id] = ele.value;
return acc;
}, {});
$(this).closest('.child-border, .parent-group').remove();
console.log(jsonData);
});
function charCount(e) {
// Get the text
var chars = this.value;
// Get maxlength as a number
var charMax = Number(this.getAttribute('maxlength'));
// Number of chars typed
var charDone = chars.length;
// Chars remaining is 100 - chars typed
var charToGo = charMax - charDone;
// Display chars remaining
$(this).next('.msg').val(charToGo);
}
// onkeyup invoke charCount
$('.txt').on('keyup', charCount);
</script>
</body>
</html>
Using zer00ne's Demo 4, this is what I finally came up with. the differences are:
1. Set the first working row as array for database insert using regex. Also designated unique row input id's using parentheses.
2. Set delete button so that it does not appear on first row.
3. My script sets a max number of rows (8).
4. Global variable used to hold row count. Important in the event that the user deletes a row or rows in the middle of the set, then adds rows below.
5. Set checkbox so that the value is kept in cloned rows. "checked" set to false.
The PHP shows how I handled the array server-side so that I come out with arrays in numerical order. This could probably be handled differently, but worked for me. Without using the LastArrayValue variable to handle the last array value, and the ChildCount variable, which says how many rows there actually are, if you delete, for instance, rows 2 & 3 out of eight, you would only have 6 rows, but not be allowed to add additional. Also, without those variables, when rows are deleted in the middle, you will end up with duplicate array keys. This becomes even more critical when you have a max number of rows to deal with.
https://jsfiddle.net/uyz2zjj6/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title></title>
<style type="text/css">
textarea,
output,
button {font-size:inherit;}
output:nth-of-type(n+2) {margin-left:3px;}
.msg {border:none;}
.clearfix:before,
.clearfix:after {display:table; content: "";}
.clearfix:after {clear:both;}
.RowDeleteButton {float:right; font-family:arial, sansserif; font-size:14px; display:inline-block; text-decoration:none; color:#AC0F0F; font-weight:900; cursor:pointer;}
.RowDeleteButton:hover, .RowDeleteButton:focus {color:#FF0000;}
</style>
</head>
<body>
<fieldset>
<div class="parent-group">
<div class="form-group">
<input id="Name(0)" name="Name[0]" size="20" value="" />
<input type="checkbox" id="HM(0)" name="HM[0]" value="X" />
<textarea class="txt" id="TA(0)" rows="1" cols="30" name="TA[0]" maxlength="100"></textarea>
<input class='msg' name="Output" id="Output(0)" size="3" readonly value="100" />
<input type="text" name="Location[0]" id="Location(0)" size="30" value="" />
<div class="form-group" style="display:inline-block;">
<a class="RowDeleteButton del" id="DeleteRow" href="javascript:void(0)"> X </a>
</div>
<div class="Clear"></div>
</div>
</div>
<div class="clearfix"></div>
<div id="container"></div>
<div class="form-group">
<a id="AddRow" href="javascript:void(0)"><span style="color:#0F61AC;">Add Row</span></a>
</div>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
// onclick...
window.LastArrayValue = 0;
$('#DeleteRow').closest('.form-group').hide();
$('#AddRow').on('click', function(e)
{
var ChildCount = $('.child-group').length;
if(ChildCount == 7)
{
alert("Sorry, 8 is the maximum number of rows");
}
else
{
var len = window.LastArrayValue;
window.LastArrayValue = len + 1;
$('.parent-group').clone(true, true).find(':input').each(function(idx, ele)
{
var ename = ele.name;
var eid = ele.id
var ArrayValue = len+1;
ele.name = ename.replace(/(\[\/?[^\]]*\])/g, "["+ArrayValue+"]");
ele.id = eid.replace(/(\(\/?[^\]]*\))/g, "("+ArrayValue+")");
if(ele.type == "checkbox"){ele.checked = false;}
else{ele.value = '';}
}).end().find('.form-group').toggle(true).end()
.toggleClass('parent-group child-group').hide()
.appendTo('#container').slideDown('slow');
}
});
$('.del').on('click', function(e)
{
var jsonData = $(this).closest('.child-group, .parent-group')
.find(':input:not(button)').get()
.reduce(function(acc, ele)
{
acc[ele.name || ele.id] = ele.value;
return acc;
}, {});
$(this).closest('.child-group, .parent-group').remove();
console.log(jsonData);
});
function charCount(e)
{
// Get the text
var chars = this.value;
// Get maxlength as a number
var charMax = Number(this.getAttribute('maxlength'));
// Number of chars typed
var charDone = chars.length;
// Chars remaining is 100 - chars typed
var charToGo = charMax - charDone;
// Display chars remaining
$(this).next('.msg').val(charToGo);
}
// onkeyup invoke charCount
$('.txt').on('keyup', charCount)
</script>
</body>
</html>
PHP
// Get the last key number in the array in the event that rows were deleted
// TA is the only required field. If that field is not filled, the row is ignored
end($_POST['TA']); // move the internal pointer to the end of the array
$key = key($_POST['TA']); // fetches the key of the element pointed to by the internal pointer
$Ct = $key+1; // account for array start at 0
reset($_POST['TA']); // Reset the array back to the top for processing.
$j=0; // Count only if TA has a value (revaluate $Ct when complete for later use ($Ct = $j))
for($i=0;$i<$Ct;$i++)
{
if(empty($_POST['TA'][$i])) // Empty may be that field is empty or there is no such row.
{
continue;
}
$Name[$j] = $_POST['Name'][$i];
$HM[$j] = $_POST['HM'][$i];
$TA[$j] = $_POST['TA'][$i];
$Location[$j] = $_POST['Location'][$i];
$j++;
}
$Ct = $j; // $Ct now holds the number of records and those records are in numerical order, 1-8

HTML paragraph isnt going into a straight line

I'm kinda new to programming and I cant solve this problem. The paragraphs are coming out like a stair case.
p
p
p
p
p
The p's are examples, but here is all the code I have done so far.
Keep in mind I'm not the best at css(I'm still learning)
All help would be appreciated
Please show me on how I an fix this problem, and tell me where in my code is this problem occurring.
I tried google but couldn't find anything...
var house = {}
function House() {
var msg = 'This house is painted'
var bath;
var bed;
var cook;
var Paint = document.getElementById('paint').value;
var square = document.getElementById('Square').value;
var bath = document.getElementById('bath').value;
var bed = document.getElementById('Bed').value
var cook = document.getElementById('Cook').value;
//Get paragraphs to store values
var paint = document.getElementById('isPaint');
var squareFeet = document.getElementById('sq_Feet')
var bathRoom = document.getElementById('bathroom')
var bedRoom = document.getElementById('BedRoom')
var kitchen = document.getElementById('kitchen');
if(Paint == 'Yes' || Paint == 'yes') {
house['isPainted'] = true;
paint.innerHTML = msg;
}
else if(Paint == 'No' || Paint == 'no') {
house['isPainted'] = false;
var msg = 'this house is not painted'
paint.innerHTML = msg;
}
else if(Paint == '') {
house['isPainted'] = undefined;
var msg = 'no details given';
paint.innerHTML = msg;
}
if(square != '' ) {
var squareFeetMsg = 'the house is';
squareFeet.innerHTML = squareFeetMsg + ' ' + document.getElementById('Square').value + ' square feet';
house['squareFeet'] = document.getElementById('Square').value
}else {
var squareFeetMsg = 'No Details Given';
squareFeet.innerHTML = squareFeetMsg;
}
}
body {
width: auto;
height: auto;
}
#houseDtails{
width: 350px;;
}
#container {
width: auto;
height: auto;
}
.houseDetails {
height: 0px;
float: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>House App</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="conatainer">
<div id="houseDtails">
<label for="paint">Is this house painted: </label><br>
<input type="text" id="paint" class="Detail" /><br>
<label for="Square">How many SQ feet does this have? :</label>
<input type="text" id="Square"><br>
<label for="bath">How many bathrooms does your house have</label>
<input type="text" id="bath"><br>
<label for="Bed">How many bedrooms dos your house have</label>
<input type="text" id="Bed"><br>
<label for="Cook">Does your house have a kitchen</label>
<input type="text" id="Cook"><br>
<input type="submit" name="" id="sub" class="subm" onclick="House()">
</div>
<div id="addDetailsToPage">
<p id="isPaint" class="houseDetails"></p>
<p id="sq_Feet" class="houseDetails"></p>
<p id="bathroom" class="houseDetails"></p>
<p id="Bedroom" class="houseDetails"></p>
<p id="Kitchen" class="houseDetails"></p>
</div>
</div>
<script src="House.js"></script>
</body>
The reason for the paragraphs rendering in that manner is result of float set on .houseDetails.
.houseDetails {
height: 0;
float: right;
}
This is because you have float: right; in your CSS for .houseDetails. Remove it and you should have your p aligned on the left below one another

How to write javascript code for BMI_Calculator.html?

I'm supposed to write javascript code for an html page that will calculate a persons BMI and tell them what it means (the number). The rules of the test were to not change the html on the page, but to just write the javascript code and link it to the html page. That's all. I have copied the html page just in case you guys might wanna have a look at it. Here is what the BMI Calculator is supposed to do using javascript:
Person enters name, selects gender, enters weight and height. The application will calculate the persons BMR, BMI, and tell what it means (i.e. saying "you are too thin", "you are healthy", or "you are overweight").
and it will display an image of a thin, healthy, or overweight person which is a png image.
If they do not enter a name, an error message prompts them to enter a name. The name must be at least five characters long.
If they do not select a gender, then an error message prompts them to please select a gender. The gender is represented by a radio button. The user selects male or female.
If the user does not enter a weight, an error message prompts them to please enter a weight.
If height is not entered, an error message prompts them to please enter a height.
If you are a male, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age+5).
If you are a female, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age-161).
If the BMI is less than 18.5: "you are too thin".
If the BMI is between 20 to 25: "you are healthy".
If the BMI is greater than 25: "you are overweight".
Also, please don't put the question on hold or delete it. This is important for me and I need help. If you want help, please don't. It took me a long time to write this question.
Here is the html that I am supposed to write the javascript code for:
<html>
<head>
<title> BMI Calculator </title>
<style>
label {
display: inline-block;
width: 80px;
height: 25px;
}
button {
height:30px;
margin: 5px 0px;
}
fieldset {
display: inline-block;
}
#errMsg {
color: red;
}
#frm {
float: left;
width: 30%;
}
#imgSec {
float: left;
padding: 5px 0px;
border-left: 3px solid darkblue;
}
</style>
<!-- link to javascript file -->
<script type="text/javascript" src="BMI_javascript.js">
</script>
</head>
<body>
<div id="title"><h3>BMI Calculator</h3></div>
<section id="frm">
<form name="bmiForm" onsubmit="return false;">
<fieldset>
<legend>Enter your Details:</legend>
<label for="user">Name:</label>
<input type="text" id="user" size="25" required> <br />
<label for="gender">Gender:</label>
<input type="radio" id="rbMale" name="gender"> Male
<input type="radio" id="rbFemale" name="gender">Female <br />
<label for="age">Age:</label>
<input type="number" id="age" size="10" required> <br />
<label for="weight">Weight(kg):</label>
<input type="number" id="weight" size="10" required> <br />
<label for="height">Height(cm):</label>
<input type="number" id="height" size="10" required> <br />
<div id="errMsg"></div>
</fieldset>
<br>
<button onclick="calculate()">Calculate BMI</button>
<button type="reset" onclick="clearErr()">Reset</button>
<br>
<fieldset>
<legend>Result:</legend>
<label for="bmr">Your BMR: </label>
<input type="text" name="bmr" id="bmr" size="18" readonly><br />
<label for="bmi">Your BMI: </label>
<input type="text" name="bmi" id="bmi" size="10" readonly><br />
<label for="meaning">This Means: </label>
<input type="text" name="meaning" id="meaning" size="25" readonly><br/>
</fieldset>
</section>
<section id="imgSec">
<img id="img" src="" height="250px">
</section>
</form>
</body>
</html>
And here is the javascript I wrote for it. I know it's horrible. The problem is the code does not work. Nothing works.
function GenderType() {
var GenderType = document.getElementsByName("rbMale","rbFemale");
if(rbMale == "Male") {
GenderType.innerHTML = "Male";
} else {
rbFemale == "Female";
GenderType.innerHTML = "Female";
}
}
function validate() {
var name = document.getElementById("name");
var age = document.getElementById("age");
var male = document.getElementById("male");
var female = document.getElementById("female");
var weight = document.getElementById("weight");
var height = document.getElementById("height");
error = false;
var reName = /^[a-zA-Z ]{5,}$/;
if (reName.test(name.value) == false) {
nameError.innerHTML = "Name must be eight letters or more";
error = true;
} else {
nameError.innerHTML = "";
}
age = parseInt(age.value);
if ( isNaN(age) || age < 0 || age > 65) {
ageError.innerHTML = "Age must be in range 0-65";
error = true;
} else {
ageError.innerHTML = "";
}
weight = parseInt(weight.value);
if ( isNaN(weight) || weight < 0) {
weightError.innerHTML = "Weight must be greater than 0";
error = true;
} else {
weightError.innerHTML = "";
}
height = parseInt(height.value);
if (isNaN(height) || height < 0) {
heightError.innerHTML = "height must be greater than 0"
error = true;
} else {
heightError.innerHTML = "";
}
if ( !male.checked & !female.checked) {
genderError.innerHTML = "Select value";
error = true;
} else {
genderError.innerHTML = "";
}
}
function BMRCalculate () {
if ( validate()==false ) {
var GenderType = document.getElementById("rbMale","rbFemale").value;
var age = document.getElementById("age").value;
var female = document.getElementById("rbFemale");
var male = document.getElementById("rbMale");
var weight = document.getElementById("weight");
var height = document.getElementById("height");
var BMIValue = weight/( (height/100)*(height/100) );
var BMRValue;
var ThisMeans = document.getElementById("meaning");
if(GenderType == male) {
BMRValue = 10*(weight+6.25)*(height-5)*(age+5);
} else {
GenderType = female;
BMRValue = 10*(weight+6.25)*(height-5)*(age-161);
}
if (BMIValue<18.5) {
ThisMeans = "you are too thin";
document.write(ThisMeans);
} else if (BMIValue>18.5 && BMIValue<25) {
ThisMeans = "you are healthy";
document.write(ThisMeans);
} else {
ThisMeans = "You are not healthy";
document.write(ThisMeans);
}
}
Mate, #gavgrif gave you some very good tips, but about the code...try to start over and think the problem again.

Web page with JavaScript program's label is not aligning with the other labels/text areas

I apologize for asking silly questions, but I have tried to mess with the CSS and changed very little. I am trying to get the label/dropdown (which says "withdrawal" by default to align with the others and also get rid of some of the space between the text areas so that it looks more like the screenshot provided by my instructor. I did manage to reduce some of the extra space between areas by reducing the pixels, but I am not certain how to get it to look exactly like the screenshot.
If anyone would please give suggestions, I would genuinely appreciate it.
var pad_left = function(text, width, pad) { //sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = pad + result;
}
return result; // populates text area
}
var pad_right = function(text, width, pad) { // sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = result + pad;
}
return result;
}
var getResults = function(results) { // actual calculation functions
if (results.length == 0) {
return "";
}
var balance = 2000; / /actual format of text area
var list = pad_right("Date", 12, " ");
list += pad_right("Amount", 12, " ");
list += pad_right("Running Balance", 15, " ") + "\n";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 15, "-") + "\n";
for (var i = 0; i < results.length; i++) { // loop to calculate balances
var trans = results[i];
list += pad_right(trans["date"], 12, " ");
if(trans["type"] == "withdrawal") // withdrawal calculation
{
balance -= trans["amount"]
list += "$" + pad_left( "-" + trans["amount"].toFixed(2), 11, " ") + " ";
} else { //for Deposits
balance += trans["amount"]
list += "$" + pad_left( trans["amount"].toFixed(2), 11, " ") + " ";
}
list += "$" + pad_left(balance.toFixed(2), 14, " ") + "\n";
}
return list;
}
var get_runningBalance = function(results) { // function to calculate Running Balance
var runningBalance = 0, amount;
for (var i in results) {
runningBalance = startBal - "amount" ;
runningBalance += parseInt(runningBalance.toFixed(2));
}
return runningBalance;
}
var get_startBal = function(transactions){ // fills Starting Balance
return 2000;
}
var get_totalDep = function(transactions){ // function to calculate Total Deposits
var totalDep = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "deposit")
{
totalDep += trans["amount"]
}
}
return totalDep;
}
var get_totalWd = function(transactions){ // function to calculate Total Withdrawals
var totalWd = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
totalWd -= trans["amount"]
}
}
return totalWd;
}
var get_endBal = function(transactions){ // function to calculate Ending Balance
var balance = 2000;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
balance -= trans["amount"]
} else { // Is Deposit
balance += trans["amount"]
}
}
return balance.toFixed(2);
}​
// sets up the global variables and arrays for the functions
var balances = [];
var transactions = [];
var $ = function (id) {
return document.getElementById(id);
}
// pulls the info from text boxes
var update_display = function() {
$("startBal").value = get_startBal(transactions);
$("totalDep").value = get_totalDep(transactions);
$("totalWd").value = get_totalWd(transactions);
$("endBal").value = get_endBal(transactions);
$("date").value = "";
$("amount").value = "";
$("date").focus();
$("results").value = getResults(transactions);
}
// function to add transactions to the text area
var addTrans_click = function () {
var trans = [];
trans["date"] = $("date").value;
trans["amount"] = parseFloat($("amount").value);
trans["type"] = $("type").value;
if (trans["date"] == "") return;
if (isNaN(trans["amount"])) return;
transactions.push(trans);
update_display();
}
// the event handlers
window.onload = function () {
$("addTrans").onclick = addTrans_click;
$("date").focus();
}​
body {
background: none repeat scroll;
font-family: Arial,Helvetica,sans-serif;
}
#content {
background: none repeat scroll;
border: 8px solid gray;
margin: 10px auto;
padding: 5px 20px;
text-align: center;
width: 600px;
}
h1, h2 {
text-align: left;
}
label {
display: block;
float: left;
padding-right: 1em;
text-align: right;
width: 10em;
}
input {
display: block;
float: left;
}
select {
display: block;
text-align: center;
width: 10em;
}
.formLayout label {
float: left;
text-align: right;
width: 10em;
}
.formLayout input {
margin-bottom: 0.5em;
margin-left: 0.5em;
}
.formLayout br {
clear: both;
}
​
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Monthly Balance Calculator</title>
<link href="monthly_balance.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="mbc_library.js"></script>
<script type="text/javascript" src="monthly_balance.js"></script>
</head>
<body>
<div id="content">
<h1>Monthly Balance Calculator</h1>
<br />
<h2>Add Transaction</h2>
<hr />
<br />
<div class="formLayout">
<label for="date">Date:</label>
<input type="text" name="date" id="date" />
<br />
<br />
<label for="type">Type:</label>
<select name="type" id="type">
<option value="withdrawal">Withdrawal</option>
<option value="deposit">Deposit</option>
</select>
<br />
<label for="amount">Amount:</label>
<input type="text" name="amount" id="amount"/>
<br />
<br />
<label> </label>
<input type="button" id="addTrans" value="Add Transaction" />
<br />
</div>
<h2>Transactions</h2>
<hr />
<br />
<textarea name="results" id="results" rows="10" cols="60" disabled="disabled">
</textarea>
<br />
<br />
<h2>Summary</h2>
<hr />
<br />
<div class="formLayout">
<label for="startBal">Starting Balance:</label>
<input type="text" name="startBal" id="startBal"
class="disabled" disabled="disabled"/>
<br />
<br />
<label for="totalDep">Total Deposits:</label>
<input type="text" name="totalDep" id="totalDep"
class="disabled" disabled="disabled"/>
<br />
<br />
<label for="totalWd">Total Withdrawals:</label>
<input type="text" name="totalWd" id="totalWd"
class="disabled" disabled="disabled"/>
<br />
<br />
<label for="endBal">Ending Balance</label>
<input type="text" name="endBal" id="endBal"
class="disabled" disabled="disabled"/>
<br />
<br />
</div>
</body>
</html>
​
Note, I had to add BOTH JS files in the same form because this site only allows me to paste two, despite the fact that I added two to the HTML page
I think this is what you need.
Check with below code.
var pad_left = function(text, width, pad) { //sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = pad + result;
}
return result; // populates text area
}
var pad_right = function(text, width, pad) { // sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = result + pad;
}
return result;
}
var getResults = function(results) { // actual calculation functions
if (results.length == 0) {
return "";
}
var balance = 2000; / /actual format of text area
var list = pad_right("Date", 12, " ");
list += pad_right("Amount", 12, " ");
list += pad_right("Running Balance", 15, " ") + "\n";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 15, "-") + "\n";
for (var i = 0; i < results.length; i++) { // loop to calculate balances
var trans = results[i];
list += pad_right(trans["date"], 12, " ");
if(trans["type"] == "withdrawal") // withdrawal calculation
{
balance -= trans["amount"]
list += "$" + pad_left( "-" + trans["amount"].toFixed(2), 11, " ") + " ";
} else { //for Deposits
balance += trans["amount"]
list += "$" + pad_left( trans["amount"].toFixed(2), 11, " ") + " ";
}
list += "$" + pad_left(balance.toFixed(2), 14, " ") + "\n";
}
return list;
}
var get_runningBalance = function(results) { // function to calculate Running Balance
var runningBalance = 0, amount;
for (var i in results) {
runningBalance = startBal - "amount" ;
runningBalance += parseInt(runningBalance.toFixed(2));
}
return runningBalance;
}
var get_startBal = function(transactions){ // fills Starting Balance
return 2000;
}
var get_totalDep = function(transactions){ // function to calculate Total Deposits
var totalDep = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "deposit")
{
totalDep += trans["amount"]
}
}
return totalDep;
}
var get_totalWd = function(transactions){ // function to calculate Total Withdrawals
var totalWd = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
totalWd -= trans["amount"]
}
}
return totalWd;
}
var get_endBal = function(transactions){ // function to calculate Ending Balance
var balance = 2000;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
balance -= trans["amount"]
} else { // Is Deposit
balance += trans["amount"]
}
}
return balance.toFixed(2);
}​
// sets up the global variables and arrays for the functions
var balances = [];
var transactions = [];
var $ = function (id) {
return document.getElementById(id);
}
// pulls the info from text boxes
var update_display = function() {
$("startBal").value = get_startBal(transactions);
$("totalDep").value = get_totalDep(transactions);
$("totalWd").value = get_totalWd(transactions);
$("endBal").value = get_endBal(transactions);
$("date").value = "";
$("amount").value = "";
$("date").focus();
$("results").value = getResults(transactions);
}
// function to add transactions to the text area
var addTrans_click = function () {
var trans = [];
trans["date"] = $("date").value;
trans["amount"] = parseFloat($("amount").value);
trans["type"] = $("type").value;
if (trans["date"] == "") return;
if (isNaN(trans["amount"])) return;
transactions.push(trans);
update_display();
}
// the event handlers
window.onload = function () {
$("addTrans").onclick = addTrans_click;
$("date").focus();
}​
body {
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
font-family: Arial,Helvetica,sans-serif;
}
#content {
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
border: 8px solid gray;
margin: 10px auto;
padding: 5px 20px;
text-align: center;
width: 600px;
}
h1, h2 {
text-align: left;
}
h2 {
margin-bottom: 0;
padding-bottom: 0;
}
label {
display: block;
float: left;
text-align: right;
width: 10em;
}
input {
display: block;
float: left;
}
select {
display: block;
float: left;
text-align: center;
width: 10em;
margin-bottom: 0.5em;
margin-left: 0.5em;
}
.formLayout label {
float: left;
text-align: right;
width: 10em;
}
.formLayout input {
margin-bottom: 0.5em;
margin-left: 0.5em;
}
.formLayout br {
clear: both;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Monthly Balance Calculator</title>
<link href="monthly_balance.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="mbc_library.js"></script>
<script type="text/javascript" src="monthly_balance.js"></script>
</head>
<body>
<div id="content">
<h1>Monthly Balance Calculator</h1>
<br />
<h2>Add Transaction</h2>
<hr />
<br />
<div class="formLayout">
<label for="date">Date:</label>
<input type="text" name="date" id="date" />
<br />
<label for="type">Type:</label>
<select name="type" id="type">
<option value="withdrawal">Withdrawal</option>
<option value="deposit">Deposit</option>
</select>
<br />
<label for="amount">Amount:</label>
<input type="text" name="amount" id="amount"/>
<br />
<label> </label>
<input type="button" id="addTrans" value="Add Transaction" />
<br />
</div>
<h2>Transactions</h2>
<hr />
<br />
<textarea name="results" id="results" rows="10" cols="60" disabled="disabled">
</textarea>
<br />
<br />
<h2>Summary</h2>
<hr />
<br />
<div class="formLayout">
<label for="startBal">Starting Balance:</label>
<input type="text" name="startBal" id="startBal"
class="disabled" disabled="disabled"/>
<br />
<label for="totalDep">Total Deposits:</label>
<input type="text" name="totalDep" id="totalDep"
class="disabled" disabled="disabled"/>
<br />
<label for="totalWd">Total Withdrawals:</label>
<input type="text" name="totalWd" id="totalWd"
class="disabled" disabled="disabled"/>
<br />
<label for="endBal">Ending Balance</label>
<input type="text" name="endBal" id="endBal"
class="disabled" disabled="disabled"/>
<br />
</div>
</body>
</html>
​

Categories

Resources