A bit of background: I am building an transportation system for a school. The admin can add the places to configure the route. I have a just gave a text box to add a place and ADD button to keep adding more text boxes so he can add multiple places at once.
The problem: The user fills the data, if he wish he adds as many as input boxes he needs and sends that to controller. How can i find out, how many he added the place. I can not use JavaScript Validation because of few reason.
I am using php-codeigniter
<div class="control-group">
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Enter Place/Stop</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span10" id="field1" name="place_6" type="text" data-items="8"/><button id="b1" class="btn btn-info add-more" type="button">Add more</button>
</div>
<br>
<small>Press button to add another place</small>
</div>
</div>
</div>
And the jQuery
$(document).ready(function(){
var next = 1;
$(".add-more").click(function(e){
e.preventDefault();
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span10" id="field' + next + '" name="place_' + (next+5) + '" type="text">';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
});
});
Make sure that new and existing inputs are given the name with an ending "[]" instead of a digit and you will get an array inside your $_POST.
This:
<input type="text" name="places[]" />
Would give you:
$_POST['places']; # array() with all posted inputs
And from there you could just do a count().
count($_POST['places']);
Related
What I am trying to achieve:
My form consists of four fields of #item, #unit, #price, and #total.
A user can input multiple lines of #item and #unit. For this, if the user clicks on "Add new line', there will appear a new line to receive user input for item and unit (quantity). If the user clicks on "-" on an already existing line, the line will be removed.
Which item is selected is identified on real-time using javascript change().
The price of the selected item is dynamically retrieved using ajax and the price data is appended into the #price element and #total element is also filled up by calculating #unit x #price.
To achieve this, here's what I did.
First, my HTML form as below.
<form id="form">
<input type="submit" name="create" value="Create" />
<!-- dynamically add more lines -->
<div class="form-group table-row hide" id="template">
<!-- remove button-->
<div class="table-cell" style="width: 45px;">
<a class="btn btn-default removeButton">
<span class="glyphicon glyphicon-minus">
</span>
</a>
</div>
<!-- user input: item -->
<div class="table-cell">
<select id="item" class="form-control">
<option value=""></option>
<option value="item-1">Item 1</option>
<option value="item-2">Item 2</option>
<option value="item-3">Item 3</option>
</select>
</div>
<!-- user input: quantity -->
<div class="table-cell">
<input id="unit" min="1" step="1" value="1" type="number" class="form-control" />
</div>
<!-- price is dynamically filled up using ajax -->
<div class="table-cell">
<input id="price" type="text" class="form-control" />
</div>
<!-- total is dynamically calculated -->
<div class="table-cell">
<input id="total" type="text" class="form-control" />
</div>
</div>
<button type="button" class="btn btn-default addButton">Add new line</button>
</form>
And javascript code to implement dynamic add/remove of input forms.
<script>
jQuery(document).ready(function($) {
var idx = new Number( 0 );
$('#form')
// Add button click handler
.on('click', '.addButton', function() {
var $template = $('#template'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.insertBefore($template);
// assign name attributes with proper array name and index
$clone.find('#item').attr('name', 'lines[' + idx + '][item]').attr('required', 'required').val('');
$clone.find('#unit').attr('name', 'lines[' + idx + '][unit]').attr('required', 'required').val('');
$clone.find('#price').attr('name', 'lines[' + idx + '][price]').attr('required', 'required').val('');
$clone.find('#total').attr('name', 'lines[' + idx + '][total]').val('');
idx = idx + 1;
})
// Remove button click handler
.on('click', '.removeButton', function() {
if (confirm("<?php _e( 'Are you sure you wish to remove this line? This cannot be undone.', 'doumi' ); ?>")) {
var $row = $(this).parents('.form-group');
// Remove element containing the option
$row.remove();
idx = idx - 1;
}
});
});
</script>
Lastly, jQuery to call ajax.
<script>
/* Get Item Price */
jQuery('#item').change(function(){
var $item_id=$('#item').val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// call ajax
jQuery("#price").empty();
jQuery.ajax({
url: ajaxurl,
/* ******************************************************************** */
/* ajax_get_item_price is a function that returns the price of the item */
/* ******************************************************************** */
data:' action=ajax_get_item_price&item_id='+$item_id,
type:'GET',
success:function(results) {
jQuery("#price").append(results);
}
});
});
</script>
I have no problem dynamically adding and removing lines for the input form.
The problem is that form elements in each line is given a name as an array like below;
<select id="item" name="lines[0][item]"></select>
<input id="unit" name="lines[0][unit]" />
<input id="price" name="lines[0][price]" />
<input id="total" name="lines[0][total]" />
<select id="item" name="lines[1][item]"></select>
<input id="unit" name="lines[1][unit]" />
<input id="price" name="lines[1][price]" />
<input id="total" name="lines[1][total]" />
<select id="item" name="lines[2][item]"></select>
<input id="unit" name="lines[2][unit]" />
<input id="price" name="lines[2][price]" />
<input id="total" name="lines[2][total]" />
...
...
...
<select id="item" name="lines[n][item]"></select>
<input id="unit" name="lines[n][unit]" />
<input id="price" name="lines[n][price]" />
<input id="total" name="lines[n][total]" />
I guess that since there are multiple #items with varying names, jQuery does not know which #item it needs to pay attention to. However, I have no idea, either, as to how to properly call ajax with the concerned #item.
Any advice is highly appreciated.
Ok, as I said, ids should be unique for a page, so for similar items you should use classes:
....
<select class="item" name="lines[2][item]"></select>
<input class="unit" name="lines[2][unit]" />
<input class="price" name="lines[2][price]" />
<input class="total" name="lines[2][total]" />
....
So, for change event use something like
jQuery('.item').change(function(){
// to narrow the items, use this
var this$ = $( this );
// this$ contain exactly one item, which is currently changing
// do stuff
});
No quite get what exactly wrong is happening, but I think you have too many items with price is and thus issuing prblems.
So this line does next: gets all #price elements and appends results to each of them.
success:function(results) {
jQuery("#price").append(results);
}
You should clarify which #price item you exactly need.
First, as I already mentioned - use classes for multiple similar fields jQuery(".price")
Second, add some clarification what field exactly should be updated.
There can be many ways, I show two
One way, use next function.
success:function(results) {
this$.next('.price').eq(0).append(results);
// here we refer to this$ - we try to find all `.price` element
// which come after our `select`
// as there can be a lot of them we take only the first one
}
Another way, Use kind of context, ie some div, in bounds of which your elements are grouped.
I suggest changing your html like this
<div class="item-wrapper">
<select class="item" name="lines[2][item]"></select>
<input class="unit" name="lines[2][unit]" />
<input class="price" name="lines[2][price]" />
<input class="total" name="lines[2][total]" />
</div>
So, every block of your fields will be wrapped in a div.
After that we can tell jQUery to find .price element only in a div in which changed select is located
success:function(results) {
var parent$ = this$.parent();
// again we refer to this$ getting its parent which is div
parent$.find('.price').append(results);
// here we try to find `.price` element located in a parent$ div.
// As it is definitely only one, we don't need to use any other code.
}
So, this is all that I can say)
I am trying to have a contract filled in with values from a form on the same page, I have the basic idea but can not understand what I am missing in my application of it.
jQuery(function($) {
var input_5 = $('#input_5');
var Child2Name = $('#Child2Name');
var previewinput_5 = $('.Previewinput_5');
var preview2ChildName = $('.PreviewChild2Name');
input_5.keyup(function(e) {
previewChild1Name.text(input_5.val()); });
Child2Name.keyup(function(e) {
preview2ChildName.text(Child2Name.val()); });
});
<li class="form-line" id="id_5">
<label class="form-label-left" id="label_5" for="input_5">
Legal Business Name<span class="form-required">*</span>
</label>
<div id="cid_5" class="form-input">
<input type="text" class=" form-textbox validate[required]"
data-type="input- textbox" id="input_5" name="q5_legalBusiness"
size="20" value="" />
</div>
</li>
<input type="text" name="child2name" id="Child2Name" />
<Label>Child2 Name</label>
Whether it’s what <span class="input_5"></span> <br>
Whether it’s what <span class="PreviewChild2Name"></span> <BR>
The second part works fine, the first is clearly having issues with how the actual form is being displayed
http://jsfiddle.net/3dMqU/10/
You aren't using the right names(variable name and class name) in these lines:
var previewinput_5 = $('.Previewinput_5');
Whether it’s what <span class="cid_5"></span>
I assume previewinput_5 should be previewChild1Name and Previewinput_5 should be cid_5. Your fiddle worked for me because you did the naming in it correctly, which is why I was confused.
I've a page with two formulas one. Each one has it's own form with inputs etc. They both call the same Javascript function on key up.
Only the first one works, I kind of understand why but I can't find a resolution, I'm too new to Javascript to know how to tackle the problem. I can't change the structure of the JS file a great deal as other equations on other pages depend on this set up.
Is there a workaround?
Shortened HTML:
<div id="formula">
<p>To find ρ<sub>b</sub>:</p>
<form id="formula" name="formula">
<input type="hidden" id="formulaName" name="formulaName" value="porosityRhob"/>
<div>
<label>$\rho_{fl}$:</label>
<input type ="text" name="input" id="input" onkeyup="calculatePEFormula()"/>
</div>
<div>
<label>Result:</label>
<input type="text" id="result" name="result">
</div>
</form>
</div>
<br/>
<div id="formula">
<p>To find Φ:</p>
<form id="formula" name="formula">
<input type="hidden" id="formulaName" name="formulaName" value="porosityPhi"/>
<div>
<label>$\rho_{ma}$:</label>
<input type ="text" name="input" id="input" onkeyup="calculatePEFormula()"/>
</div>
<div>
<label>Result:</label>
<input type="text" id="result" name="result">
</div>
</form>
</div>
THE JS:
function PEFormula(result, formulaName){
this.result = result;
this.formulaName = formulaName;
}
function calculatePEFormula(){
var PEObject = new PEFormula($("#result"), $("#formulaName"));
var formulaName = $("#formulaName").val();
switch(formulaName){
case "porosityRhob" : PEObject.porosityRhoB();
break;
case "porosityPhi" : PEObject.porosityPhi();
break;
}
PEFormula.prototype.porosityPhi = function(){
var input = parseFloat($("#input").val());
//logic
return r;
}
The HTML attribute id is supposed to be unique
<div id="formula">
<form id="formula" name="formula">
<input type="hidden" id="formulaName" name="formulaName" value="porosityRhob"/>
<input type ="text" name="input" id="input" onkeyup="calculatePEFormula()"/>
<input type="text" id="result" name="result">
Try changing these ids instead use classes
Here is the solution change all field ids to class and form id should be different and pass parameter id of form as parameter onkeyup="calculatePEFormula('form#formula1')" and onkeyup="calculatePEFormula('form#formula2')" Now in js
function PEFormula(result, formulaName){
this.result = result;
this.formulaName = formulaName;
}
function calculatePEFormula(form_id){
var PEObject = new PEFormula($(form_id+" .result"), $(form_id+" .formulaName"));
var formulaName = $(form_id+" .formulaName").val();
switch(formulaName){
case "porosityRhob" : PEObject.porosityRhoB();
break;
case "porosityPhi" : PEObject.porosityPhi();
break;
}
PEFormula.prototype.porosityPhi = function(){
var input = parseFloat($(form_id+" .input").val()); //provide the form id here
//logic
return r;
}
You're using ID's when you should be using classes.
You need to avoid assigning the same id attribute to multiple elements. An element's ID should be unique.
Never use the same id for multiple elements. That's a basic concept in HTML. An identification should be unique and identical. So there cannot be any duplicated IDs inside any HTML page. So please change the ids of 2nd form,
<div id="formula2">
<p>To find Φ:</p>
<form id="formula2" name="formula">
<input type="hidden" id="formulaName2" name="formulaName" value="porosityPhi"/>
<div>
<label>$\rho_{ma}$:</label>
<input type ="text" name="input" id="input2" onkeyup="calculatePEFormula()"/>
</div>
<div>
<label>Result:</label>
<input type="text" id="result2" name="result">
</div>
</form>
</div>
Change the IDs accordingly when calling the same js function.
I have renamed all the IDs by adding 2 at the end of each ID. Make every ID unique.
I am trying to dynamically add fields with jquery for a project. My problem is that when I send the form to the processing script and do a print_r() on the $_POST['item'] it only lists the last array...
Here is my code:
<div class="itemAdd row">
<div class="span4">
<p>Item Number: <br /><input class="span4" type="text" name="item[itemNumber]" /></p>
<p>Status: <br />
<select name="item[status]" class="span4">
<option value="enabled" selected="selected">Enabled</option>
<option value="disabled">Disabled</option>
<option value="damaged">Damaged</option>
</select>
</p>
</div>
<div class="span4">
<p>Item Notes:<br /><textarea class="span4" style="height:100px;" name="item[notes]"></textarea></p>
</div>
<div class="clearfix"></div>
<hr />
</div>
This button adds new fields:
<i class="icon-plus icon-white"></i> Add Item
Here is the jquery to add new fields:
<script>
//Add Items
$('a#addItem').on('click', function(event) {
event.preventDefault();
$('#productItems').append('<div class="itemAdd row"><div class="span4"><p>Item Number: <br /><input class="span4" type="text" name="item[itemNumber]" /></p><p>Status: <br /><select name="item[status]" class="span4"><option value="enabled" selected="selected">Enabled</option><option value="disabled">Disabled</option><option value="damaged">Damaged</option></select></p></div><div class="span4"><p>Item Notes:<br /><textarea class="span4" style="height:100px;" name="item[notes]"></textarea></p></div><div class="clearfix"></div><hr /></div>');
});
You are using arrays in your html, but the index is a string:
item[itemNumber]
So every item will overwrite the previous one.
You could change it to:
itemNumber[]
and
itemNote[]
or, if you have a numeric ID, you could use that.
You're forcing array keys in your form fields, et.c.:
... name="item[itemNumber]" ...
itemNumber isn't a JS var, it's literal html/attribute text in the html blob you're appending. Perhaps you meant something more like
... name="item[' + itemNumber + ']" ...
instead. Even just item[] would allow PHP to assign array keys for you automatically. But as it stands now, PHP will create an array for you, but since all your fields are using the SAME key names, you'll be continually overwriting values and end up with only the last field name/key-pair in the form.
I'm trying to create an integer update form field for my cart system. On the page, I already have a + and - function to increase and decrease the quantity by 1. How could I include an integer form field next to the (+) and (-) to udpate by a certain result and then send this to the cart page. Thank you very much for any help.
This is the main part of the code that is enclosed within PHP (I left out the information before the first a href link because it isn't important)
(+)
(-)
I'm not quite sure if i really get your question right, but i think you want to change an input field in a chart.
i think you should solve that problem with JavaScript instead of PHP, because you have to reload the page on every Click.
in jQuery it would like that:
$(".increase").each(function() {
$(this).click(function() {
var ipt = $("#" + $(this).attr("data-what"));
ipt.val(parseInt(ipt.val()) + 1);
});
});
$(".decrease").each(function() {
$(this).click(function() {
var ipt = $("#" + $(this).attr("data-what"));
ipt.val(parseInt(ipt.val()) - 1);
if(parseInt(ipt.val()) < 0) {
ipt.val(0);
}
});
});
and the html is:
<div class="item">Item 1 <input type="text" id="item1" value="1" size="2"> (+1 | -1)</div>
<div class="item">Item 2 <input type="text" id="item2" value="1" size="2"> (+1 | -1)</div>
<div class="item">Item 3 <input type="text" id="item3" value="1" size="2"> (+1 | -1)</div>
see http://jsfiddle.net/axYfq/4/
and with the submit button you get the right quantity :)
You'll have to post a form to cart.php:
<form action="cart.php" method="post">
<input type="text" name="qty"/>
<input type="submit" name="submit_increase" value="(+)"/>
</form>
<form action="cart.php" method="post">
<input type="text" name="qty"/>
<input type="submit" name="submit_remove" value="(-)"/>
</form>
And in your cart.php, you can use if (isset($_POST['submit_increase'])) to determine if you're increasing or decreasing, then $_POST['qty'] to grab the number of items to add/remove.
This isn't the only solution. You could use one form, hidden inputs, or javascript to build a query string. Its up to you.
You could use javascript getelementbyID to do this.
First, you will need a form field with an appropriate ID:
<input type="text" name="quantity" id="NumberOfItems" />
Then put a span around the (+) and (-) to call a JS function:
<span onclick="IncrementNumber()">(+)</span>
<span onclick="DecrementNumber()">(-)</span>
Then you can use getelementbyID to change the value when they click a button:
function IncrementNumber()
{
document.getElementById("NumberOfItems").value-=-1; // Messy, but works
}
function DecrementNumber()
{
document.getElementById("NumberOfItems").value-=1;
}
I believe you need to use a form here. Try doing:
<form action="#" method="POST">
<input type="hidden" name="user_action" value="increase">
<input type="submit" value="increase">
</form>
<form action="#" method="POST">
<input type="hidden" name="user_action" value="decrease">
<input type="submit" value="decrease">
</form>
This way you will output two buttons, and when the user clicks on each one, you will get their action from the $_POST variable. So then you could do something like:
<?php
if(isset($_POST['increase'])){
$number_of_items += 1;
}
if(isset($_POST['decrease'])){
$number_of_items -= 1;
}
?>
<p>You have ordered <?php echo $number_of_items; ?> items</p>