Trouble with cloning in jQuery - php

In a form that needs a variant number of band members I am using the following code on a button to duplicate an input.
A snippet of the HTML is this:
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<label for="band_member">Band Member: </label>
<input type="text" name="name1" id="name1" />
</div>
<div>
<input type="button" id="btnAdd" value=" add another member " />
</div>
And this jquery is in the document ready function:
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first').attr( 'val', '' ).attr('id', 'name' + newNum).attr('name', 'name' + newNum);
$('#input' + num).after(newElem);
$("#band_member_count").val( newNum );
}); // end btnAdd click
When the form is submitted, the added inputs aren't being submitted with the last entry becoming the value of the first input and the value of each newly added input is not being cleared like the code indicates.
I would greatly appreciate any assistance with this.
Thanks in advance,
Jon

I think the reason it isn't working is because you are adding the id="name" + num to the label, rather than the input and each input therefore has the same exact id.
Change the first selector to input selector:
newElem.children(':first').attr( 'val', '' ).attr('id', 'name' + newNum).attr('name', 'name' + newNum);
should be:
newElem.find('input').attr('id', 'name' + newNum).attr('name', 'name' + newNum).val("");

Related

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 Values from dynamic textbox?

I have this codes that create a textbox, and each textbox has it's own unique id eg textbox1, textbox2 so on. I had trouble in submitting the data because the textbox is dynamic, u will not know how many textbox created by the user., so I dont have idea on how to post the data eg., $_POST['textbox'],.
$(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", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" name="txtLine' + counter + '" id="txtLine' + counter + '" placeholder="Line#' + counter +' " >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
You can submit the form elements with square brackets like so and it will post all of the form inputs as an array:
<form method="post" action="form.php">
<input name="txtLine[]" />
<input name="txtLine[]" />
<input name="txtLine[]" />
<input type="submit" />
</form>
You can then access all of them in an array like so $_POST["txtLine"]
Output of $_POST:
Array
(
[txtLine] => Array
(
[0] => hey
[1] => there
[2] => jack
)
)

Get values inserted for field dynamically

I would like to insert up to 10 fields dynamically 10 into my form :
<form action="" method="post">
...
<div id="dynamicInput">Entry 1
<br>
<input type="text" name="myInputs[]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
...
<input type="submit" class="btn btn-primary" />
</form>
JS code :
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
After clicking submit in form ( with post method ) I hope to get values inserted in this field in my php page?
For example I inserted 3 values dynamically using the JS code above, so I hope to get in my php page an array like this :
Array(
[0] => value1, [1] => value2, [2] => value3
)
Your initial form :
<div id="dynamicInput">Entry 1
<br><input type="text" name="myInputs[]">
</div>
and your javascript :
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
Give this dynamically generate field the name name='myInputs[]'> myInputs
Therefore when you receive the forms data back into your PHP code you will receive this in the $_POST array:
$_POST['myInputs'][0] = data in the first field
$_POST['myInputs'][1] = data in the second field
$_POST['myInputs'][2] = data in the third field
...
$_POST['myInputs'][9] = data in the tenth field
I don't know how to do with javascript but by using jquery you can do achieve it easily
please add script jquery.js in your site
HTML
<div id="dynamicInput">Entry 1
<input type="text" name="myInputs[]" class="myInputs" />
<input type="button" class="add_input" value="Add another text input" />
</div>
jQuery
$(document).ready(function(){
var limit = 10;
$(".add_input").on('click', function(){
if( $(".myInputs").length == limit ){
alert("You have reached the limit of adding " + limit + " inputs");
return false;
}
$(".myInputs:last").after("<br>Entry "+ ( $(".myInputs").length + 1 )+" <input type='text' name='myInputs[]' class='myInputs' />");
});
});
you can also check example at JSFiddle

Posting and retrieving Multiple Text box values using Jquery and PHP

I have Jquery code that can create multiple text boxes .Now, i want to submit my text boxes' values so that i could get them using PHP on next page.I want to submit text box in the same way as ( )
and on the second page,i could get values using POST method.How can i i post multiple text values in this case and how can i retrieve them on the next page using php?? Plz help as i am a new bee.
CODE:
<head>
<script type="text/javascript">
$(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", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--; $("#TextBoxDiv" + counter).remove(); });
$("#getButtonValue").click(function ()
{
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
Try to giving name for text boxes as array
e.g. input type='textbox' name='textbox[]' id='textbox1'
and access it on PHP page as array
$arrayRequest = $_REQUEST['textbox'];

how to send the radio button information in ajax based form in PHP?

I have made an ajax based form for the website, it takes input from the user and sends it to the database. All fields are working fine but there is a problem with the radio buttons in sending the values.
My code for the ajax is
<script type="text/javascript">
function emp1() {
.....................
xmlhttp.send("firstname=" + firstname.value + "&lastname=" + lastname.value + "&company=" + company.value
+ "&myemail=" + myemail.value
+ "&address=" + address.value
+ "&city=" + city.value
+ "&province=" + province.value
+ "&postalcode=" + postalcode.value
+ "&country=" + country.value
+ "&contact=" + contact.value
+ "&radio1=" + radio1.value
+ "&paymentmethod=" + paymentmethod.value
);
}
code for html form for radio buttons is
<input type="radio" name="radio1" id="radio1" value="Free Shipping" onclick="emp1();"> Free Shipping<br />
<input type="radio" name="paymentmethod" id="paymentmethod" value="abc" onclick="emp1();">abc
<br />
<input type="radio" name="paymentmethod" id="paymentmethod" value="def" onclick="emp1();" onchange="emp1();">def
<br />
<input type="radio" name="paymentmethod" id="paymentmethod" value="ghi" onclick="emp1();">ghi
Any help ... ..
thnx in advance
You can use something like this to get selected radio button vlaue using javascript inside your emp1() function. it will give you selected radio button value.
var inputs = document.getElementsByName("paymentmethod");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
var paymentmethod = inputs[i].value;
}
}
alert(paymentmethod);

Categories