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.
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)
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']);
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 have three sets of form fields that are shown and hidden by jQuery and a Select list.
They are displaying just like I want them. But now the information that was being passed to the php code from the first two sets is being lost and if the bottom set of three fields are the set used. The information is passed no problem.
Is this a case of similarly named items lower in the page erasing the information of items in the upper part of the pages?
How do I get around this?
<ul id="options">
<li>
<h2>Your guest names</h2>
<label for="GuestName">Guest:</label> <input type="text" style="width:180px;" name="GuestName" id="GuestName" /><br/>
</li>
<li>
<h2>Your guest names</h2>
<label for="GuestName">Guest:</label> <input type="text" style="width:180px;" name="GuestName" id="GuestName" /><br/>
<label for="GuestName2">Guest 2:</label> <input type="text" style="width:180px;" name="GuestName2" id="GuestName2" /><br/>
</li>
<li>
<h2>Your guest names</h2>
<label for="GuestName">Guest:</label> <input type="text" style="width:180px;" name="GuestName" id="GuestName" /><br/>
<label for="GuestName2">Guest 2:</label> <input type="text" style="width:180px;" name="GuestName2" id="GuestName2" /><br/>
<label for="GuestName3">Guest 3:</label> <input type="text" style="width:180px;" name="GuestName3" id="GuestName3" /><br/>
</li>
</ul>
<script>
$("li").hide();
$("#numberattending").change(function() {
var index = $(this).children(":selected").index();
$("#options").children().hide().eq(index).show();
});
</script>
When you hide those fields, try also disabling them. This will prevent them from being submitted with the form. You'll, of course, have to re-enable them when you show them.
Try these changes (your code commmented, replace with new code):
// $("#options").children().hide().eq(index).show();
$("#options").children().hide().find('input').prop('disabled', true);
$("#options").children().eq(index).show().find('input').prop('disabled', false);
A better way might be to make jQuery fire a 'hide' event when you call hide() and disable the inputs when that happens (and similar for show()):
// taken from http://stackoverflow.com/a/2857952/259457
var _oldhide = $.fn.hide;
$.fn.hide = function(speed, callback) {
$(this).trigger('hide');
return _oldhide.apply(this,arguments);
}
$('#options li').on('hide', function() {
$(this).find('input').prop('disabled', true);
});
Then you can keep your code the rest of your code the same, and the fields will be disabled/enabled automatically when you call show() or hide() on the li tags.
Is this a case of similarly named items lower in the page erasing the information of items in the upper part of the pages?
yes it is.. when the form is posted.. the fields in the form is posted by its name , in your case three inputs have the same name so it is replacing and only one is getting posted... one way is to give it a unique name..
or disableing all other field except the one ,so that it is not posted ..
try this
$("#numberattending").change(function() {
var index = $(this).children(":selected").index();
$("#options").find('input').prop('disabled',true);
$("#options").children().hide().eq(index).show().find('input').prop('disabled',false);
});
This is stupidly simple, but I can't figure out why I constantly get the error msg here, it looks right and works right in other applications....is this due to the "0" zeros? It shouldn't be because it's returning the error before it gets to any of the other stuff, pls help! been staring at this so long Im getting to that "can't see the forest from the trees" point.
PHP
<?php
if(empty($_POST['Contact0FirstName']) || empty($_POST['Contact0LastName']) ||
empty($_POST['Contact0Email']) || empty($_POST['Contact0Phone1']) ||
empty($_POST['CaptchaInput']) || !empty($_POST['LeadBlind'])) {
echo "Please fill out all fields marked *";
die();
} else {
//curl stuff
}
?>
and the form
<form id="Lead" method="post" action="PHP/Lead.php" accept-charset="UTF-8">
<ul id="LeadForm">
<li>*required field</li>
<li>
<input type="hidden" name="LeadBlind" id="LeadBlind">
<label for="Contact0FirstName">1| First Name*</label>
<label for="Contact0LastName">2 | Last Name*</label>
<label for="Contact0Email">3 | Email*</label>
</li>
<li>
<input type="text" name="Contact0FirstName" id="Contact0FirstName">
<input type="text" name="Contact0LastName" id="Contact0LastName">
<input type="text" name="Contact0Email" id="Contact0Email">
</li>
<li>
<label for="Contact0Phone1">4| Daytime Phone*</label>
<label for="Contact0Phone2">5| Evening Phone</label>
<label for="CaptchaInput">6| Please enter the code</label>
</li>
<li>
<input type="text" name="Contact0Phone1" id="Contact0Phone1">
<input type="text" name="Contact0Phone2" id="Contact0Phone2">
<input type="text" class="numbers" name="Captcha" id="Captcha" value="" readonly>
<input type="text" class="numbers" name="CaptchaInput" id="CaptchaInput" size="6" maxlength="6">
</li>
<li>
<input type="submit" id="LeadSend" value="Try It Now!">
<span id="processing">Submitting Your Request</span>
</li>
<li class="text">You will get 30 days of NinjaTrader + Rithmic (the data feed) to experience how trading should really be.</li>
<li class="text">Email Support or call 800 771 6748 (Optimus Trading Group)</li>
</ul>
<div class="clear"></div>
</form>
In firebug, it shows the fields getting passed, with a value, but I get the "Please fill out all fields marked *" error returned.
!empty($_POST['LeadBlind'])
nothing else leads to the problem
try making it to check if its empty
else try removing fields one by one to see where exactly is the problem
otherwise
add var_dump($_POST); after <?php tag
Between here:
<?php
if(empty($_POST['Contact0FirstName']) ...
Please put a
print_r($_POST);
And make sure all the keys you're accessing the data from are correct and populated.
IE:
<?php
print_r($_POST);
if(empty($_POST['Contact0FirstName']) ...
!empty($_POST['LeadBlind']
This field can only be empty, because it's hidden and you didn't assigned a value to it.
Also, this is very poor HTML (Tags should be closed) and I would use the isset()-function on every $_POST-field that is been set in your Form. Because if a field has no value and the form is being send, there is no entry in the $_POST-Array in the first place.