Jquery Time Picker On Multiple Input Fields - php

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.

Related

jQuery classname validation not working for dynamically generated text fields

I am facing a problem with jQuery Validation to validate the ajax (dynamically) generated text fields...
Here is the snippet of the HTML code
<form name="booking" id="booking" method="post" action="">
<ul>
<li>
<span>Mobile Number</span>
</li>
<li>
<input type="tel" name="mobile" id="mobile" class='form_mobile'/>
</li>
<li>
<span>Number of male tickets</span>
</li>
<li>
<select name="male_qunatity" id="male_qunatity" >
</select>
</li>
</ul>
</form>
Jquery validation script is here
$(document).ready(function(){
Here is the ajax call starts
$('#male_qunatity').change(function() {
var male_tickets = $(this).val();
var mobile = $('#mobile').val();
var path = '<?php echo site_url() ?>';
ajaxurl = path + '/wp-admin/admin-ajax.php';
var data = {
action: 'get_quantity',
qty: male_tickets,
mobile: mobile
};
$.post(ajaxurl, data, function(response) {
$('#m_attendees').html(response);
});
}); //END dropdown change event
$("#booking").validate({
});
$('.form_mobile').each(function() {
$(this).rules('add', {
required:true,
number:true,
messages: {
required:"Please enter a mobile number",
number:"Only numbers allowed"
}
});
});
});//validation ends
Here is the ajax code to text-boxes based on the count selected
$quantity= $_REQUEST['qty'];
$mobile= $_REQUEST['mobile'];
$pass = "<table>";
for($i =0; $i<$quantity; $i++ ){
$pass .= "<tr>
<td>
<input type='text' id='mobile-".$i."' class='form_mobile' name='mmobile[]'>
</td>
</tr>";
}
$pass .= "</table>";
echo $pass;
FYI: The form validation is working fine for the form fields, except the dynamically created fields..
How to solve this one?
Any suggestions would be greatly appreciated..
1) Since jQuery Validate depends on the name attribute, you'll need to alter your PHP to ensure that every name is unique. Note the index, $i, added to the name attribute...
"... <input type=text id='mobile-".$i."' name='mmobile[".$i."]' class='form_mobile'> ..."
(you're also missing quotes around text; should be type='text')
2) When creating fields dynamically, you would call .rules('add') AFTER the fields are dynamically created. In your case, here...
$.post(ajaxurl, data, function(response) {
$('#m_attendees').html(response); // <- create the new fields
$('.form_mobile').each(function() { // <- then dynamically add the rules
$(this).rules('add', {
required:true,
number:true,
messages: {
required:"Please enter a mobile number",
number:"Only numbers allowed"
}
});
});
});
3) .validate() is the initialization method for the plugin on your form. Just call it once when the DOM loads. (.validate() does not get called repeatedly when the form is validated, because validation is automatic once the plugin is properly initialized.)
$(document).ready(function() { // <- DOM is ready
$("#booking").validate({ // <- initialize plugin on your form
// your options // <- plugin options
});
});

HTML element in JQuery

I am using JQuery autocomplete option to get values from database using PHP. I have 2 text boxes and I am trying to use same PHP file to get the required results.
My HTML code is
<tr>
<td>LOB</td>
<td><input autocomplete="off" type="text" name="ABC" class="autocomplete"/></td>
</tr>
<tr>
<td>Project Name</td>
<td><input autocomplete="off" type="text" name="PQR" class="autocomplete"/></td>
</tr>
and my JQuery is
$(document).ready(function() {
$( ".autocomplete" ).autocomplete({
source: 'LiveSearch.php?name='+ $(".autocomplete").attr('name') + '&',
minLength: 2
});
});
But as these there are 2 elements with same class. I am not getting correct arrr('name'). MySQL will differ based on this name. I tried (this) but still not getting the result.
If I am in the first text box then name should be of that text box etc..
Please let me know if I am missing anything.
You can target the textbox using name.
$('[name=ABC]').val()
Use id to differentiate
<tr>
<td>LOB</td>
<td><input autocomplete="off" type="text" name="ABC" id="id1" class="autocomplete"/></td>
</tr>
<tr>
<td>Project Name</td>
<td><input autocomplete="off" type="text" name="PQR" id="id2" class="autocomplete"/></td>
</tr>
//Script
$(document).ready(function() {
$( ".autocomplete" ).autocomplete({
source: 'LiveSearch.php?name='+ $("#id1").attr('name') + '&',
minLength: 2
});
});
You're mixing the scope of 'all autocompletes' and 'the current automplete'. One way of dealing with this is to use jQuery's each() method:
$('.various-things').each(function () {
console.log($(this).attr('something');
});
This would log the 'something' attribute of each .various-things on the page. It looks like what you'd need is:
$(document).ready(function() {
$( ".autocomplete" ).each(function () {
$(this).autocomplete({
source: 'LiveSearch.php?name='+ $(this).attr('name') + '&',
minLength: 2
});
});
});
Now it'll find all autocompletes and set them up using their own name.

Multiple text boxes for AJAX auto complete and name check

I'm trying to create a text box that will search a mysql database, provide auto completed text below the text box and then show a confirmation tick or cross to show that the name is already in the database (or not).
I've got it to work with just one text box, but I'd like to add multiple text-boxes on the same page. eg so someone can search for 10 different names, have them all auto completed and then shown with either a green tick or red cross to confirm that they are in the database.
I'm new at this so apologies if it is something obvious that I'm doing wrong!
Thanks in advance.
This is the javascript:
<script type="text/javascript">
function check_username(){
var username = $("#username").val();
if(username.length > 2){
$.post("username.php", {
username: $('#username').val(),
}, function(response){
$('#Info').fadeOut();
setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
});
return false;
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(1000);
}
$(function() {
$( "#username" ).autocomplete(
{
source:'source.php' })
});
</script>
This the the html textfield:
<td><input type="text" id="username" type="text" onblur="return check_username();"/></td>
<td><div id="Info"></div></td>
<td><input type="text" id="username2" type="text" onblur="return check_username2();"/></td>
<td><div id="Info"></div></td>
try:
$( "input#username,input#username2" ).autocomplete(
instead of
$( "#username" ).autocomplete(

How do you calculate total cost with input fields using jQuery?

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.

Jquery Date Picker On Multiple Input Fields

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);
}
});

Categories