I have an appendchild-function that adds form elements. In IE, everything works fine; the process.php is able to $_POST it. But in firefox, it doesnt send the data.
Here is my code.
<script type="text/javascript">
var i=0;
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="text" name="work" /><input type="file"
class="fileupload" size="80" name="file' + (num) +'" onclick="addElement()"/> <a
class="removelink" onclick=\'removeElement('+divIdName+')\'>Remove This File</
a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
<td>
<div class="file_input_wrapper">
<input type="hidden" value="1" id="theValue" />
<div id='org_div1'>
<input type="file" class="fileupload" name="file1" size="80" onclick="addElement()" />
</div>
</td>
Solved the problem...
Basically, I had this..
<div>
<form>
</div>
</form>
And changed to this..
<form>
<div>
</div>
</form>
Seems firefox doesnt like invalid html.
You can use PHP's field name array functionality to get around having to keep track of your field names. Simply name the field like this:
<input type="file" name="files[]" ... />
^^--- array notation
and PHP will handle each file box as a separate member in the $_FILES array after the form's submitted. This frees you up from all the extra overhead of keeping track of how many boxes there are and hidden form fields to store the value.
You may want to reconsider having the file element's onclick be the thing that adds a new file input. What happens if someone clicks on the "browse" button to add a file? They'll get a new file input box, even though they may only have wanted one. If they choose the wrong file or change their minds later and click browse again to change the file selection, they'll get yet another input box.
Consider having a dedicated "add another box" button instead.
Just want to ask where your form tag is located? Before or after table tag? I had similar problem and my form tag was inside table. When I put form tag outside of table everything worked fine.
Site doesn't work anymore.
Here is working example. I used your code. Only two thing I changed is
<input type="text" name="work[]" /> instead of <input type="text" name="work" />
and you was missing one </div> closing div tag
here is code (tested on IE7, IE8, FF and google chrome)
<?php
if (!empty($_POST['btnProsledi'])){
print_r($_POST);
echo "<br />";
print_r($_FILES);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
var i=0;
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="text" name="work[]" /><input type="file" class="fileupload" size="80" name="file' + (num) + '" onclick="addElement()"/> <a class="removelink" onclick=\'removeElement(' + divIdName + ')\'>Remove This File</a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<td>
<input name="proba" type="text" id="proba" value="" />
</td>
</tr>
<tr>
<td>
<div class="file_input_wrapper">
<input type="hidden" value="1" id="theValue" />
<div id='org_div1'>
<input type="file" class="fileupload" name="file1" size="80" onclick="addElement()" />
</div>
</div>
</td>
</tr>
<tr>
<td>
<input name="btnProsledi" type="submit" id="btnProsledi" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
Related
Hi I try to sum two data using AJAX and display it into hidden text input after that, I will pass the variable using PHP post method.
There are no problems in my jQuery AJAX code but the problem is after I submit the button, the value I retrieve from textbox total_rec[] is blank.
Here's my code below.
HTML:
<form method="post" action="<?php echo base_url() ?>user/recitem_insert">
<table>
<thead>
<tr><th>Test</th></tr></thead>
<tbody>
<tr><td>
<input type="hidden" name="last_item_rec[]" value="<?php echo $row->rec_qty; ?>">
<input type="text" name="item_rec[]" id="txt" disabled="">
<input type="hidden" name="total_rec[]" value="">
</td><tr>
</tbody>
</table>
</form>
JQUERY AJAX:
<script>
$(document).ready(function(){
$("input[name=item_rec\\[\\]]").on('keyup',function(){
var one = $(this).parents('tr').find('input[name=last_item_rec\\[\\]]').val();
var two = $(this).parents('tr').find('input[name=item_rec\\[\\]]').val();
sum = parseInt(one) + parseInt(two);
$(this).parents('tr').find('input[name=total_rec\\[\\]]').val(sum);
});
});
<script>
PHP CODE: (recitem_insert.php)
$total_rec = $_POST['total_rec'];
for($i=0;$i<sizeof($check);$i++){
for($j=0;$j<sizeof($total_rec);$j++){
$query=mysqli_query($con,"UPDATE tblstock
SET
rec_qty='$total_rec[$j]'
WHERE id = '$check[$i]'
")or die(mysqli_error($con));
}
}
As you told that the item contain 2 or more value. So you can use class instead of name.
HTML
<input type="hidden" class="last_item_rec" name="last_item_rec[]" value="23" />
<input type="text" class="item_rec" name="item_rec[]" id="txt" />
<input type="hidden" class="total_rec" name="total_rec[]" value="" />
jQuery
$(function(){
$(".item_rec").on('keyup',function(){
var one = $(this).parents('tr').find('.last_item_rec').val();
var two = $(this).parents('tr').find('.item_rec').val();
sum = parseInt(one) + parseInt(two);
console.log(sum);
$(this).parents('tr').find('.total_rec').val(sum);
});
});
I am currently building a dynamic form, using a bit of HTML, PHP and jQuery. This form contains a drop down select field (with the tag name) and two input boxes named tag_text_color and tag_background_color.
When you select a tag in the select field, a bit of jQuery will fill the boxes tag_text_color and tag_background_color with the current database value.
Before that, I have a form which allow the user to add a tag in the database. My problem occurs when I right before adding a tag in the database.
Here is the code for adding a tag :
<form id="form_addtag" method="post" name="form_addtag" action="add_tag.php">
<legend>Add a tag</legend>
<input type="text" name="tag_name" id="tag_name" class="text" size="30" placeholder="Tag Name" />
<input type="text" name="tag_text_color" id="tag_text_color" class="text" size="6" placeholder="#ffffff"/>
<input type="text" name="tag_bg_color" id="tag_bg_color" class="text" size="6" placeholder="#000000" />
<button type="submit" id="button_save_tag">Add</button>
</form>
and the jQuery corresponding function :
$( document ).ready(function() {
$("#form_addtag").submit(function(e) {
e.preventDefault();
var url = "add_tag.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form_addtag").serialize(), // serializes the form's elements.
});
$('#form_addtag')[0].reset();
$("#form_edittag").load("demo.php #form_edittag")
});
Adding a tag works fine, and it reloads perfectly the form to edit a tag. However if in this block I am selecting the new tag, it is not loaded yet by jQuery
HTML to edit a tag :
<form id="form_edittag" method="post" name="form_edittag" action="edit_tag.php">
<legend>Edit a tag</legend>
<select id="select_edittag">
<?php
$tags = get_tags();
$numberOfTags = sizeof($tags);
var_dump($numberOfTags);
var_dump($tags);
foreach ($tags as $line)
{
echo("<option value='".$line["name"]."''>".$line["name"]."</option>");
}
//print("<option value='". $tags[ $j ]["name"]."'>".$tags[ $j ]["name"]."</option>");
?>
</select>
<input type="text" name="tag_text_color_edit" id="tag_text_color_edit" class="text" size="6" />
<input type="text" name="tag_bg_color_edit" id="tag_bg_color_edit" class="text" size="6" />
<button type="submit" id="button_edit_tag">Edit</button>
<button type="submit" id="button_delete_tag">Delete</button>
</form>
Corresponding jQuery :
$( document ).ready(function() {
$( document ).on( "change", "select#select_edittag", function()
{
var name = $("#select_edittag").val();
var tags = <?php echo json_encode(get_tags()); ?>;
$("#tag_text_color_edit").val(tags[name]["text_color"]);
$("#tag_bg_color_edit").val(tags[name]["background_color"]);
});
});
The function get_tags() will return an array with all the tags in the database.
I was thinking that each time I select a new item in my select "select_edittag" it would run the script, and update the tags variable with the lastest content from the function get_tags(). It does not sadly.
Any idea ? If you want a live demo I can host something like that
No.
PHP is running once, when loading the page. You must repopulate 'tags' via ajax. Check: getJSON
I have a PHP variable which I am trying to get to appear onto an input field without using the 'value' attribute but I can't seem to get that to work.
I tried a jQuery code I found first to 'append' the variable to the input field but that didn't work.
var first_name = "<?php echo $current_user['first_name']; ?>";
alert(first_name);
$('#first_name').val($('#first_name').val() + first_name);
I then tried using getElementById but it also didn't work.
var first_name = "<?php echo $current_user['first_name']; ?>";
alert(first_name);
document.getElementById('first_name').value = first_name;
Any suggestions would be greatly appreciated!
EDIT:
This is the HTML form
<form name="personal_form" action="includes/editpersonal.php" method="POST">
<fieldset>
<legend><h2>Personal Details</h2></legend>
<table class="personalform">
<!--if there is an error on first name, the class name 'form_error_row' will be input into the following tr-->
<!--allows me to colourise the text field to indicate an error on this row-->
<tr class="<?php echo form_row_class("first_name") ?>" >
<th><label for="first_name"><p>First Name: </p></label></th>
<td>
<input type="text" name="first_name" id="first_name" size="40" />
<!--if there is an error it will print out a div with the error message-->
<?php echo error_for('first_name') ?>
</td>
</tr>
</table>
</fieldset>
<input type="submit" class="reg-button" value="Update Records" />
</form>
Try assigning value in document.ready to ensure html elements are ready for to be accessed by the script.
$(document).ready(function(){
$('#first_name').val($('#first_name').val() + first_name);
});
I have number of check boxes that gets generated dynamically. So i do not know how many check boxes gets generated each time. I need to have some JavaScript ways to count the total numbers of check boxes in a form.
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
I can not change the name of the check boxes as i need to send the values to serverside PHP script as an array.
Since all other answers are jquery based, I'll offer a pure javascript solution. Assuming the following form:
<form id="myform">
<input type="checkbox" value="username1" name="check[0]" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" /><br/>
</form>
You could compute the number of checkbox elements with the following logic:
<script type="text/javascript">
var myform = document.getElementById('myform');
var inputTags = myform.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
BTW: As others have noted, the id attribute in any HTML tag should be unique within the document. I've omitted your id="1" attributes in my sample HTML above.
Update:
If you simply want to count all checkbox elements on the entire page without using a containing form element, this should work:
<script type="text/javascript">
var inputTags = document.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
In Plain JavaScript:
var myForm = document.forms[nameOrIndex];
var inputs = myForm.getElementsByTagName('input');
var checkboxes = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].getAttribute('type').toLowerCase() == 'checkbox'){
checkboxes.push(inputs[i]);
}
}
alert(checkboxes.length);
I would go with:
alert(document.querySelectorAll("input[type=checkbox]").length);
If you wanted a particular form you would need to select the form and use that as a base for your call to querySelectorAll instead of document or change the selector to include the form.
<form id="aForm">
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
<form id="bForm">
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
Then use:
alert(document.querySelectorAll("#aForm > input[type=checkbox]").length); //shows 2
alert(document.querySelectorAll("#bForm > input[type=checkbox]").length); //shows 3
Note: The Selectors API is only available in newer browsers starting with: Internet Explorer 8, Firefox 3.5, Safari 3.1, Chrome 1, and Opera 10.
alert( $("form input[type='checkbox']").length );
Will give you all the checkboxes in a form, using jQuery.
As you tagged your question with php and you seem to use some sort of numbering already for the form fields, you can also just echo that php counter to a javascript variable:
<?php
//
?>
<script language="javascript" type="text/javascript">
var checkbox_counter = <?php echo $your_counter_in_php; ?>
</script>
<?php
//
?>
By the way, in html you can only have one id on a page and it canĀ“t start with a number.
you could use jquery
var len = $('input:checkbox').length;
alert(len);
WORKING DEMO
if you have jQuery you could do something like
alert ($(':checkbox').length ());
If not then you'll have to document.getElementsByTagName ('input'), iterate over the collection you get back and increment a counter every time you encounter one with its type attribute set to checkbox.
How do I do unlimited fields in php? Here is the scenario:
At first, there are only 2 fields, lets called: first name1, last name1
What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..
Can anyone give me some sample script in php? I am new to PHP.
The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.
That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.
Simple Javascript (jQuery) Example:
$(document).ready(function(){
$("input[value='Add']").click(function(event){
event.preventDefault();
$("p.field:last").clone().insertAfter("p.field:last");
});
});
<form method="post">
<p class="field">
<input type="text" name="firstname[]" value="" />
<input type="text" name="lastname[]" value="" />
</p>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
Simple PHP Example:
I don't encourage you use this as-is
<?php
$count = 1;
if ($_POST["submit"] == "Add") {
$count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;
} else
if ($_POST["submit"] == "Done") {
print "<pre>";
print_r($_POST["firstname"]);
print_r($_POST["lastname"]);
print "</pre>";
}
?>
<form method="post">
<?php for($i = 0; $i < $count; $i++) { ?>
<p class="field">
<input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" />
<input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
</p>
<?php } ?>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.
A general outline of the solution is this:
Initially $count is 1, and one row is generated.
If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
If the user clicks Submit, the names that have been entered are processed.
Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>