I am having some problem to retrieve input values from dynamically added jquery table row ...
these are my code .. expecting a good solution .. thanks in advance :)
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//This line clones the row inside the '.row' class and transforms it to plain html.
var clonedRow = $('.row').clone().html();
//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
var appendRow = '<tr class = "row">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
//this line get's the last row and appends the appendRow when it finds the correct row.
$('.employmentHistoryForm tr:last').after(appendRow);
});
//when you click on the button called "delete", the function inside will be triggered.
$('.deleteThisRow').live('click',function(){
var rowLength = $('.row').length;
//this line makes sure that we don't ever run out of rows.
if(rowLength > 1){
deleteRow(this);
}else{
$('.employmentHistoryForm tr:last').after(appendRow);
deleteRow(this);
}
});
function deleteRow(currentNode){
$(currentNode).parent().parent().remove();
}
});
</script>
</head>
// finaly i need pass the values from text feild ...
<body>
<form name="add_row" method="post" action="process.php">
<div class="employmentHistory">
<table class="employmentHistoryForm">
<tr class = "row">
<td> <label for="company">Name</label></br>
<input type="text" name="name" />
<g:textField name="company" class="company">
</g:textField></td>
<td><label for="position"> Position </label></br>
<input type="text" name="name" />
<g:textField name="position" ></g:textField></td>
<td></br><input type="button" class="deleteThisRow" value="Delete"/></td>
</tr>
</table>
</div>
<input type="button" id="btnAddMore" value="add more"/>
</body>
change the text field names to name1,name2,name3....namen
on the php side get the length of array like.
$numoftxtfield = count($_POST);
this gives the length of text field then using for loop or foreach loop get the all values of the text fields.
IF you do not want to change name of text field then you can use name as an array like..
name = "name[]"
after submit form you can retrive it by implode/explode.
Related
I have a form in which users can dynamically add rows. In each row there is a drop-down menu of products that should auto-populate a text field with the price associated with the product chosen. This works perfectly for the first row, but does not work in the dynamically added rows. The product names are still being pulled from the mysql database into the drop-down, but it is not auto-populating the text field when chosen. Any help would be appreciated!
EDIT: I added the following section, which I think will make this whole thing work, I just need to figure out how to attach the i variable to the name or id or class, and then I can have the auto-populate code include price[i] and product[i]... and I THINK that will make it work for each dynamically added row. Any ideas now?
for(var i=0;i<$('.orderform tr').length;i++)
{
}
END EDIT
Auto-populate code:
<script>
$(function() {
$('select[name="product[]"]').change(function()
{
$('#price').val($('select[name="product[]"] option:selected').data('price'));
});
});
</script>
Adding a row code:
<script>
$(document).ready(function(){
//This line clones the row inside the '.row' class and transforms it to plain html.
var clonedRow = $('.row').clone().html();
//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
var appendRow = '<tr class = "row">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
//this line get's the last row and appends the appendRow when it finds the correct row.
$('.orderForm tr:last').after(appendRow);
for(var i=0;i<$('.orderform tr').length;i++)
{
}
});
</script>
HTML/PHP:
<table class="orderForm" id="orderForm" width="100%">
<tr class="row">
<td>
<div class="pure-control-group">
<label>Product or Service</label><select name="product[]" id="product">
<option value=""></option>
<?php while($productRow = mysql_fetch_assoc($productResult)){?>
<option value="<?php echo $productRow['prouct_id'];?>" data-price="$<?php echo $productRow['price']; ?>"><?php echo $productRow['product']; ?></option>
<?php } ?>
</select>
</div>
<div class="pure-control-group">
<label>Price</label><input type="text" id="price" name="price[]">
</div>
<input type="button" class="deleteThisRow" id="deleteThisRow" value="Delete"/>
</td>
</tr>
</table>
<input type="button" id="btnAddMore" value="Add Product or Service" class="pure-button"/>
.clone() by default doesn't clone the event handlers. You can use .clone(true).appendTo(".orderForm");. The true parameter of the .clone() function copies the values and events over as well.
Is it possible to have a text input field which displays somewhere else (e.g. in a div) what its content is on change?
Example: I type 1, so 1 is outputted somewhere on my screen immediatly, then I type 2 and the previous value is now updated to 12.
html
<input type="text" id="inputField" />
<div id="screen"></div>
script
document.getElementById('inputField').onkeyup = function(){
document.getElementById('screen').innerHTML = this.value;
};
The code is good but I want the screen's inner html value to be format in php. Example: the screen value is stored into $screen and then I'd echo the output where i want into the screen
[I want (echo "$screen";) like in php I will type the number in text box means it echo the value immediately used with php format]
how to store a screen value into variable $screen
You can do this by little javascript code, (assuming that you need to display text entered in a input field on a html div),
So try this in html,
<input type="text" id="inputField" />
<div id="screen"></div>
and bind a onkeyup event to the input field by which you can get the text when someone enters into it. So your javascript will be,
document.getElementById('inputField').onkeyup = function(){
document.getElementById('screen').innerHTML = this.value;
};
Working demo here and you can post the input field value to any php script by including a form element in your html code.
Try this,
HTML
<input type="text" id="addInput" />
<div id="showdata"></div>
SCRIPT
$('input#addInput').on('keyup',function(){
$('div#showdata').html($(this).val());
});
<html >
<head>
<script type="text/javascript">
function KeyHandler() {
var result = document.getElementById('result');
result.innerHTML=document.getElementById('txtInput').value;
}
</script>
</head>
<body >
<div>Type something.........</div><br />
<input type='text' id='txtInput'onkeyup="KeyHandler()" />
<br/>
Result:
<div id="result"></div>
</body>
</html>
I have got a form (php in html or the other way around). Once user selects an option in a drop down list, it would get the input value and create a few text boxes. It seems like I have to use onchange(). How do I read the input and perform logics within the script inself? Instead of opening another .php script?
Currently this is what I have.
<?php
$tables = $_POST["tables"];
?>
<html>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
Table Name: <div id="tables">
<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>
</div>
</form>
<?
echo "".$tables."";
?>
You can't interact with PHP once the HTML is sent to the browser without either
Refreshing the page, or
Using AJAX (JavaScript).
If you know the options in the <select> beforehand (which it seems like you do), you should write some JavaScript to accomplish what you need. Here is a simple example using jQuery.
$('#tables_select').change(
function( eventObject ){
alert('You chose ' + $(this).val());
switch( $( this ).val())
{
case 'Applications':
$('#tables').append('<input type="text" name="application_name" value="Enter an application name" />"');
break;
case 'Device':
$('#tables').append('<input type="text" name="device_name" value="Enter a device name" />"');
break;
}
}
);
You will need to add additional logic to remove the inserted elements if the user changes their choice, and to insert the correct <input> elements when the page first loads, but it is a good starting point.
if you want to add any input type ... here is the demo demo with code
you use following method.
<form method="post" action="<?php echo $PHP_SELF;?>" onChange="return createTxtbox()">
Table Name: <div id="tables">
<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>
</div>
<span id="fooBar"> </span>
</form>
then write javascript,
<SCRIPT language="javascript">
function createTxtbox() {
var type="text";
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>
I'm attempting to make it so that when you click a button, it'll add new fields to the page. I know that onclick can only take JS functions so I decided to try my luck making a JS script. At first I had tried to do
<html>
<head><title>multiple line test</title><head>
<body>
<script type="text/javascript">
var texters='';
var num=0;
function newInput(nomnom)
{
texters='';
num=nomnom+1;
for (var i=0; i<nomnom; i++)
{
texters+='<p>\
Please specify a file, or a set of files:<br>\
<input type="file" size="40">\
</p>\
<p>\
Caption : <br> \
<input type="text" size="30">\
</p>';\
}
document.write(texters+'<div>\
<input type="submit" value="Send">\
</div>\
</form>\
<br>' + '<input type="button" value="new entry" onclick="newInput(num)">' . '</body></html>');
}
newInput(num);
</script>
</body>
</html>
but that didn't work. So I tried instead to add a little bit of php being that I know it better. I tried this :
<html>
<head><title>multiple line test</title><head>
<body>
<script type="text/javascript">
var texters='';
var num=0;
function newInput(nomnom)
{
document.write(<?php
tex='';
for (var i=0; i<=(nomnom); i++)
{
tex.='<p>
Please specify a file, or a set of files:<br>
<input type="file" size="40">
</p>
<p>
Caption : <br>
<input type="text" size="30">
</p>';
}
echo tex . '<div>
<input type="submit" value="Send">
</div>
</form>
<br>' . '<input type="button" value="new entry" onclick="newInput(num)">' . '</body></html>';
?>);
}
newInput(num);
</script>
</body>
</html>
But I know that won't work because I can't get the variable I'm using for the number of fields to use out of the JS and into the PHP. Is there any way I could force JS to put that number in $_POST so I can retrieve it without having to make another form? Or is there a better way to do what I'm trying to do?
You can set a hidden input field on the form, and have the Javascript populate that.
You should try using jquery http://jquery.com/ or a simialr scripting library as it will make manipulating the DOM much easier. Using jquery you can create an onClick function that will do what you want in a few lines of code:
var onClickAddInput = function()
{
$('div#your_div_id').append('<input type="text" size="30" />');
}
If you need to add more input boxes you could loop the append statement and give the individual input boxes ids that equal the loop number.
As commented PHP is for serverside, javascript for clientside. html is the ui elements which either can create. If you need something done on the server, do it in PHP, if it needs to be done on the client, do it in javascript. Here is a sample of javascript for you.
function newInput(nomnom)
{
var tex='';
for (var i=0; i<=(nomnom); i++)
{
tex+='<p>Please specify a file, or a set of files:';
tex+='<br/><input type="file" size="40"></p>';
tex+='<p>Caption :';
tex+='<br/><input type="text" size="30"></p>';
}
document.getElementById('form_id').innerHTML += tex;
}
when this function is called, it will create a number of new inputs and add them to the form with the id "form_id".
Is it possible?
I want a user to post an array full of 1-5 pieces of data.
At first there would be only one text field on show, but on clicking a 'plus' icon next to it, it would create another text field below it for more user input.
I would also want to have a delete icon next to text boxes 2-5, to remove them if necessary.
My JQuery knowledge is limited, and I can work out how to append text boxes to a list, but not to keep track of them/delete them. Ideally I would also want to pass them as an array to php, so I can easily loop through them.
<input type="text" size="15" maxlength="15" name="1"><img src="add.png" onclick="add();">
<!-- Below is hidden by default, and each one shows on click of the add image -->
<input type="text" size="15" maxlength="15" name="2"><img src="delete.png" onclick="delete(2);">
<input type="text" size="15" maxlength="15" name="3"><img src="delete.png" onclick="delete(3);">
<input type="text" size="15" maxlength="15" name="4"><img src="delete.png" onclick="delete(4);">
<input type="text" size="15" maxlength="15" name="5"><img src="delete.png" onclick="delete(5);">
jQuery clone() is very handy for this. A small example how it could be done (working example on jsfiddle)
<ul>
<li><input type="text" name="textbox[]" /></li>
</ul>
<input type="button" id="addTextbox" value="Add textbox" />
<script type="text/javascript">
$(function(){
$('#addTextbox').click(function(){
var li = $('ul li:first').clone().appendTo($('ul'));
// empty the value if something is already filled in the cloned copy
li.children('input').val('');
li.append($('<button />').click(function(){
li.remove();
// don't need to check how many there are, since it will be less than 5.
$('#addTextbox').attr('disabled',false);
}).text('Remove'));
// disable button if its the 5th that was added
if ($('ul').children().length==5){
$(this).attr('disabled',true);
}
});
});
</script>
For the server-side part, you could then do a foreach() loop through the $_POST['textbox']
As long as you give each text box a name like "my_input[]", then when the form is submitted, PHP can get the answer(s) as an array.
$_REQUEST['my_input']; would be an array of the values stored in each text box.
Source: Add and Remove items with jQuery
Add
Remove
<p><input type="text" value="1" /></p>
<script type="text/javascript">
$(function() { // when document has loaded
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});
$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});
$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});
});
</script>
You will need to create DOM elements dynamically. See how it is done for example in this question. Notice that
document.createElement
is faster then using jquery's syntax like
$('<div></div>')
Using that technick, you could create inputs like
<input name="id1"/>
<input name="id2"/>
<input name="id3"/>
<input name="id4"/>
<input name="id5"/>
On submitting your form you'll get all them in your query string like
...id1=someval1&id2=someval2&...
Having that, you could process this query as you want on server side.
<form method="POST" id="myform">
<input />
Add textbox
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#add_textbox').click(function(){
var form=$(this).closest('form');
var count=form.find('input').length();
form.append('<div class="removable_textbox"><input />delete</div>');
$('.delete_input').click(function(){
$(this).find('.removable_textbox').remove();
return false;
});
return false;
});
$('#myform').submit(function(){
var i=1;
$(this).find('input').each(function(){
$(this).attr('name','input-'+i);
i++;
})
});
});
</script>
<?php
if(isset($_POST['input-1'])){
$input_array=$_POST;
}
?>
something like this?
I wrote a litte jQuery plugin called textbox. You can find it here: http://jsfiddle.net/mkuklis/pQyYy/2/
You can initialize it on the form element like this:
$('#form').textbox({
maxNum: 5,
values: ["test1"],
name: "textbox",
onSubmit: function(data) {
// do something with form data
}
});
the settings are optional and they indicate:
maxNum - the max number of elements rendered on the screen
values - an array of initial values (you can use this to pass initial values which for example could come from server)
name - the name of the input text field
onSubmit - onSubmit callback executed when save button is clicked. The passed data parameter holds serialized form data.
The plugin is not perfect but it could be a good start.