I have this script where I generate dynamically with javascript a bunch of text inputs.
After that I want to iterate between then in order to sum it´s contents and do a calculation.
The result of each iteration should be added to the end of an array. I don´t know why, but the array contents seems to be replaced every time the loop starts again, and it should add the new element created by the loop instead. But the only content it takes is the first one, and not the last one added.
Here´s the sample,
$totalCeldas = strip_tags($_POST['totalCeldas']);
$mesesTotales = array();
for ($vuelta=1; $vuelta<$totalCeldas; $vuelta++) {
$mes = 'mes'.$vuelta;
$anio = 'yr'.$vuelta;
$exp = 'exp'.$vuelta;
$valorMes = strip_tags($_POST[$mes]);
$valorAnio = strip_tags($_POST[$anio]);
$x = (($tYear - $valorAnio ) * 12) + ($tMonth- $valorMes);
$mesesTotales[] = $x;
echo '$valorAnio '.$valorAnio.'<br>';
echo '$valorMes '.$valorMes.'<br>';
//I´ve tried printing out each iteration in order to get to the problem, but it only prints out the first value.
foreach($mesesTotales as $valor){
echo 'El valor es '.$valor.'<br>';
}
I´ve also tried array_push, with the same result: It grabs only the result in the first iteration.
This is how the fields gets generated in Javascript:
function generarTabla1() {
var cant = document.forms["generar-tabla"]["cantMeses"].value;
if (cant && !isNaN(cant)) {
for ($i=0; $i<cant; $i++) {
var e = 0;
var celdaMes = " Mes <input style='width:5%;' type='text' name='mes"+($i+1)+"'> ";
var celdaYr = " Año <input style='width:8%;' type='text' name='yr"+($i+1)+"'> ";
var celdaExp = " Expensa $<input style='width:15%;' type='text' name='exp"+($i+1)+"'>
<br>";
$('#output').append(celdaMes, celdaYr, celdaExp); //agregamos las celdas necesarias
}
I rather answer this than deleting the question, in case someone else have the same silly issue:
Yes, the for loop has an issue: It should say lees or equal than, and not only less than.
So this:
for ($vuelta=1; $vuelta<$totalCeldas; $vuelta++) {
Changed for this:
for ($vuelta=1; $vuelta<=$totalCeldas; $vuelta++) {
worked.
I know, it´s silly, but I didn´t feel that was right to delete the question or let it go unanswered.
Related
I have a list of categories for products on my site and am trying to allow products to be listed under multiple categories.
When creating a product there is a list of categories with checkboxes generated from PHP like so:
$sql = "SELECT * FROM categories";
$stmt = DB::run($sql);
$categoryCount = $stmt->rowCount();
if ($categoryCount > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row["id"];
$category_name = $row["category"];
$category_checkboxes .= "<input type='checkbox' value='$id' name='cat_$id' id='cat_$id'> $category_name<br />";
}
}
I created a hidden input to determine the amount of available categories
<input type="hidden" name="cat_count" id="cat_count" value="<?php echo $categoryCount; ?>">
I am then trying to loop through these in JS to get which ones were selected to send via AJAX to my parsing script to add to the DB.
var categories;
var cat_count = document.getElementById("cat_count").value;
var i;
for(i=1; i<=cat_count; i++){
var cat_id = 'cat_'+i;
var cat = document.getElementById(''+cat_id+'').value;
categories += cat+',';
}
I have two issues with this:
First a category can be deleted so although there might be 3 categories these could have ID's like '1,3,5'. So my checkboxes will have these ID's but the JS is looking for '1,2,3' and it obviously gets an error when it is trying to get the value of a NULL element.
Second, if it can get the values, it will get all of the values of all checkboxes not just the ones that are checked which is what I need. Although if I get a way to loop through the ID's correctly this shouldn't be too difficult to but in a if checked condition.
Any suggestions or assistance with this would be greatly appreciated.
Here is a cleaner way to do this. You don't need cat_count; Add a class to your checkboxes, select all of them, get their value and append it to the categories variable; Working fiddle
var categories = "";
var checkboxes = Array.from(document.getElementsByClassName("checkbox"));
checkboxes.forEach(function(element, index) {
categories += element.value;
});
Id need to be unique so this line var cat_count = document.getElementById("cat_count").value; will always return a single element.
Change it by adding index to it
Instead of Id you can use name with
document.getElementsByName("'cat_$id'")
Thanks to #CBroe for getting there first, that worked for me.
var categories = '';
var category = document.getElementsByClassName("product_category");
var i;
for(i=0; i<category.length; i++){
if(category[i].checked == true){
var category_value = category[i].value;
categories += category_value+',';
}
}
How I create a do...while loop (or if there is a better way to go about this - please advise) for a form with potentially additional information?
Background - I've got a form that will accept a users assessment of a particular location (such as a basement). Using only 1 location per form, this works nicely and submits to my db without a problem.
Now I want to enhance this form with a "add new location" button. I don't (obviously) want to create new pages but rather a loop that can store the first location, save it (which I know could be done with be a session variable) and then clear the fields for locations 2, 3, 4, etc.
My confusion is around the functionality of the button. What type of button is this? Reset with a unique id such as new_loc[]?
And then when I write this as a do...while loop should I do it like this:
<?php
do {
all my form fields
} while (some condition that looks for the button submit);
?>
ok so I have a created a simple JS that can "handle" this.
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " locations");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><br><input type='text' name='location[]'>";
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
Now the problem is that JS will add 1 new field - any suggestions on how to add a massive block of HTML to the JS? I tried adding all my fields to the JS and I get a whole bunch of unclosed string errors.
So first of all your form must have action="" method="post"
then add this php to your page:
session_start();
if (isset ($_POST['NameOfSubmitButtonInsideForm'])) {
if (!isset ($_SESSION['sessionName'])) {
$_SESSION['sessionName'] = 1
}
for ($i = 0; $i <= $_SESSION['sessionName']; $i++) {
echo 'some html code like a form with a input that has
<input type="submit" name="submit- . $i .'EndInputTag>';
};
}
So this will loop the number of times the user clicked the button and you can echo out html code based on that number, or what ever it is you need to do in the loop.
Ok I've figured this out. Thanks to Marc B for suggesting JS.
HTML for the button
<input style="margin-left:5px;" class="btn btn-primary" type="button" value="Add Additional Location" onClick="addInput('locInformation');">
JS
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<h3>Location " + (counter + 1) + "</h3>" + document.getElementById('additionalLoc').innerHTML;
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
And then lastly is the new locInformation stuff:
<div id="additionalLoc" language="text">
huge block of HTML with additional fields
</div>
I have an app for making questionnaires. Users have index.php page where they create the questions and choose minimum number of answers, then they have process.php page where they can enter their answers or add more answers.
PROBLEM: When user clicks add more button, it creates textarea of the particular question but with the wrong name. The add more button should add a textarea and change its name according to the minimum of the defined textareas. So if you for ex. have 4 defined textareas in question2, the next textareas should be like odg25, odg26, odg27, odg28 etc...
The problem is in variable $k (process.php) - because it is not defined in addmore function, but I don't know how to pass somehow in this part of code to make it happen.
THIS IS THE TESTING LINK
INDEX.PHP
<input id="btntxt" type="submit" value="TEXT" onclick="addtxt();" /><br/><br/>
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
PROCESS.PHP
<script type="text/javascript">
<?php $chars = $_POST['chars']; ?>
function addmore(index) {
var textarea = document.createElement("textarea");
textarea.name = "odg" + index + //WHAT SHOULD I ADD HERE???;
textarea.rows = 3;
textarea.setAttribute('maxlength',<?php echo $chars ?>);
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
<body>
<?php
$bla = "";
$pitanje = $_POST['question'];
$length = count($_POST['question']);
$req = $_POST['req'];
$requiem = '';
$min = $_POST['min'];
$area = array("","","","","","","","","","","","","","","");
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
if(($min[$j])!="") {
for($k=1;$k<=$min[$j];$k++) {
$area[$j] .= '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea><br/>';}}
if(($min[$j])=="") {
$area[$j] = '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea>';}
$addmore = '<input type="button" name="more" value="Add more" onClick="addmore('.$j.');">';
$bla .= $j.') '.$pitanje[$j].'<br/>'.$area[$j].'<div id="inner'.$j.'"></div>'.$addmore.'<br/>';}}
echo $bla;
?>
FNCS.JS
var n = 1;
function addtxt() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var required = document.createElement("input");
required.type = "checkbox";
required.name = "req[" + n + "]";
var minimum = document.createElement("input");
minimum.type = "text";
minimum.name = "min[" + n + "]";
var div = document.createElement("div");
div.innerHTML = n + ". Question: " + "<br />" + textarea.outerHTML + "<br />" + "Required: " + required.outerHTML + "<br />" + "Min: " + minimum.outerHTML + "<br /><hr/><br/>";
document.getElementById("brain1").appendChild(div);
n++;
}
I did the same kind of dev.
I had a globalized counter (cpt) in the javascript is incremented by 1 each duplication
My variables were duplicated like this id = "foo_" + cpt.
I added a hidden field for the counter <input type="hidden" id = "cpt"> and its value was changed for each replication.
Php side, I recovered the counter and then a loop to iterate through all the duplicate fields.
// For example
$cpt = $_POST['cpt'];
for ($i = 1; $i <= $cpt; $i++) {
$foo[$i] = $_POST['foo_' . $i];
}
I hope it will help.
You're mixing JavaScript and PHP. PHP is doing some part of the question generation and then JavaScript has to pick up where it left off.
The problem with that approach is that you'll find you end up duplicating a lot of functionality.
The answer the quesiton WHAT SHOULD I ADD HERE??? is "odg" + $j + $k
If instead you start by doing:
var questions = <?php echo json_encode($_POST["question"]);?>;
You now have all your question data available in JavaScript. You can move the for loop from PHP to JavaScript and have j and k there.
What you're going to have to do is make $k able to be passed into process.php.
That is accomplished with something like this:
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input id="numRows" type="hidden" name="numRows" value="1"/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
notice I've added a new <input> element with the name "numRows" which will be passed via POST to process.php. I've given it an arbitrary default value of 1, you can set this however you wish.
Now, when a user clicks the "add more" button, within fncs.js do this:
document.getElementById("numRows").value++;
and finally, in your process.php you need to read in the value of this, as $k:
<?php $k = isset($_POST['numRows']) ? urldecode($_POST['numRows']) : 1; ?>
within process.php you may do as you wish, then, with that value $k.
You need to store last text area value in hidden variable and always increment that
first step: At start set value of hidden variable and your counter
'n' same
second step : at each step where you are adding new text area ,
overwrite the hidden value by new counter value of text area
Remember Textarea counter should be always fetched from hidden value
I think this may help you to solve your problem
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model
This question comes after solving my last question, I'd like to get some values out of the hidden forms but when I try to retrieve them only empty strings come by, I've considered just using arrays to store the information as it is introduced but I'd like to know if it's possible just to retrieve it afterwards and how.
Also, There is a table that is generated on the fly with some javascript:
function createTable(){
if ( document.getElementById("invoiceFormat").rowNumber.value != ""){
rows = document.getElementById("invoiceFormat").rowNumber.value;
}
var contents = "<table id='mt'><tr>";
if ( document.getElementById("invoiceFormat").cb1[0].checked ){
contents = contents + "<td class='htd'>Quantity</td>";
}if (document.getElementById("invoiceFormat").cb1[1].checked ){
contents = contents + "<td class='htd'>Description</td>";
}if (document.getElementById("invoiceFormat").cb1[2].checked ){
contents = contents + "<td class='htd'>Unitary Price</td>";
}if (document.getElementById("invoiceFormat").cb1[3].checked ){
contents = contents + "<td class='htd'>Subtotal</td>";
}
for (i=4; i<=k; i++){
if (document.getElementById("invoiceFormat").cb1[i].checked ){
contents = contents + "<td>" + document.getElementById("invoiceFormat").cb1[i].value + "</td>";
}
}
contents = contents + "</tr>";
for (j=1; j<=rows; j++){
contents = contents + "<tr>";
for (l=0; l<=k; l++){
if (document.getElementById("invoiceFormat").cb1[l].checked ){
hotfix = l +1;
contents = contents + "<td> <input id='cell" + j + "_" + hotfix + "' name='cell' type='text' size='15' /> </td>";
}
}
contents = contents + "</tr>";
}
contents = contents + "</table>";
var createdTable = document.getElementById("mainTable");
createdTable.innerHTML = contents;
}
After it's created I've tried to access it but without luck so far, I just can't get what the user inputs in the input fields that are created. How can I do this?
I'm using raw javascript with jQuery so answers with or without the library are welcomed :)
document.getElementById("invoiceFormat").cb1[3].checked
First of all I do not know what ".cb1[3]" means here so I will ignore it and will tell you how I would solve this problem: (I assume that "invoiceFormat" is id of your form.)
1) in your form set name property of every field you have. that way you can reach them like document.getElementById("invoiceFormat").fieldName.value
if you will use this method make sure that put your form in a local variable. it will be a lot faster
var form = document.getElementById("invoiceFormat");
form.fieldName.value;
2) give every field you have a unique id and just use getElementById directly on fields not on form.
I am not sue if this method is better, but I am useing second one all the time. I just get used to it I guess.
3) there is one more way but it might be an overkill. when you create your form fields, you can put them in an object(not values but the elements themselves) and even hide it in a closure. That way you can call something like
formElements.formFieldOne.value;