How to write a for loop with forms in JavaScript - javascript

I'm new to JS.
I want to write a for-loop in JS that gives out a chosen number of forms.
This is what I got so far. (Maybe I have to write a function. But I have no clue how to continue.)
<!DOCTYPE html>
<html lang="de">
<head>
<title>Survey</title>
<link rel="stylesheet" type="text/css" href="survey.css">
</head>
<body>
<h1><?php echo "Title: ".$_POST["title"];
?></h1>
<script>
var Ausgabe = "";
for (var i = 1; i <= <?php echo $_POST["anzahl"];?>; i++){
Ausgabe = i + ". question: " + <form>
<input type="text" id="title" name="title">
</form>
document.write(Ausgabe)
}
</script>
</body>
</html>
Any tips are welcome.

You could do this with JavaScript:
var Ausgabe = "";
for (var i = 1; i <= <?php echo $_POST["anzahl"];?>; i++){
Ausgabe = i + ". question: " + "<form><input type=\"text\" id=\"title\" name=\"title\"></form>"
document.write(Ausgabe)
}
Adding quotes around the "html" string and escaping the quotes inside it (like type=\"text\").
Anyway I think should be better do the loop directly via PHP, something like:
<?php
for ($i = 1; $i <= anzahl; $i++) {
echo "<form><input type=\"text\" id=\"title\" name=\"title\"></form>";
}
I hope it helps, bye.

I do not know what your goals are, but I think you are trying to do something like this:
var input = prompt('Enter a number (<= 10):'),
html = '';
if (Number(input) <= 10) {
for (var i = 0; i < Number(input); i++) {
html += '<form>';
html += ' <input type="text" placeholder="' + i + '">';
html += '</form>';
}
} else {
console.log('The number is too high!');
}
document.body.innerHTML = html;

Related

Display sum of specific column in Javascript

I wish to display sum of amount for particular region.
Below is my code to display the data, however I am sure how to add up the amount.
I am able to read csv file an display in html table.
I am new to Javascript. Any help to proceed would be much appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
var getCSVData = e.target.result;
var rows = getCSVData.split("\n");
var html = '<table border="1">';
rows.forEach((data, index) =>
{
html += "<tr>";
var value = data.split(",");
var region = value[1];
var amount =value[3];
if(region=="SA")
{
html += "<td>" + region + "</td>";
html += "<td>" + amount + "</td>"
}
html += "</tr>";
});
html += '</table>';
document.getElementById("data").innerHTML = html;
document.getElementById("data").style.color="blue";
}
</script>
<title> Read CSV file using JavaScript </title>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>
You need to create a variable that you use as an accumulator to save the result of the sum, for example:
var sum = 0;
for (i = 1; i <= 10; i++) {
sum += 10;
}
console.log(sum)
Following your idea, you need to create a variable initialized at 0 before forEach and then inside the loop, accumulate its result
NOTE:
1. When you read your .csv file, it is received as a String, so the value of the variable amount is also a String, so before making the sum it should be transformed to a Number type to avoid concatenate
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
var getCSVData = e.target.result;
var rows = getCSVData.split("\n");
var html = '<table border="1">';
var sum = 0;
rows.forEach((data, index) =>
{
html += "<tr>";
var value = data.split(",");
var region = value[1];
var amount = value[3];
if(region=="SA")
{
if (Number(amount)) {
sum += Number(amount)
}
html += "<td>" + region + "</td>";
html += "<td>" + amount + "</td>"
}
html += "</tr>";
});
html += '</table>';
html += '<span>' + sum + '</span>';
document.getElementById("data").innerHTML = html;
document.getElementById("data").style.color="blue";
}
</script>
<title> Read CSV file using JavaScript </title>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>

How can I escape from PHP code inside Javascript?

var i = 1;
$("#add_row").click(function(){
var arr = "<tr><td><input type='hidden' name='counter' value='" + i + "'><input type='hidden' id='pd-id-" + i + "' name='pd-id-" + i + "'><input autocomplete='off' type='text' id='pd-search-" + i + "' class='hahaha'><ul style='width: 44.8vw' class='livesearch' id='pd-result-" + i + "' onclick='clickResult()'></ul></td><td><input type='text' required name='workdescription-" + i + "'></td><td><select></select></td><?php
$date = new DateTime();
$y=1;
if (date('d') < '18' AND date('d') > '2') {
for ($x = 1 ; $x <= 16 ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $x . "'></td>";
}
} else if (date('d') < '3') {
for ($x = 16 ; $x <= date('t', strtotime(date('Y-m')." -1 month")) ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $y . "'></td>";
$y++;
}
} else {
for ($x = 16 ; $x <= date('t') ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $y . "'></td>";
$y++;
}
}
$i++;
?></tr>"
;
i++;
$( "#tablebody" ).append(arr);
});
I need to escape the letter i inside the echo of the PHP. I want them to have the value of the javascript variable i at the top. How may I do this? Also is there a better way to do this?
Like I said in a comment above, there 's no need for PHP in this case. You can solve it with Javascript only. To answer your question correctly, here 's a possible solution with Javascript and PHP.
<table id="my-table">
<tr>
</tr>
</table>
<template id="my-template">
<td><input type="text" name=""></td>
</template>
<script>
var day = '<?= (new DateTime())->format('d') ?>',
daysOfMonth = '<?= (new DateTime())->format('t') ?>',
daysOfMonthOneMonthBefore = '<?= (new DateTime('-1 month'))->format('t') ?>',
template = document.getElementById('my-template'),
i = 1,
y = 1;
var positiveInt = new Number(day),
positiveIntOneMOnthBefore = new Number(daysOfMonthOneMonthBefore),
inputElement = template.content.querySelector('input');
if (positiveInt < 18 && positiveInt > 2) {
for (var x = 1; x <= 16; x++) {
inputElement.name = 'hr-' + i + '-' x;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
} else if (positiveInt < 3) {
for (var x = 16; x <= positiveIntOneMOnthBefore; x++) {
inputElement.name = 'hr-' + i + '-' + y;
y++;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
} else {
for (var x = 16; x <= positiveInt; x++) {
inputElement.name = 'hr-' + i + '-' + y;
y++;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
}
</script>
As you said you need only the actual date from the server. The rest of the code is done with native javascript. You don t even need jQuery for this. This code example is not tested. This code uses HTML5 elements like the template tag. Make sure you are using the right HTML5 doctype. Beside that it should show you a possible way how to solve your issue.
Try your echos like this:
echo "<td><input type='text' name='hr-' + i + '-" . $x . "'></td>";
Remember that all the php code gets completely parsed server-side. Javascript is client side. Don't confuse javascript and php syntax. Concating with . is php, + is the javascript equivalent. Also use quotes consistently. E.g. " in php and ' in javascript. If you need " in Javascript, escape it like so: \".

php javascript echo javascript variable to php loop condition dynamically using onclick or how can I use ajax to solve it?

How can I store only the value of f() into $ab?
How can I also change $ab dynamically in the loop condition when the button is pressed so that the integers are printed out dynamically?
<script type="text/javascript">
var i = 0;
function f(){
i = i + 10;
document.getElementById("more").innerHTML= i;
}
</script>
php
$ab = "<p id='more'> </p>";
echo $ab;
for($x=0;$x<$ab;$x++) echo $x . "<br>";
echo "<button type='button' onclick='f()'> > </button>";
Try this,
Hope this work for you.
<script type="text/javascript">
var i = 10;
function f(){
i = i + 10;
var html = "";
for(var j=0;j<i;j++){
html += j+"<br/>";
}
document.getElementById("more").innerHTML= html;
}
</script>
You need to send the variable $x to your function f
echo "<button type='button' onclick='f($x)'> > </button>";
Then in the function you can count how many times the buttons all together are clicked, i++:
var i = 0;
function f(x) {
x += i * 10;
i++;
document.getElementById("more").innerHTML= i;
}

Looping through text boxes, using id as a variable?

Basically I'm trying to populate an array with some values in text boxes. I thought I could do it by incrementing though ids, but it isn't working.
Here it is:
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
Is it possible doing it my method, or will it inevitably not work for whatever reason? Doing some searches it seems jquery might be the way to go, but I'm not sure how to get started with that.
jQuery certainly simplifies things, but it can't do anything that JavaScript can't do, and many amazing websites were built long before jQuery came into existence.
In populateArray(), remove innerHTML here:
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
Should be:
mod[i] = parseInt(document.getElementById(pop).value);
You can simplify the function like this:
function populateArray() {
var i;
for(i = 0 ; i < sections * 3 ; i++) {
mod[i] = parseInt(document.getElementById(i).value);
}
document.getElementById('debug').innerHTML = mod.toString();
}
In addSection(), this wipes out the values of existing input elements:
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
Instead, you should create new input elements and append them.
Here's a rewrite of the function:
var input= document.getElementById('input');
function addSection(){
var inp, i;
sections++;
for(var i = 0 ; i < 3 ; i++) {
inp= document.createElement('input');
inp.type= 'text';
inp.id= identifier++;
input.appendChild(inp);
}
input.appendChild(document.createElement('br'));
} //addSection
In removeSection(), values of all input elements are wiped out.
Instead of rewriting that function, I've done a complete rewrite or your program, without any global variables and without assigning IDs to the input elements.
If you have any questions, I'll update my answer with explanations.
Snippet
function addSection() {
var input= document.getElementById('input'),
sect= document.querySelector('section');
input.appendChild(sect.cloneNode(true));
}
function removeSection() {
var input= document.getElementById('input'),
sects= document.querySelectorAll('section');
if(sects.length > 1) {
input.removeChild(sects[sects.length-1]);
}
}
function calculate() {
var inp= document.querySelectorAll('section input'),
debug= document.getElementById('debug'),
mod= [],
i,
val;
for(i = 3 ; i < inp.length ; i++) {
val= parseInt(inp[i].value);
mod.push(val || 0);
}
debug.innerHTML = mod.toString();
}
section:first-of-type {
display: none;
}
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'>
<section>
<input type="text">
<input type="text">
<input type="text">
</section>
</div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
This version of your script stores the actual elements in an array of sections. That way you can loop through them as you would an array, and alter the contents that way.
Here's a pen of the code: looping through added elements
var sections = [];
var output = document.getElementById('input');
function addSection(){
var section = document.createElement('div');
for (var i = 0; i < 3; i++) {
el = document.createElement('input');
el.type = 'text';
section.appendChild(el);
}
sections.push(section);
output.appendChild(section);
}
function removeSection(){
if (sections.length > 0){
output.removeChild(sections.pop())
}
}
function calculate(){
populateArray();
}
function populateArray(){
for (var i = 0; i < sections.length; i++) {
for (var j = 0; j < sections[i].children.length; j++ ) {
sections[i].children[j].value = (i+1) * (j+2);
}
}
}
If your problem is the NaN, this is because you select an input field and then first try to read its innerHtml before reading its value. Read values of inputs directly.
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>

javascript/jquery start button for .ogg looped play

The code below generates and loops a randomized number of iterations of some .ogg files. They play as soon as the page loads.
The commented-out bits are my attempt to add a 'start' button. What am I doing wrong here, and how can I start this with a button rather than on page load?
(Also: I am suspecting that it is bad practice to combine php and javascript as I have done. I did it because randomization in php is so easy, and I am still new to js/jquery.)
(EDIT: see the edit below. I just forgot to close the tag.)
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
$randC = rand(2,4);
$C = $randC * 4;
$G = $C / 2;
echo "
<script type=\"text/javascript\">
$(document).ready(function()
{
// $(\"#start\").click(function()
// {
var time = 0;
var riff_time = 2920;
var base = 'riff';
for(i = 0; i < $C; i++)
{
var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", time);
time += riff_time;
}
var timeG = 0;
var riff_time = 2920;
var baseG = 'riffG';
for(iG = 0; iG < $G; iG++)
{
var idG = baseG + ((iG + 1) );
window.setTimeout (\"document.getElementById('\" + idG + \"').play()\", timeG);
timeG += riff_time;
// }
} // EDIT: This should be }); ... that fixes it.
});
</script>
"?>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<!--<button id="start">Start</button>
<br> -->
<?php
echo "C:<br>";
for ($i=1; $i<= $C; $i++) {
echo '<audio controls id="riff'.$i.'">
<source src="loopC.ogg" type="audio/ogg">
</audio>';
}
echo "<br>G:<br>";
for ($i=1; $i<= $G; $i++) {
echo '<audio controls id="riffG'.$i.'">
<source src="loopG.ogg" type="audio/ogg">
</audio>';
}
?>
</body>
</html>
You can give a class start as well as and data-id to the start buttons.
So your html for start button would be like,
<img src="start-button.jpg" class="start" data-id="riff1">
//So this is start button for audio elementwith id riff1.
How will this work?
$('.start').click(function(){
$("#"+$(this).data('id')).play(); //This should do.
}
And yes in your php file should be type of this,
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
$randC = rand(2,4);
$C = $randC * 4;
$G = $C / 2;
<script type="text/javascript">
$(document).ready(function()
{
// $("#start").click(function()
// {
var time = 0;
var riff_time = 2920;
var base = 'riff';
<?php for(i = 0; i < $C; i++)
{
echo " var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", time);
time += riff_time; ";
}
?>
var timeG = 0;
var riff_time = 2920;
var baseG = 'riffG';
<?php for(iG = 0; iG < $G; iG++)
{
echo " var idG = baseG + ((iG + 1) );
window.setTimeout (\"document.getElementById('\" + idG + \"').play()\", timeG);
timeG += riff_time; ";
// } ?>
}
});
</script>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<!--<button id="start">Start</button>
<br> -->
<?php
echo "C:<br>";
for ($i=1; $i<= $C; $i++) {
echo '<audio controls id="riff'.$i.'">
<source src="loopC.ogg" type="audio/ogg">
</audio>';
}
echo "<br>G:<br>";
for ($i=1; $i<= $G; $i++) {
echo '<audio controls id="riffG'.$i.'">
<source src="loopG.ogg" type="audio/ogg">
</audio>';
}
?>
</body>
</html>

Categories

Resources