I have 2 problem here
I have to remove array which it value is 0
I have to insert a data to database using loop
any response would be appreciated
here my code :
Javascript
for (a = 0; a <= i; a++) {
$(".addmore_" + a).on('click', function (a) {
return function() {
var data = "<tr><td><input class='form-control sedang' type='text' id='packinglist_" + a + "' name='packinglist[]'/></td></tr>";
$("#keatas_" + a).append(data);
} ;
}
(a));
};
My Java script is working properly but the point is when I want to add the input-box to database, a data didn't loop
here my html
for($i=1;$i<=5;$i++)
{
<table id='keatas_$i' class='keatas'>
<tr>
<input class='form-control' type='hidden' id='hiddenlot_$i' name='hiddenlot[]' />
<input class='form-control' type='hidden' id='hiddencustomer_$i' name='hiddencustomer[]' />
<td>
<a><span class='glyphicon glyphicon-plus addmore_$i'></span></a>
</td>
</tr>
</table>
}
so i need to loop my input box everytime i press "addmore" button ,and for some reason i need to loop 'hiddencustomer[]' and 'hiddenlot[]'
and here my query.php
for ($i = 0; $i < 5; $i++) {
$idlot = $_POST['hiddenlot'][$i];
$customer = $_POST['hiddencustomer'][$i];
$a=mysql_query("INSERT INTO item VALUES ('',now(),'$idlot')");
$count = count($_POST['packinglist']);
for ($c = 0; $c < $count; $c++) {
$pack = $_POST['packinglist'];
$packinglist1 = array_values(array_filter($pack));
$packinglist = $packinglist1[$c];
$item = mysql_query("SELECT * FROM item ORDER BY item_id DESC");
$itemid = mysql_fetch_array($item);
$a= mysql_query("INSERT INTO packing_list VALUES('','$packinglist','$itemid[item_id]')");
}
}
I put 2nd loop in 1st loop cause I need a item_id for insert to packing_list table and I got a item_id by last input to item table
sorry for bad explain and bad english
I hope you can understand what I mean
thankyou
I am new to javascript, I have created 2 functions, createInput() which creates input boxes with a name parameter when called and appends them to a tag, newTwo() which calls createInput() twice with two different names.
I cannot seem to provide a index for the two name elements and make it increment each time the newTwo() is called. I need this so that I can trace the field values as a pair.
function createInput(name)
{
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("name", name);
var form = document.getElementById("foobar");
form.appendChild(input);
}
function newTwo()
{
var $i = 0;
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
}
When I call newTwo(), input fields are created with the array index as follows.
<input type="text" name="first_name[0]" />
<input type="text" name="last_name[0]" />
If I call it again, the next two fields will be
<input type="text" name="first_name[0]" />
<input type="text" name="last_name[0]" />
my desired output for the previous second call would be
<input type="text" name="first_name[1]" />
<input type="text" name="last_name[1]" />
Any suggestions? Thanks in advance.
Because you have var $i = 0; inside the function, you're creating a new variable and initializing it to 0 every time you run the function. If you want to use a variable that maintains its value between function calls, you need to declare it outside the function. For example:
var $i = 0;
function newTwo()
{
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
}
Or if you really want to avoid making $i global you could create a IIFE around it like this:
var newTwo = (function() {
var $i = 0;
return function() {
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
};
})();
Note that there are subtle differences between this and the previous version. See these questions for more details:
How do JavaScript closures work?
var functionName = function() {} vs function functionName() {}
I have a MySQL database of orders that each have various activities associated with them. My PHP/HTML page pulls down the activities when you click an order and allows the user to change attributes of the activities with a form. On submit another PHP file loops through activities in the table and runs an update query on the database. Works great!
I have recently added a JavaScript function that will add activities to the list (appendChild, createElement...). I then added to my PHP file an INSERT query for the new activities.
The problem is that when I run the update PHP file it is not looping through the newly added records that were added with JavaScript. I checked it by using <?php print $size = count($_POST['FcastID']) ?> and the value doesn't change when records have been added.
The records look fine when added to the table and the id and name convention match the other records. It seems like the page needs to be refreshed before the PHP file runs.
PHP file with dynamically created html form
<div id="submit"><form method="post" action="Up_Forecast.php"><input type="submit" value="Submit"></div>
....
<table id="fcast">
<?
$i=0;
while($row = mysqli_fetch_array($res_fcast))
{
echo "<tr id='fcastRow[$i]'>";
echo "<td class='medium'><input type='text' id='qtyJan[$i]' name='qtyJan[$i]' value='".$row[Jan]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyFeb[$i]' name='qtyFeb[$i]' value='".$row[Feb]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMar[$i]' name='qtyMar[$i]' value='".$row[Mar]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyApr[$i]' name='qtyApr[$i]' value='".$row[Apr]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMay[$i]' name='qtyMay[$i]' value='".$row[May]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJun[$i]' name='qtyJun[$i]' value='".$row[Jun]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJul[$i]' name='qtyJul[$i]' value='".$row[Jul]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyAug[$i]' name='qtyAug[$i]' value='".$row[Aug]."'/></td>";
echo "<td class='medium'><input type='text' id='qtySep[$i]' name='qtySep[$i]' value='".$row[Sep]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyOct[$i]' name='qtyOct[$i]' value='".$row[Oct]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyNov[$i]' name='qtyNov[$i]' value='".$row[Nov]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyDec[$i]' name='qtyDec[$i]' value='".$row[Dec]."'/></td>";
echo "<td class='medium'><input type='text' id='Totalqty[$i]' name='Totalqty[$i]' value='".$row[Total]."' disabled/></td>";
echo "</tr>";
++$i;
}
?>
<tr><td class="blank"></td><td class="mini"><input type="button" onclick="addRowYear(this)" value="Add"/></td></tr>
</table>
</form>
</div>
Javascript function to add row
function addRowYear(lastRow){
var rowNo = lastRow.parentNode.parentNode.rowIndex;
var newRow = document.getElementById("fcast").insertRow(rowNo);
newRow.setAttribute("id","fcastRow["+rowNo+"]");
var cell0 = newRow.insertCell(0);
cell0.setAttribute("class","mini");
var input0 = document.createElement("input");
input0.setAttribute("type","text");
input0.setAttribute("name","FcastID["+rowNo+"]");
input0.setAttribute("value","new");
cell0.appendChild(input0);
var cell1 = newRow.insertCell(1);
cell1.setAttribute("class","mini");
var input1 = document.createElement("input");
input1.setAttribute("type","text");
input1.setAttribute("name","Fcast_ActID["+rowNo+"]");
input1.setAttribute("id","Fcast_ActID["+rowNo+"]");
cell1.appendChild(input1);
var curAct = document.getElementById("selAct").innerHTML;
document.getElementById("Fcast_ActID["+rowNo+"]").value = curAct;
var cell2 = newRow.insertCell(2);
cell2.setAttribute("class","mini");
var input2 = document.createElement("input");
input2.setAttribute("type","text");
input2.setAttribute("name","Year["+rowNo+"]");
cell2.appendChild(input2);
var month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
for (var i = 0; i < month.length; i++) {
//alert(month[i]);
x=3;
var cell = newRow.insertCell(x);
cell.setAttribute("class","medium");
var input = document.createElement("input");
input.setAttribute("type","text");
input.setAttribute("class","numbers");
input.setAttribute("name","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("id","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("onkeyup","findTotal()");
cell.appendChild(input);
x=x+1;
}
var cell15 = newRow.insertCell(15);
cell15.setAttribute("class","medium");
var input15 = document.createElement("input");
input15.setAttribute("type","text");
input15.setAttribute("class","numbers");
input15.setAttribute("name","Totalqty["+rowNo+"]");
input15.setAttribute("id","Totalqty["+rowNo+"]");
cell15.appendChild(input15);
PHP Update - Called on Submit of form
$size = count($_POST['FcastID']);
$i = 0
while ($i < $size) {
$FcastID = $_POST['FcastID'][$i];
$ActID = $_POST['Fcast_ActID'][$i];
$Year = $_POST['Year'][$i];
$Jan = $_POST['qtyJan'][$i];
$Feb = $_POST['qtyFeb'][$i];
$Mar = $_POST['qtyMar'][$i];
$Apr = $_POST['qtyApr'][$i];
$May = $_POST['qtyMay'][$i];
$Jun = $_POST['qtyJun'][$i];
$Jul = $_POST['qtyJul'][$i];
$Aug = $_POST['qtyAug'][$i];
$Sep = $_POST['qtySep'][$i];
$Oct = $_POST['qtyOct'][$i];
$Nov = $_POST['qtyNov'][$i];
$Dec = $_POST['qtyDec'][$i];
$Total = $_POST['Totalqty'][$i];
$update = "UPDATE FCAST SET
Year='$Year',
Jan=replace('$Jan',',',''),
Feb=replace('$Feb',',',''),
Mar=replace('$Mar',',',''),
Apr=replace('$Apr',',',''),
May=replace('$May',',',''),
Jun=replace('$Jun',',',''),
Jul=replace('$Jul',',',''),
Aug=replace('$Aug',',',''),
Sep=replace('$Sep',',',''),
Oct=replace('$Oct',',',''),
Nov=replace('$Nov',',',''),
`Dec`=replace('$Dec',',',''),
Total=replace('$Total',',','')
WHERE
FcastID='$FcastID'";
mysqli_query($link, $update);
Without seeing your code, it is difficult to say. Something I have used in the past that works well is the following:
PHP:
foreach($_POST as $key => $value) {
//... $key is name of field, $value is the value
}
This goes through each individual field in the submitted form and reads the value in each. I've used this exact script for dynamically-created forms, and it works great. You have to be careful, though, if you use the same name for different fields, the values will be stored as arrays.
EDIT
HTML:
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
JavaScript:
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
It isn't all that important to know how the JavaScript code works. All you need to know is that clicking on the "Add" button will duplicate the field and clicking on "Remove" will remove the most recently added field. Try it out at the link provided.
PHP:
This is where the magic happens…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
Looks easy enough, right?
This PHP code is within the same file as the form, so first we check to see if the form has been submitted by checking for the name of the submit button if(isset($_POST['submit'])){…}.
If the form has been submitted, go through each submitted item foreach($_POST as $name => $item){…}.
The submit button counts as one of the fields submitted, but we aren't interested in storing that value, so check to make sure the value you are reading in is not from the submit button if($name != 'submit'){…}.
Finally, all the fields within this form have the same name field_name[]. The square brackets are used for multiple items that share the same name. They are then stored in an array. Read through each item within that array for the length of the array for($m=0; $m < sizeof($item); $m++){…} and then do what you'd like with each value. In this case, I've just printed them to the screen echo ($name.' '.$item[$m].'<br>');
Below are a couple screen-shots of the page…
Before submitting the form:
After submitting the form:
You can go to the page and view the code (right click -> View Source), but the PHP will not show up in the source. I assure you that all the PHP used for this is shown above - just the few lines.
If each item has a completely unique name (which you can achieve via JavaScript when adding fields), then you will not need to loop through the array of values (i.e. will not need for($m=0; $m < sizeof($item); $m++){…} block). Instead, you'll likely read the value using simply $item. If you name your fields with the square brackets (i.e. field_name[]), but only have one of that field, then reading a singular value may require $item or $item[0]. In that case you'll just have to test it and see. Some field types behave differently than others (i.e. input, text area, radio buttons, etc).
The Whole Thing
Here is the entire code for index.php - you can just copy and paste it and run it on your own server. Just make sure to change the name of the file in the action attribute <form> tag…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
<html>
<head>
<script type="text/javascript" src="../scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
<script>
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
</script>
</html>
I am trying to build a little resume builder. I want the user to be able to enter any number of phone numbers. However, the appendChild() is not working as expected. Actually, it's not working at all. It does nothing. Any ideas?
HTML:
<div id="phoneNumbers">
<?php
if(isset($_SESSION['phoneNumber'])){
for($i = 0; $i<sizeof($_SESSION['phoneNumber']); $i++){
echo "<input type=\"text\" size=\"20\" name = \"phoneNumber[".$i."]\"
value=\"".$_SESSION['phoneNumber'][$i]."\" />
<br />";
}
}
else{
?>
<input type="text" size="20" name = "phoneNumber[0]"
value="" />
<br />
<?php
}
?>
</div>
<input type="button" value="Add another phone number" onclick="addPhoneNumber()">
Javascript:
var numberOfPhoneInputs = 1;
function addPhoneNumber()
{
// Found out the following doesn't work as expected...
// var newPhoneNumberInput = "<input type=\"text\" size=\"20\" name = \"phoneNumber[" +
// numberOfPhoneInputs +"]\" value=\"\" />" +
// "<br />"
// document.getElementById("phoneNumbers").innerHTML += newPhoneNumberInput;
var div = document.getElementByID("phoneNumbers");
var newPhoneNumberInput = document.createElement('input');
newPhoneNumberInput.setAttribute('type', 'text');
newPhoneNumberInput.setAttribute('name', 'phoneNumber['+numberOfPhoneInputs+']');
newPhoneNumberInput.setAttribute('size', '20');
newPhoneNumberInput.setAttribute('value', '');
div.appendChild(newPhoneNumberInput);
numberOfPhoneInputs ++;
}
document.getElementByID needs to be document.getElementById
This error should show in your console.
You need to return false; from the click handler to prevent the button's default action of submitting the page.
you need to make these changes ...
change document.getElementByID("phoneNumbers"); to document.getElementById("phoneNumbers");
(optional) It will be good if you change var div to var phoneNumbersDiv or something
fiddle example : http://jsfiddle.net/v8rF3/
Updated code:
var numberOfPhoneInputs = 1;
function addPhoneNumber(){
var div1 = document.getElementById("phoneNumbers");
var newPhoneNumberInput = document.createElement('input');
newPhoneNumberInput.setAttribute('type', 'text'); newPhoneNumberInput.setAttribute('name', 'phoneNumber['+numberOfPhoneInputs+']');
newPhoneNumberInput.setAttribute('size', '20');
newPhoneNumberInput.setAttribute('value', '');
div1.appendChild(newPhoneNumberInput);
numberOfPhoneInputs ++;
}
I made a number of html forms containing only radio buttons and a submit button. However, I cannot get them to validate properly--independently of each other. Here is my code:
PHP/HTML code for the form:
<table>
<?php
for($i=0; $i<count($array1); $i++)
{
$number = $i + 1;
echo "<TR><TD>;
echo "<form name='move' action='listChange_controller.php' method='POST'>Title:<br/>
<input type='radio' name='change".$number."' value = 'val1' />Thing1
<input type='radio' name='change".$number."' value = 'val2'/>Thing2
<input type='radio' name='change".$number."' value = 'val3'/>Thing3
<input type='button' name='submit' value='submit' onClick='validate(".$number.");'/>";
echo "</form>";
echo "</TD></TR>";
}
?>
</table>
Here is the javascript/jquery I have been trying, but has not worked:
function validate(number)
{
var name_var = 'change'+number;
if($('input:radio[name=name_var]:checked').length > 0)
{
$.post('file.php',{ name_var:$('input:radio[name=name_var]:checked').val()});
}
else
{
alert('You must choose');
return false;
}
}
When I do this, it always thinks I have not chosen a radio button before pressing submit; it always carries out the 'else' part of my javascript function.
Please let me know why it is not working, and what would work. Any help and suggestions appreciated.
This line...
if($('input:radio[name=name_var]:checked').length > 0)
should read
if($('input:radio[name=' + name_var + ']:checked').length > 0)
Change...
if($('input:radio[name=name_var]:checked').length > 0)
to...
if ($('input[name=' + name_var + ']').is(':checked'))