Adding XML attribute from array PHP - javascript

I am have a dynamic HTML form (jQuery) that a user can add in an ingredient and its quantity, After the user puts in the data I need to save the data as XML. I was thinking of having the quantity as an attribute of the ingredient tag, so for example
<ingredient quantity="250g"> spaghetti </ingredient>
However at the moment I'm not sure how to pass the information in through my array as only a string is allowed as an attribute. I was wondering if anyone had an idea how to do this?
Here are some snippets of my code.
HTML form:
<div id="addIngredient">
<p>
<input type="text" id="ingredient_1" name="ingredient[]" value="" placeholder="Ingredient"/>
<input type="text" id="quantity_1" name="quantity[]" value="" placeholder="quantity"/>
Add
</p>
</div>
<br />
jQuery:
$('#addNewIngredient').on('click', function () {
$('<p> <input id="ingredient_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /><input id="quantity_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" /> Remove </p> ').appendTo(addDiv2);
i++;
return false;
});
PHP:
$ingredients = $xml->createElement('ingredients');
for ($i = 0; $i < 2; $i++) {
$element = $ingredientName[$i];
$ingredient = $xml->createElement('ingredient_name', $element);
$ingredient->setAttribute("quantity", $quantity);
$ingredients->appendChild($ingredient);
}
$recipe->appendChild($ingredients);

Related

JS/JQuery : continue with the index of array of the form while generating new fields

I have a form that is generated dynamically using PHP with a foreach loop.
The input fields of this form are inturn returning the data in a 3-D array which makes it easy to back-track where to submit these fields and how to store them. so here is is the form:
<?php
$i = 0;
foreach ($shop->fetch()->showResults() as $sr){
$j = 0;
if($i == 0){
echo '<div id="ser'.$sr->id.'" location = "'.$sr->id.'" class="tab-pane fade active in">';
$i++;
} else{
echo '<div id="ser'.$sr->id.'" location = "'.$sr->id.'" class="tab-pane fade">';
$i++;
}
$ser = new Service(Input::get('cd'));
$ser->fetchPriceInShop($sr->id, $ser->fetchData()->id);
foreach ($ser->fetchData() as $price){
echo '<input type="text" value="'.$price->duration.'" name="price['.$sr->id.']['.$j.'][duration]" placeholder="duration (in Minutes)">
<input type="text" value="'.$price->price.'" name="price['.$sr->id.']['.$j.'][price]" placeholder="Price ($ 100)">
<br>';
$j++;
}
echo '
<button style="float: right;" class="addPrice" type="button">+</button>
</div>';
}
?>
so the resulting form is something like this:
<input type="text" value="10.00" name="price[1][0][price]" placeholder="Price ($ 100)">
<br><input type="text" value="20" name="price[1][1][duration]" placeholder="duration (in Minutes)">
<input type="text" value="20.00" name="price[1][1][price]" placeholder="Price ($ 100)">
<br><input type="text" value="30" name="price[1][2][duration]" placeholder="duration (in Minutes)">
<input type="text" value="30.00" name="price[1][2][price]" placeholder="Price ($ 100)">
<br>
now, I am trying to make this form flexible where I can add more fields to it and submit value using them. using the following js for that:
$(".addPrice").on("click", function(){
var location = $(this).parent().attr('location');
var element = '<input type="text" placeholder="duration (minutes)" name="prices['+location+'][index][duration]">';
element += '<input type="text" placeholder="price (aud)" name="prices['+location+'][index][price]"><br>';
$(this).parent().append(element);
});
I somehow managed to fetch the first index (location) and the last index are static, but I have no clue how can I find the second index of the array generated. Please help me figuring out the solution.
PS: I am a noob at stack overflow so please don't be harsh. I am learning to use this platform.
I'm recommending a re-structuring of your multi-dim array to avoid unnecessary counting / incrementing.
The form generating php code:
$i=0;
foreach($shop->fetch()->showResults() as $sr){
echo "<div id=\"ser{$sr->id}\" location=\"{$sr->id}\" class=\"tab-pane fade",(!$i++?" active in":""),"\">";
$ser=new Service(Input::get('cd'));
$ser->fetchPriceInShop($sr->id, $ser->fetchData()->id);
foreach($ser->fetchData() as $price){
echo "<input type=\"text\" value=\"{$price->duration}\" name=\"price[{$sr->id}][duration][]\" placeholder=\"duration (in Minutes)\">
<input type=\"text\" value=\"{$price->price}\" name=\"price[{$sr->id}][price][]\" placeholder=\"Price ($ 100)\">
<br>";
}
echo "<button style=\"float:right;\" class=\"addPrice\" type=\"button\">+</button>";
echo "</div>";
}
*note the $i++ condition first checks if it is zero, then increments. This maintains your intended use. Demo of this technique
The jquery code:
$(".addPrice").on("click", function(){
var location = $(this).parent().attr('location');
var element = '<input type="text" placeholder="duration (minutes)" name="price['+location+'][duration][]">';
element += '<input type="text" placeholder="price (aud)" name="price['+location+'][price][]"><br>';
$(this).parent().append(element);
});
I might also like to recommend the use of data-location instead of location as an attribute name.
You can add a class to your price element and count the elements with that class.
var idx = parent.find('.price').length;
function parsePrice(el) {
var parent = $(el).parent();
var location = parent.attr("location");
var idx = parent.find('.price').length;
var element = '<input type="text" placeholder="duration (minutes)" name="price[' + location + '][' + idx + '][duration]">';
element += '<input type="text" placeholder="price (aud)" name="price[' + location + ']['+idx+'][price]"><br>';
$(element).insertBefore(el);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1" location="1" class="tab-pane fade active in">
<input type="text" value="10" name="price[1][0][duration]" placeholder="duration (in Minutes)">
<input class="price" type="text" value="10.00" name="price[1][0][price]" placeholder="Price ($ 100)">
<br><input type="text" value="20" name="price[1][1][duration]" placeholder="duration (in Minutes)">
<input class="price" type="text" value="20.00" name="price[1][1][price]" placeholder="Price ($ 100)">
<br><input type="text" value="30" name="price[1][2][duration]" placeholder="duration (in Minutes)">
<input class="price" type="text" value="30.00" name="price[1][2][price]" placeholder="Price ($ 100)">
<br>
<input type="button" onclick="parsePrice(this);" value="go" />
</div>
Alternately you can group your elements inside of parent container, such as a div in your PHP loop:
foreach ($ser->fetchData() as $price){
echo '<div class="pricediv price-'.$sr->id.'"><input type="text" value="'.$price->duration.'" name="price['.$sr->id.']['.$j.'][duration]" placeholder="duration (in Minutes)">
<input type="text" value="'.$price->price.'" name="price['.$sr->id.']['.$j.'][price]" placeholder="Price ($ 100)">
</div>';
$j++;
}
And then select a count of those elements:
function parsePrice(el) {
var parent = $(el).parent();
var location = parent.attr("location");
var idx = parent.find('div').length;
var element = '<input type="text" placeholder="duration (minutes)" name="price[' + location + '][' + idx + '][duration]">';
element += '<input type="text" placeholder="price (aud)" name="price[' + location + '][' + idx + '][price]"><br>';
$(element).insertBefore(el);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1" location="1" class="tab-pane fade active in">
<div class="pricediv price-1"><input type="text" value="10" name="price[1][0][duration]" placeholder="duration (in Minutes)">
<input class="price" type="text" value="10.00" name="price[1][0][price]" placeholder="Price ($ 100)">
</div>
<div class="pricediv price-2"><input type="text" value="20" name="price[1][1][duration]" placeholder="duration (in Minutes)">
<input class="price" type="text" value="20.00" name="price[1][1][price]" placeholder="Price ($ 100)">
</div>
<div class="pricediv price-3"><input type="text" value="30" name="price[1][2][duration]" placeholder="duration (in Minutes)">
<input class="price" type="text" value="30.00" name="price[1][2][price]" placeholder="Price ($ 100)">
<br>
<input type="button" onclick="parsePrice(this);" value="go" />
</div>
You could use get elements by Tag name to find the index.
$(".addPrice").on("click", function(){
var location = $(this).parent().attr('location');
var index=$(this).parent().getElementsByTagName("input").length/2;
var element = '<input type="text" placeholder="duration (minutes)" name="prices['+location+']['+index+'][duration]">';
element += '<input type="text" placeholder="price (aud)" name="prices['+location+']['+index+'][price]"><br>';
$(this).parent().append(element);
});

Dynamic JQUERY array works for some records

Thanks to the help from StackOverflow I have got as far as creating a single line entry with fields and then this adds each field to an array but the Hours SQL statement isn't working e.g. it will have blank sql entries for the first 2 records and then work correctly on another but I cannot see what I am doing wrong. Any help would be very appreciated.
<td colspan="3" align="left"><div id="hoursrow">
<p> <span class="text">Hours Labour :</span></span></p>
<p> <span class="headings"><span class="text"><span class="hours">Start Time:
<input type="time" name="add_start" size="4" />
Finish Time:
<input type="time" name="add_finish" size="4" />
Date:
<input type="date" name="add_date" size="4" />
OVT:
<input type="checkbox" name="add_overtime_hours" id="add_overtime_hours" size="1" maxlength="1" />
</span></span><span class="text"><span class="hours">
<input onclick="addhours(this, event);" type="button" value="Add Labour" />
</span></span></p>
<p class="headings"><span class="text"><span class="hours">
<span class="info">(This row will not be saved unless you click on "Add Labour" first) </span></span></span></p>
</div></td>
<td width="7"></td>
</tr>
<tr>
var rownumhours = 1;
function addhours(obj, e) {
rownumhours++;
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[' + rownumhours + ']" size="4" value="' +
$(obj).closest('span.headings').find('[name="add_start"]').val() + '"> Finish Time: <input type="time" name="add_finish[' + rownumhours + ']" value="' +
$(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[' + rownumhours + ']" value="' +
$(obj).closest('span.headings').find('[name="add_date"]').val() + '"> Show_Overtime: <input type="text" name="show_overtime_hours[' + rownumhours + ']" size="1" value="' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? '1' : '0' ) + '"> Overtime: <input type="checkbox" name="add_overtime_hours[' + rownumhours + ']" size="1" value="' +
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '') +
' "> <input type="button" value="Remove" onclick="removeRow(' +
rownumhours + ');"></p>';
jQuery('#hoursrow').append(hoursrow);
$(obj).closest('span.headings').find('[name="add_start"]').val("");
$(obj).closest('span.headings').find('[name="add_finish"]').val("");
$(obj).closest('span.headings').find('[name="add_date"]').val("");
$(obj).closest('span.headings').find('[name="show_overtime_hours"]').val("");
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').removeAttr('checked');
}
function removeRow(rnum) {
jQuery('#rownumhours' + rnum).remove();
}
So it is showing on the page properly as I want it to but then the major problem is is won't add properly to the database.
I have echo'd the sql that is to be inserted into the database and it shows the following.
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
VALUES('904','','','','')
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
VALUES('904','','','','')
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
VALUES('904','10:10','11:11','2017-01-03','') //
The Sql part is as follows
if (
!empty($_POST['add_start']) && !empty($_POST['add_finish']) && !empty($_POST['add_date']) && !empty($_POST['show_overtime_hours'])&&
is_array($_POST['add_start']) && is_array($_POST['add_finish']) && is_array($_POST['add_date']) && is_array($_POST['show_overtime_hours'])&&
count($_POST['show_overtime_hours']) && count($_POST['add_finish']) && count($_POST['add_date']) === count($_POST['add_start'])
) {
$add_start_array = $_POST['add_start'];
$add_finish_array = $_POST['add_finish'];
$add_overtime_hours_array = $_POST['show_overtime_hours'];
$add_date_array =$_POST['add_date'];
for ($i = 0; $i < count($add_start_array); $i++) {
$add_start_values = $mysqli->real_escape_string($add_start_array[$i]);
$add_finish_values = $mysqli->real_escape_string($add_finish_array[$i]);
$add_date_values = $mysqli-> real_escape_string($add_date_array[$i]);
$add_overtime_hours_boolean = $mysqli-> real_escape_string($add_overtime_hours_array[$i]);
$sql_add_hours = "INSERT INTO hours(job_number,start_time,finish_time,date,overtime) VALUES('$increment_job_number','$add_start_values','$add_finish_values','$add_date_values','$add_overtime_hours_boolean')";
$mysqli-> query($sql_add_hours);
// This next section is for debugging only
//echo ($add_date_values);
//echo ($add_start_values);
//echo ($add_finish_values);
echo ($sql_add_hours);
//echo ($add_overtime_hours_values);
}
Ok, after doing some inspections, actually the first group of the html components produced from the JQuery is :
"Start Time:"
<input type="time" name="add_start[2]" size="4" value="23:57">
"Finish Time:"
<input type="time" name="add_finish[2]" size="4" value="22:57">
"Date:"
<input type="date" name="add_date[2]" value="2017-01-13">
"Show_overtime:"
<input type="text" name="show_overtime_hours[2]" size="1" value="0">
"Overtime:"
<input type="checkbox" name="add_overtime_hours[2]" size="1" value="on">
<input type="button" value="Remove" onclick="removeRow(2)">
You see there...,the counter (rownumhours) starts from 2.
Thus in your php part, the first entries for these array :
$add_start_array = $_POST['add_start'];
$add_finish_array = $_POST['add_finish'];
$add_overtime_hours_array = $_POST['show_overtime_hours'];
$add_date_array =$_POST['add_date'];
Also at 2nd-index, but as your loop starts from zero , hence the entry for the location is empty.
So start the rownumhours in javascript part from -1:
var rownumhours = -1;
Quick Fix
You increment the rownumhours before dynamically adding a new row of fields.
The quickest fix is change the rownumhours value to 0
var rownumhours = 0;
So the newly added row of fields will have the index of 1 and up.
Also add [] to the name tag to the first/default row:
<input type="time" name="add_start[]" size="4"> <!-- this will have an index of 0 -->
<!-- DO THE SAME WITH FIRST/DEFAULT SET OF FIELDS -->
Recommendation
But what you can actually do is do not bother with the assigning of index.
Just put [] to the given row of fields:
<td colspan="3" align="left">
<div id="hoursrow">
<p>
<span class="text">Hours Labour :</span>
</p>
<p>
<span class="headings">
<span class="text">
<span class="hours">
Start Time: <input type="time" name="add_start[]" size="4" />
Finish Time: <input type="time" name="add_finish[]" size="4" />
Date: <input type="date" name="add_date[]" size="4" />
OVT: <input type="checkbox" name="add_overtime_hours[]" id="add_overtime_hours" size="1" maxlength="1" />
</span>
</span>
<span class="text">
<span class="hours">
<input onclick="addhours(this, event);" type="button" value="Add Labour" />
</span>
</span>
</span>
</p>
<p class="headings">
<span class="text">
<span class="hours">
<span class="info">(This row will not be saved unless you click on "Add Labour" first)</span>
</span>
</span>
</p>
</div>
</td>
Then remove the rownumhours and do not assign index for dynamically added input fields:
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[]" size="4" value="' + $(obj).closest('span.headings').find('[name="add_start"]').val() + '"> /*** JUST CONTINUE THE REST OF THE INPUT FIELDS ***/
Thank you all so very much for the help. I am sorry It took a few days to reply. I have made the changes by taking the rownumhours ++ off and using the [] for the naming to be taken care of itself which I had no idea it was clever enough to do it on its own.
The Mysql Section worked well and I also left the html section because I only wanted to have different names for the multiple hours into the entries
var rownumhours = 0;
function addhours(obj, e) {
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[]" size="4" value="' +
$(obj).closest('span.headings').find('[name="add_start"]').val() + '"> Finish Time: <input type="time" name="add_finish[]" value="' +
$(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[]" value="' +
$(obj).closest('span.headings').find('[name="add_date"]').val() + '"> <input type="hidden" name="show_overtime_hours[]" size="1" value="' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? '1' : '0' ) + '"> Overtime: <input type="checkbox" name="add_overtime_hours[]" size="1" value="' +
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '') +
' "> <input type="button" value="Remove" onclick="removeRow(' +
rownumhours + ');"></p>';
jQuery('#hoursrow').append(hoursrow);
rownumhours++;
$(obj).closest('span.headings').find('[name="add_start"]').val("");
$(obj).closest('span.headings').find('[name="add_finish"]').val("");
$(obj).closest('span.headings').find('[name="add_date"]').val("");
$(obj).closest('span.headings').find('[name="show_overtime_hours"]').val("");
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').removeAttr('checked');
}
function removeRow(rnum) {
jQuery('#rownumhours' + rnum).remove();
}
</script>

jQuery Calculations after appending more input fields

I am building an expense template an am having an issue regarding using jQuery Calculations and click functionality to append a set of input fields.
I am combining twooncodes, one to calculate the sum of the values in input fields, and the other to Add a new row of input fields when the user clicks so (these are also to be added to the sum). Problem is, the sum is not adding to the total from the newly appended rows. Only the default row of fields adds.
Any help is appreciated (Fiddle ex: http://jsfiddle.net/NicoleScotsburn/o8x02sjh/4/ )
Appending table with inputs code:
//Increment Variables
var items = $('#items');
var i = $('#items td').size() + 1;
var mileage = $('#mileage');
var j = $('#mileage td').size() + 1;
//Append Table Rows
$('#addItem').on('click', function() {
$('<tr><td> <label for="date"><input type="text" id="date" size="10" name="date_' + i +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="desc"><input type="text" id="desc" size="30" name="desc_' + i +'" /></label></td>' +
'<td> $<label for="entmt"><input type="text" id="sum" size="10" name="entmt_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="meals"><input type="text" id="sum" size="10" name="meals_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="other"><input type="text" id="sum" size="10" name="other_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="travel"><input type="text" id="sum" size="10" name="travel_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="lodging"><input type="text" id="sum" size="10" name="lodging_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="hst"><input type="text" id="sum" size="10" name="hst_' + i +'" placeholder="0.00" /></label></td>' +
'<td> Remove</td></tr>').appendTo(items);
i++;
return false;
});
$('#addMileage').on('click', function() {
$('<tr><td> <label for="mdate"><input type="text" id="mdate" size="10" name="mdate' + j +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="mlocation"><input type="text" id="mlocation" size="30" name="mlocation' + j +'" value="" placeholder="" /></label></td>' +
'<td> <label for="km"><input type="text" id="km" size="10" name="km' + j +'" value="" placeholder="" />KM</label></td>' +
'<td> Remove</td></tr>').appendTo(mileage);
j++;
return false;
});
//Remove Buttons
$('body').on('click', '#remItem', function() {
if( i > 2 ) {
$(this).parents('tr').remove();
i--;
}
return false;
});
$('body').on('click', '#remMileage', function() {
if( j > 2 ) {
$(this).parents('tr').remove();
j--;
}
return false;
});
Calculation function: (This works assuming the id of the input is id="sum" and gets outputted to another input called totalsum.
$("input[id^=sum]").sum("keyup", "#totalSum");
I am not familiar with jQuery Calculations, but it looks like what you are doing can be achieved using plain jQuery or javascript. I did a quick google search for jquery sum and I found this other stackoverflow post that might help you. stackoverflow sum
You can add a class attribute called "sum" to all the fields you want to sum up and use the jquery marked as the answer. Once you get done calculating the total you can assign it to the total amount input field.
$('.sum').blur(function () {
var sum = 0;
$('.sum').each(function() {
sum += Number($(this).val());
});
$("#totalsum").val(sum);
});​​​​​​​​​

Save dynamically generated input fields

I am using this code to generate dynamically ADD More input fields and then plan on using Save button to save their values in database. The challenge is that on Save button, I want to keep displaying the User Generated Input fields. However they are being refreshed on Save button clicked.
javascript:
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '">Item quantity: <input type="text" name="qty[]" size="4" value="' + frm.add_qty.value + '"> Item name: <input type="text" name="name[]" value="' + frm.add_name.value + '"> <input type="button" value="Remove" onclick="removeRow(' + rowNum + ');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
</script>
HTML:
<form method="post">
<div id="itemRows">Item quantity:
<input type="text" name="add_qty" size="4" />Item name:
<input type="text" name="add_name" />
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p>
<button id="_save">Save by grabbing html</button>
<br>
</p>
</form>
One approach is to define a template to add it dynamically via jQuery
Template
<script type="text/html" id="form_tpl">
<div class = "control-group" >
<label class = "control-label"for = 'emp_name' > Employer Name </label>
<div class="controls">
<input type="text" name="work_emp_name[<%= element.i %>]" class="work_emp_name"
value="" />
</div>
</div>
Button click event
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData));
counter += 1;
});
The main thing is to call e.preventDefault(); to prevent the page from reload.
You might want to check this working example
http://jsfiddle.net/hatemalimam/EpM7W/
along with what Hatem Alimam wrote,
have your form call an upate.php file, targeting an iframe of 1px.

JQuery ignoring form element

I have this JQuery:
$(document).ready(function() {
$("#generate").click(function() {
var texts = [];
alert();
$("form label").each(function() {
var oLabel = $(this);
var oInput = oLabel.next();
texts.push(oLabel.text() + " " + oInput.val());
});
texts[0] += texts[1];
texts[2] += texts[3];
for(i=3;i<texts.length;i++)
texts[i-1] = texts[i];
texts[texts.length-1] = null;
$("#cont").html(texts.join("<br />"));
});
});
What it do is it reads form elements then types them as regular text (there is a purpose for this).
And this is how my form looks like ...
<div id="cont" style="float:right; width:75%; height:auto">
<form onSubmit="return generate();">
<label class="itemLabel" for="name">Name : </label>
<input name="name" type="text" class="itemInput" value="<? echo $queryB[1]; ?>" readonly="readonly" />
<label># Some Text</label><br />
<label for="priPhone" class="itemLabel">Customer Telephone Number : </label>Phone#
<input name="priPhone" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[2]; ?>" />
<label for="secPhone"> // Mobile#</label>
<input name="secPhone" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[3]; ?>" /><br />
<label class="itemLabel" for="email">Customer Email Address : </label>
<input name="email" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[4]; ?>" /><br />
<label>***************</label><br />
<label>Best Regards,</label><br />
<input name="another_field" type="text" /><br />
<label>last thing</label><br />
<button type="button" id="generate">Generate</button>
</form>
</div>
now, when I click the button "Generate", everything goes well except that it ignores "another_field" and doesn't get its value
Anyone got an idea to solve this? (Note: This piece of code will be running on around 25 forms so I need to have it working.)
UPDATE:
Sample output:
Name : username # Some Text
Customer Telephone Number : 90237590 // 3298579
Customer Email Address : email#host.com
***************
Best Regards,
last_field
last thing
Workaround
Since I'm having all the forms have the same ending, I've been able to get to this code:
texts[0] += " " + texts[1];
texts[1] = texts[2] + " " + texts[3];
for(i=4;i<texts.length;i++)
texts[i-2] = texts[i];
texts[texts.length-2] = texts[texts.length-3];
texts[texts.length-3] = $("#agent").val() ;
texts[texts.length-1] = null;
It solved the problem, but I'm looking for a better way to accomplish this.
Try this javascript:
$(document).ready(function() {
$("#generate").click(function() {
var texts = [];
$("form").children().each(function() {
var el = $(this);
if (el.prop('tagName') == "LABEL") texts.push(el.text());
if (el.prop('tagName') == "INPUT") texts.push(el.val());
if (el.prop('tagName') == "BR") texts.push("<br />");
});
$("#cont").html(texts.join(""));
});
});
Working example here:
http://jsfiddle.net/Q5AD4/6/
Your <br/> tag is the next tag after the label before "another_field". You should probably make your next call something like:
var oInput = oLabel.next('input');

Categories