post dynamically generated textbox using foreach loop - php

i want to post dynamically generated multiple text box using php by foreach loop.
for instance i m working on question bank and for post multiple answer from php.
here is my code that dynamically generated textbox but now i donot know how to post value of generated textbox thru foreach loop.
$("#questionbank").live('click',function(){
var mydata = '<div id="questionbank-content" class="page">';
mydata += '<div class="question"><div class="Label">Question</div><div class="textarea"><textarea id="question" rows="3" cols="30"></textarea></div></div><div class="answer"><div class="Label">Answer</div><div class="textarea"><textarea id="answer" rows="3" cols="30"></textarea></div><div class="option"><input id="a" name="answers" type="radio"></div><span id="add">Add</span>';
var i=1;
$('#add').live('click',function(){
j=i++;
$(this).after('<div class="Label">Answer</div><div class="textarea"><textarea id="answer + '+ j +'" rows="3" cols="30"></textarea></div><div class="option"><input id="a + '+ j +'" name="answers" type="radio"></div><span id="add">Add</span>');
//$(this).after('<input id="'+ j +'" type="text" value="'+ j +'"/><span id="add">Add</span>');
$(this).remove();
});
mydata += '</div></div>';
$("#leftcontainer").html(mydata);
});

Consider the following HTML
<div id="start">Start</div>
<div id="container">
</div>
I guess you want to post data from each value of the textbox/textarea by $.post() or $.ajax()
var i=1;
$('#start').one('click',function(){
j=i++;
$('#container').append('<input id="answer'+ j +'" type="text" value=""/><span id="add">Add</span>');
$('#container').after('<div id="submit">Submit</div');
});
$('#add').live('click',function(){
j=i++;
$(this).after('<input id="answer'+ j +'" type="text" value=""/><span id="add">Add</span>');
$(this).next().next().after('');
$(this).remove();
});
$('#submit').live('click',function(){
var x = $('#container > input');
var qstring='op=insertquestion'; //additional para if u want to pass any
$.each(x,function(index,value){
var id = $(this).attr('id');
var data = $(this).val();
qstring += '&'+id+'='+data+'';
});
$('#start').before(qstring + '<br/>');
});
After you get the variable qstring just post the string using $.post() method.
Example on JSFIDDLE.net

The easiest way would be to construct the textarea and submit button via jQuery and attach an click handler. Not a complete solution but it should hopefully give you an idea:
$("#add").live("click", function() {
var textarea = $("<textarea />", { "class": "textarea" });
var submitButton = $("<button />", { "type": "submit" });
submitButton.bind("click", function() {
var text = textarea.val();
$.post("/path/to/script.php", { text: text });
});
});
This will create a textarea and a submit button. When invoking the submit button, a HTTP POST is made to script.php with the textarea content as a parameter.

Related

Jquery not gathering textarea values and not sending arrays to php under specific conditions

I am trying to make a system that gets the value of all textareas into one array and then send it to php for processing, if a page only has textareas with textbox like here:
<div class='form-group'>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
<div class='col-sm-10'>
<input type='text' class='form-control'></input>
</div>
</div>
Everything goes fine. However if the page includes radio boxes:
<div class='form-group'>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
<div class='radio'>
<input type='radio' name='optradio'></input>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
</div>
<div class='radio'>
<input type='radio' name='optradio'></input>
<textarea id='" + counter + "'></textarea>
</div>
</div>
The jquery code does not collect all textareas and does not successfully send it to the php code for processing.
$("#save").click(function () {
for (var i = 0; i < counter; i++) {
form1[i].push($("#" + i).val());
}
$.post("FormResponse.php", {form: form1, formid:$("#formnum").val()}, function (response, status) {
document.write(response);
});
Update:
I changed my jquery code around to get both the type and the textarea values in one place and it still doesn't work. I didn't want to use objects because I want it to be easy for my php code to differentiate which textareas belong to which inputs.
Here is the code revision:
$("#save").click(function () {
var ind = 0;
for (var i = 0; i < inputcounter; i++) {
if (document.getElementById("input#" + i) !== null) {
form1.push($("input#" + i).type());
ind = ind + 1;
}
form1[ind].push($("textarea#" + i).val());
}
document.write(form1);
$.post("FormResponse.php", {form: form1, formid: $("#formnum").val()}, function (response, status) {
document.write(response);
});
});
Haven't tested it but try this.
$("#save").click(function () {
var data = {};
$.each($('textarea'),function(){
var $this = $(this);
data[$this.id] = $this.val();
})
$.post("FormResponse.php",data,function(rep){
console.log(rep);
});
});
Edit
I have no idea what your comment means.
You do realize that you sending a object in your code right?
The PHP code still accesses the data in the same way.
If you mean that you don't know what index the data will be in, then try the code below.
$("#save").click(function () {
var data = {};
$.each($('textarea'),function(){
var $this = $(this);
data[$this.id] = $this.val();
})
$.post("FormResponse.php",{form:data, formid:$("#formnum").val()},function(rep){
console.log(rep);
});
});

posting array of text fields using jquery and ajax

i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.

Get a value from an input field

I am using the code below using jQuery and AJAX, to update my database.
Deletion works perfectly, but the edit function is not working. How is it possible to get the value from each input field?
<ol class="update">
<?php
$ss = mysql_query ("SELECT * FROM users_channels WHERE u_id='$uid'");
while ($chann = mysql_fetch_assoc($ss)) {
echo'
<li>
<input name="channelName" type="text" id="channelName" style="float:left; width:300px; border:1px solid #CCC;" value="'.$chann['channel_name'].'" />
<span id="rcolor">Delete</span>
<span id="gcolor">Save</span>
</li>';
}
?>
</ol>
Javascript code:
$(document).ready(function() {
$(function() {
$(".save_button").click(function() {
var id = $(this).attr("id");
var cvalue = $(this).attr("cvalue");
var dataStringe = 'id=' + id + '&cvalue=' + cvalue;
var parent = $(this).parent();
alert(cvalue);
$.ajax({
type: "POST",
url: "update_channel.php",
data: dataStringe,
cache: false,
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'}, 300).animate({ opacity: 0.35 }, "slow");
},
success: function() {
//parent.slideUp('slow', function() {$(this).remove();});
}
});
return false;
});
});
});
Add this in your java script function
$(document).ready(function() {
$(function() {
$(".save_button").click(function() {
var inputVal=$("#channelName").val();
//rest of your code
return false;
});
});
});
you'll get the value of an input field(as per your question) in inputVal variable.
In order to get the values of all input fields,give them a common class name instead of giving style there like this
<input class="myInput" type="text" value="red" id="one"/>
<input class="myInput" type="text" value="France" id="two" />
and then in your javascript add this
var inputValues= {};
$(".myInput").each(function() {
inputValues[$(this).attr("id")] = $(this).val();
});
alert(inputValues.one); // "red"
you'll get the value of all input fields in inputValues variable
can u be more explicit? What do you need to get? Value of all input elements? if yes .. use $('input[name=example]').each(function(){})
this will get all values of all input with specified name
I guess what you're trying to do is submit the value of your input field as cvalue? To do this, the best approach would be:
$(".save_button").click(function() {
var id = $(this).attr("id");
var parent = $(this).parent();
var cvalue = parent.find('input').val(); // this gets the value of the <input> field
var dataStringe = 'id='+ id + '&cvalue='+ cvalue;
// the rest of your code...
});

Create Element Doesn't work in jquery 1.8.3

I Have used jquery 1.8.3 to Dynamically Create the Element. But It doesn't working on this. but It's working on 1.3.2 version. Below is My Jquery Code Which I Have used for that.
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'CallBackDiv' + counter);
newTextBoxDiv.after().html('<label>Call Back Date Time #'+ counter + ': </label>'+
'<div class="controls"><input type="text" name="callback' + counter +
'" id="callback' + counter + '" value="" ></div>');
newTextBoxDiv.appendTo("#control-group");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#CallBackDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n CallBack #" + i + " : " + $('#callback' + i).val();
}
alert(msg);
});
});
<div id='control-group'>
<div id="CallBackDiv1">
<label class="control-label" for="input01">
Call Back Date Time #1:</label><div class="controls">
<input type='textbox' id='callback1' ></div>
</div>
</div>
<input type='button' value='+' id='addButton'>
<input type='button' value='-' id='removeButton'>
There's nothing wrong with the way you are creating the div. The problem with your code is your use of jQuery's after() function. Calling after() on a newly created element will return null, which you are then calling the html() method on. I suggest you read up on how to use the after() function -> http://api.jquery.com/after/
Using jQuery you can dynamically create elements like this:
// Create a new div
var newTextBoxDiv = $('<div/>', {
id: 'CallBackDiv' + counter
});
// Append the new element to the DOM
newTextBoxDiv.appendTo("#control-group");
// You can check the console for the 'newTextBoxDiv' id
console.log(newTextBoxDiv.attr('id'));
// Then call the after part
newTextBoxDiv.after().html('...');
FIDDLE DEMO
why dont you do it in plain js
var newTextBoxDiv = document.createElement('div');
newTextBoxDiv.setAttribute("id", 'CallBackDiv' + counter);

Dynamically remove select form fields inside divs with data taken from php

I have a form with select fields dynamically generated and with the options taken from php (same for all the selects). The "add" button is working but the "remove" button is not working perfectly, it´s not deleting everything and if you add again, it goes below the ideal position.
This is the code that I have:
<script type="text/javascript">
//<![CDATA[
$(function(){
var counter = 1;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var select = $('<select>').attr({id:'select'+counter,name:'select'+counter});
$.ajax({
url: 'selects.php',
dataType: "html",
success: function(data) {
select.html(data);
}
});
select.appendTo("#TextBoxesGroup");
$("#TextBoxesGroup > select").wrap ( function () {
return '<div id="wrap_' + this.id + '"></div>';
} );
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#wrap_" + counter).remove();
$("#select" + counter).remove();
});
});
//]]>
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1' >
</div>
<div id="TextBoxDiv2">
<label>Textbox #2 : </label><input type='text' id='textbox2' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
And this is the html code generated by select.php:
<option value="1">Uno</option>
<option value="2">Dos</option>
<option value="3">Tres</option>
<option value="4">Cuatro</option>
the problem ids this when you return
return '<div id="wrap_' + this.id + '"></div>'
this.id is select's id
but when you are removing
$("#wrap_" + counter).remove();
try to remove by
$("#wrap_select" + counter).remove();
because your div's id is
wrap_select+'some value' not wrap_+'some value'
As the other 2 answers said, the problem is:
$("#wrap_" + counter).remove();
Change it to:
$("#wrap_select" + counter).remove ();
To match how the wrap-div was created.
See it in action at jsFiddle.
The selects get the id 'select'+counter, and the wrappers get the id 'wrap_' + this.id, and this.id is, if I'm not too morning tired, not the same as the counter.
And since you're doing this
$("#wrap_" + counter).remove();
$("#select" + counter).remove();
You're not removing the wrapper.

Categories