I've been searching online for a solution to my problem but no luck yet. I'm hoping someone will be able to get me past this obstacle I've hit or point me in the right direction.
I'm creating an online registration form for players. So far, when I select a birth date using jquery's datepicker, it will return the correct age of the user based on the specific date I've set. I'm using a switch statement to display the correct division name and price value on the webpage based on the age selected.
All seems to work correctly up to this point.
My problem now is that I cannot seem to target the value of each price in order to create a function that adds up each price for a grand total.
HTML portion taken from my php file:
<div>
<div>
<label for="player-birthdate-1">Birthdate</label>
<input type="text" class="default-input" id="datepicker1" value="">
</div>
<div>
<label for="player-division-1">Division</label>
<input type="text" id="playerDivision1" value="" disabled>
</div>
<div>
<p id="playerFee1" class="fee" value=""></p>
</div>
</div>
<div>
<div>
<label for="player-birthdate-2">Birthdate</label>
<input type="text" class="default-input" id="datepicker2" value="">
</div>
<div>
<label for="player-division-2">Division</label>
<input type="text" id="playerDivision2" value="" disabled>
</div>
<div>
<p id="playerFee2" class="fee" value=""></p>
</div>
</div>
<div>
<p id="total" value=""></p>
</div>
Portion taken from my php file where I'm grabbing the division name and price from the database:
<script>
var divisions = {
<?php
$sql = $db->prepare("SELECT * FROM division");
$sql->execute();
$results = $sql->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $division) :
?>
'<?php echo $division->division_id; ?>' : {
id : '<?php echo $division->division_id;?>'
,name : '<?php echo $division->division_name;?>'
,price : '<?php echo $division->division_price;?>'
},
<?php endforeach; ?>
}
</script>
Datepicker and Total Fee code taken from my js file:
$(document).ready(function() {
$( '#datepicker1' ).datepicker({
onSelect: function(value, ui) {
var newDate = new Date("April 30, " + (new Date()).getFullYear()),
dob = $("#datepicker1").datepicker("getDate"),
age = new Date(newDate - dob).getFullYear() - 1970;
$('#age').val(age);
console.log(age);
switch (age){
case 5:
case 6:
$("#playerDivision1").val(divisions['1'].name);
$("#playerFee1").html(divisions['1'].price);
break;
case 7:
case 8:
$("#playerDivision1").val(divisions['2'].name);
$("#playerFee1").html(divisions['2'].price);
break;
//continues on for the remaining of the ages.....
},
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: '1990:2012'
});
$( '#datepicker2' ).datepicker({
onSelect: function(value, ui) {
var newDate = new Date("April 30, " + (new Date()).getFullYear()),
dob = $("#datepicker1").datepicker("getDate"),
age = new Date(newDate - dob).getFullYear() - 1970;
$('#age').val(age);
console.log(age);
switch (age){
case 5:
case 6:
$("#playerDivision2").val(divisions['1'].name);
$("#playerFee2").html(divisions['1'].price);
break;
case 7:
case 8:
$("#playerDivision2").val(divisions['2'].name);
$("#playerFee2").html(divisions['2'].price);
break;
//continues on for the remaining of the ages.....
},
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: '1990:2012'
});
$('.fee').html(function(){
var total = 0;
$('.fee').each(function(){
var fee = parseFloat($(this).val());
if (isNaN(fee)) {fee = 0;}
total+= fee;
$('#total').html('$' + total);
});
});
});
I look forward to advice from those on the forum. Any help or push in the right direction is greatly appreciated! :)
You've done a nice job and made it easy by giving each one a class of "fee" already, but I assume you want to parseFloat the number, not parseInt (in case there's cents in the fee?).
Also, you need to check if it's isNaN (not a number), otherwise it won't work properly.
That's a simple matter of adding:
if (isNaN(fee)) {fee = 0;}
Finally, it appears that you're doing it on the "change" event. I've had better luck with the keyup event.
I think what's happening is the line (and it's code):
$('.fee').html(function(){
is never actually being called or it's not being called at the right time.
My suggestion would be to wrap the contents of the .fee stuff in a function. Then call that function in the date picker's select callback. (Probably right before every break; statement.) This way the total would be recalculated every time the date changes.
Your function would look something like this:
function calcFee () {
var total = 0;
$('.fee').each(function () {
...
});
}
If you are doing the calculations inside the jQuery each() function loop then you can use the jQuery $(this).val() to grab the value inside each box. Then you can create a cumulative total.
Related
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.
If I press the enter key after giving the text box value like 03/20/2014 the result will appear. But if I give the value using date picker that doesn't work.
<input class="search-query" id="date" onkeypress="if(event.keyCode==13){return true;}" type="text" name="date" value="" placeholder="mm/dd/yyyy">
<script>
$(function() {
$( "#date" ).datepicker();
});
</script>
if you want to get the date when the user selects it, you can do something like this:
$ ("#datepicker").datepicker (
{
onSelect: function ()
{
var date = $(this).datepicker('getDate');
}
});
EDIT:
I have 400 'inputs' on a page using the same class:
.oDiv
Is there a way to show on the page the nth position of that class (i.e its index) - so whether its the 1st, 2nd, 40th, 100th etc,
I have a series of classes on a page:
.oDiv
There are over 400 of these on the page - what I am doing is using:
$( '.oDiv:eq(6)' ).remove();
to remove some of these depending on a users selection.
What would help me in terms of coding, is to able to see on the .HTML page the number of each of the class - for error checking and debugging.
Example:
<input type="checkbox" class="oDiv" id="Mat" name="spec[]" value="Mat 6"/>
<input type="checkbox" class="oDiv" id="Neo" name="spec[]" value="Neo 7"/>
<input type="checkbox" class="oDiv" id="Prey" name="spec[]" value="Prey 8"/>
Where 6 7 and 8 in the value shows they are the 6th, 7th and 8th in the list of oDiv classes.
Does that make sense and is this possible?
You can show onDocument load,
$.each($(".oDiv"), function() {
$("#debug").append($(this).val() );
})
where we can have a
<div id="debug"></div>
to display the values of all your checkboxes. For any removal of the checkboxes, just rerun the code to update the div.
You are looking for .index(selector)
Try this, I assume that you want to see its index when clicking.
$('.oDiv').click(function(){
alert($('.oDiv').index(this));
});
Please read this to know more about .index()
If the number is always the last character then use this:
$('input:checkbox').on('change', function(e) {
var num = $(this).val().substr(-1);
console.log(num);
});
Alternatively you can use .index to get the position:
$('input:checkbox').on('change', function(e) {
var num = $('input:checkbox').index($(this));
console.log(num);
});
Note that .index starts from 0, so the first item found will be 0, the second 1 etc.
$(function() {
$('input:checkbox').each(function(i, e)) {
var num = $('input:checkbox').index($(this));
console.log($(this).val() + " is in position " + num);
});
});
This might help:
<input type="checkbox" class="oDiv" id="Mat" name="spec[]" value="Mat 6"/>
<input type="checkbox" class="oDiv" id="Neo" name="spec[]" value="Neo 7"/>
<input type="checkbox" class="oDiv" id="Prey" name="spec[]" value="Prey 8"/>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.oDiv').each(function(index, element) {
// index is a numerical increment of each element.
// element is a javascript object of the "this" element.
jQuery(element).after(jQuery(element).val() + '<br />');
jQuery(element).on('change', function() {
jQuery(this).remove();
});
});
});
</script>
I am using timepicker from this website
In my page there are multiple fields like from time to time. I am creating dynamic names and ids for this.
PHP code:
<?php
$i=1;
foreach($locations as $location)
{
?>
<tr>
<td><?php echo $location['name'];?>
</td>
<td>
<input type="text" name="txtFromDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtFromDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtToDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtToDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtFromTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;" />
</td>
<td>
<input type="text" name="txtToTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;"/>
</td>
</tr>
<?php
$i++;
}
?>
Jquery Code:
<script type="text/javascript">
$(document).ready(function(){
var count=0;
count=<?php echo count($locations);?>;
for(i=1;i<=count;i++)
{
(function(i) {
$('#txtFromDate_'+i+', #txtToDate_'+i).datepicker({
defaultDate: new Date(),
changeMonth: true,
changeYear: true,
dateFormat: 'dd-mm-yy',
onSelect: function(selectedDate) {
var option, otherPicker;
if (this.id == "txtFromDate_"+i) {
otherPicker = $("#txtToDate_"+i);
option = "minDate";
} else {
otherPicker = $("#txtFromDate_"+i);
option = "maxDate";
}
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
otherPicker.datepicker("option", option, date);
}
});
})(i);
}
$('.time-pick').timepicker({});
$("#frmSubmitArtwork").validate({
errorClass: 'jqueryError',
validClass: 'jqueryValid',
errorElement: 'label',
success: 'jqueryValid',
messages: {
txtTitle: {
required: 'Please enter title'
},
cmbType: {
required: 'Please choose type',
},
txtDescription: {
required: 'Please enter description'
}
}
});
});
</script>
I want that to time should always be greater than from time just like what i did for fromdate and todate fields. There was example of fromdate and todate validation in datepicker documentation but i have read the timepicker documentation but i am unable to figure out how to accomplish this?
Good news.
The author of timepicker has updated the code (to version 0.2.5) and examples at plugin homepage with something you are looking for: "Two timepickers to select chronological time range". Check it here.
If I have understood correctly your scenario is like this:
The user fills the fromTime field
When he fills the toTime field you want a validation.
A solution could be this:
Just put some event on that field, something like onfocusout (don't know..) check it out. Find what event is best that triggers when the user has left the toTime box.
On this event put a function that compares the value entered to the one found in the fromTime field. Its a trivial date compare!
Hope this is what you're asking for. And an other tip, if there is such thing already implemented for the date fields, just see how is this done there.
I have a page in which there are multiple input fields that is fromdate and todate. I have created dynamic ids and name. I have used jquery date picker.
Code:
<?php
$i=1;
foreach($locations as $location)
{
?>
<tr>
<td><?php echo $location['name'];?></td>
<td>
<input type="text" name="txtFromDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtFromDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtToDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtToDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtFromTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;" />
</td>
<td>
<input type="text" name="txtToTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;"/>
</td>
</tr>
<?php
$i++;
}
?>
Jquery code For Date Picker:
(document).ready(function(){
var count=0;
count=<?php echo count($locations);?>;
for(i=1;i<=count;i++)
{
var dates = $('#txtFromDate_'+i+', #txtToDate_'+i).datepicker({
defaultDate: new Date(),
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
onSelect: function(selectedDate) {
var option = this.id == "txtFromDate_"+i ? "maxDate" : "minDate";
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
}
Jquery Date Picker is displayed for fromdate and to date fields. In the above code i have applied the from date to date validation i.e. to date should be greater than from date.
The problem with above code is that this validation is applied on the last row only.
I want that this validation should be applied to all the rows.
You redeclare the dates variable at every iteration of the loop. So when the loop is done, the dates variable that you're using in the onSelect handler is equal to last item that was set in the loop.
Update Try this code:
Update2 One more thing is the issue of variable i. Its current value is available while in the loop, so later on, when the onSelect handler is used, the i has a value as in last iteration. To overcome this, you have to put i in a context of another function, that's why I have wrapped code in the body of the loop in another function to which I'm passing i variable.
Update3 And one more thing - the logic for picking the option (minDate or maxDate) had to be reversed.
$(document).ready(function(){
var count=0;
count=<?php echo count($locations);?>;
for(i=1;i<=count;i++)
{
(function(i) {
$('#txtFromDate_'+i+', #txtToDate_'+i).datepicker({
defaultDate: new Date(),
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
onSelect: function(selectedDate) {
var option, otherPicker;
if (this.id == "txtFromDate_"+i) {
otherPicker = $("#txtToDate_"+i);
option = "minDate";
} else {
otherPicker = $("#txtFromDate_"+i);
option = "maxDate";
}
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
otherPicker.datepicker("option", option, date);
}
};
})(i);
}
});