JQuery Multiple datepickers from and to booking form - jquery-ui

Hi I found the following code from this page JQuery UI DatePicker using 2 date fields trying to get date difference
However I don't understand the datepicker ui enough to be able to stop the first datepicker from letting you only select from todays date. Im sure its simple but can someone please help!
<script type="text/javascript">
var DatePicked = function() {
var departure = $("#CheckIn");
var arrival = $("#CheckOut");
var nights = $("#Nights");
var triggeringElement = $(this);
var minArrivalDate = new Date();
var departureDate = departure.datepicker("getDate");
if (departureDate != null) {
minArrivalDate.setDate(departureDate.getDate() + 1);
} else {
minArrivalDate.setDate(minArrivalDate.getDate() + 1);
}
arrival.datepicker('option', 'minDate', minArrivalDate);
var arrivalDate = arrival.datepicker("getDate");
if (departureDate != null && arrivalDate != null && triggeringElement.attr("id") != "Nights") {
var oneDay = 1000*60*60*24;
var difference = Math.ceil((arrivalDate.getTime() - departureDate.getTime()) / oneDay);
nights.val(difference);
} else if (departureDate != null && triggeringElement.attr("id") == "Nights") {
var nightsEntered = parseInt(nights.val());
if (nightsEntered >= 1) {
var newArrivalDate = new Date();
newArrivalDate.setDate(departureDate.getDate() + nightsEntered);
arrival.datepicker("setDate", newArrivalDate);
} else {
alert("Nights must be greater than 1.");
}
}
}
$(function() {
$("#CheckIn, #CheckOut").datepicker({
onSelect: DatePicked
});
$("#Nights").change(DatePicked);
DatePicked();
});
</script>
Form:
<form class="enquiry" action="assets/scripts/booking.php" method="get" name="Booking">
<div class="Widget_Form_Spacer">
<label for="CheckIn">Check-In</label>
<input id="CheckIn" name="CheckIn" type="text" class="tF bL" value="<?php echo date("m/d/Y"); ?>" />
</div>
<div class="Widget_Form_Spacer Right">
<label for="CheckOut">Check-Out</label>
<input id="CheckOut" name="CheckOut" type="text" class="tF bL" value="" />
</div>
<div class="Widget_Form_Spacer Short">
<label for="Nights">Nights</label>
<input id="Nights" name="Nights" type="text" class="tF nL" value="1" onclick="clickclear(this, '1')" onblur="clickrecall(this,'1')" />
</div>
<div class="Widget_Form_Spacer Short">
<label for="Adults">Adults</label>
<input name="Adults" type="text" class="tF nL" value="1" onclick="clickclear(this, '1')" onblur="clickrecall(this,'1')" />
</div>
<div class="Widget_Form_Spacer Long">
<input name="Check" type="submit" value="Check Availability" />
</div>
</form>

You can use the minDate jquery UI datepicker option:
$("#date").datepicker({ minDate: new Date() });
Live DEMO

Related

MVC Validation checkbox

I am trying to make sure that at least one 'input checkbox is checked in this list there is about 10 items but I am not sure how to do this? Do I need a flag in the model?
<div>* Data</div>
#Html.ValidationMessageFor(x => x.flgData,"", new { #class = "text-danger" })
<ul>
#foreach (var item in Model.ListOfData)
{
<li>
<input type="checkbox" value="#item.Value" name="chk" />
<label asp-for="#item.Selected">#Html.Raw(#item.Name)</label>
<input type="hidden" asp-for="#item.DictionaryId" />
<input type="hidden" asp-for="#item.Name" />
</li>
}
</ul>
You could loop though all the checkbox and check if it is checked
HTML
<input type="button" id="btnSubmitCB" value="Submit" class="btn btn-primary" />
<input type="checkbox" class="chkbox" value="Bike" /> Bike
<input type="checkbox" class="chkbox" value="Car" /> Car
<input type="checkbox" class="chkbox" value="Boat" /> Boat
JQuery
$(document).ready(function () {
$('#btnSubmitCB').click(function () {
var cbChecked = false;
$('input[type=checkbox]').each(function () {
if (this.checked) {
cbChecked = true;
return false;
}
});
if (cbChecked) {
alert("At least one checkbox is checked");
}
else {
alert("No checkbox is checked");
}
});
});
Another way without using .each function
$(document).ready(function () {
$('#btnSubmitCB').bind("click", function () {
let checkedCount = $('input[type=checkbox]:checked').length;
if (checkedCount == 0) {
alert("no checkbox has been checked")
}
else {
alert("checkbox has been checked");
}
});
});

Listview not refreshing after reload the page and cannot be removed from listview after deleting the list in jquery mobile

Hello I am attending the create and retrieve the data using HTML 5 Web sql Database.Its functionality working correctly i expected.
When i showing the results in next page in list view it showing correctly but when i refresh the page list view not showing only go to previous page then come this page its working and also i added a delete button in list view when i click the delete button records are deleted.but the list not remove from the list view only go to previous then come this page only removed. How to fix this.
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Clientside Database</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile- 1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<div data-role=page id="home">
<div data-role=header>
<h1>ClientSide Database</h1>
</div>
<div data-role="content">
<ul data-role="listview" data-inset="true">
<li data-role="fieldcontain">
<label for="firstname">FirstName:</label>
<input type="text" name="firstname" id="firstname" value="" class="required" />
</li>
<li data-role="fieldcontain">
<label for="lastname">LastName:</label>
<input type="text" name="lastname" id="lastname" value="" class="required" />
</li>
<li data-role="fieldcontain">
<label for="email">Email:</label>
<input type="email" name="email" id="email" value="" class="required" />
</li>
<li data-role="fieldcontain">
<label for="date">Date of Birth:</label>
<input type="date" name="date" id="date" value="" class="required" />
</li>
<li >
<input value = "SUBMIT" type = "button" name="submit" id="submit" />
<input type="button" value="view" id="view"/>
</li>
</ul>
</div><!-- /content -->
</div>
<div data-role="page" id="dataview" data-add-back-btn=true>
<div data-role="header">
<h1>List of customers</h1>
</div>
<div data-role="content">
</div>
</div>
</body>
</html>
<script type="text/javascript">
var db = openDatabase("MyDatabase","1.0","My ClientSide Database",1000000);
$("#submit").bind('click',function(e){
db.transaction(function(transaction){
var sql = "CREATE TABLE IF NOT EXISTS clientrecords " +
" (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"fname VARCHAR(100) NOT NULL, " +
"lname VARCHAR(100) NOT NULL," +
"email VARCHAR(100) NOT NULL ," +
"date VARCHAR(100) NOT NULL)"
transaction.executeSql (sql, undefined, function ()
{
console.log("Table Created Successfully");
}, error);
});
var lname = $("#firstname").val ();
var fname = $("#lastname").val ();
var email =$("#email").val();
var date =$("#date").val();
db.transaction (function (transaction)
{
var sql = "INSERT INTO clientrecords (lname, fname,email,date) VALUES (?, ?, ?, ?)";
transaction.executeSql (sql, [lname, fname,email,date], function ()
{
console.log("Data Inserted Successfully");
}, error);
});
});
$("#view").bind ("click", function (event)
{
db.transaction (function (transaction)
{
var sql = "SELECT * FROM clientrecords";
transaction.executeSql (sql, undefined,
function (transaction, result)
{
var html = "<ul data-icon=false data-split-icon=delete data-split-theme=d>";
if (result.rows.length)
{
for (var i = 0; i < result.rows.length; i++)
{
var row = result.rows.item (i);
var lname = row.lname;
var fname = row.fname;
var email = row.email;
var date = row.date;
var id = row.id;
html += "<li " + "id=" + id + ">";
html +='<h2>' + lname + " " + fname + '</h2><p>'+ email +'</p> <div class="ui-li-aside"><p>'+date+'</p></div> Delete';
html +='</li>';
}
}
else
{
html += "<li> No customer </li>";
}
html += "</ul>";
$("#dataview").unbind ().bind ("pagebeforeshow", function ()
{
var $content = $("#dataview div:jqmData(role=content)");
$content.html (html);
var $ul = $content.find ("ul");
$ul.listview ();
$(".delete").bind ("swiperight", function (event)
{
var listitem = $(this).parent( "li" ).attr ("id");
if (!listitem) return;
$(listitem).remove ();
db.transaction (function (transaction)
{
var sql = "DELETE FROM clientrecords WHERE id=?";
transaction.executeSql (sql, [id], function ()
{
console.log("Employee Records deleted");
}, error);
});
});
});
$.mobile.changePage ($("#dataview"));
}, error);
});
});
function ok ()
{
}
function error (transaction, err)
{
alert ("DB error : " + err.message);
return false;
}
$('#your_ul_id').listview('refresh');
Just add this to your deleting event. You don't have it.
Remember, if you append or remove something, you use the above code.
If you just want to refresh it without appending, use the following:
$('#your_ul_id').listview();

How to find the text in label-for of jQuery mobile Radio and Checkbox with knockout?

I'm using jQuery 1.9.1, jQM 1.3 & knockout 2.2.1.
My html is as follows:
<div data-role="page" id="coloursView">
<div data-role="content">
<fieldset data-role="controlgroup">
<legend>Colour:</legend>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-1" value="1" />
<label for="radio-1">Red</label>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-2" value="2" />
<label for="radio-2">Blue</label>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-3" value="3" />
<label for="radio-3">Green</label>
</fieldset>
</div><!--/content -->
</div><!--/page -->
My view model is also very simple:
function ColoursViewModel() {
this.template = "coloursView";
this.colour = ko.observable("1");
this.label = ko.observable(); // custom binding
}
Now, i would like to get the description of the selected colour, not the value.
It seems to me, that i need a custom binding, like this one:
ko.bindingHandlers.label = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$("radio", element).filter(function(el) { return $(el).text() === value; }).prop("checked", "checked");
}
};
But i'm not able to get the text of the related label - the label-for text.
Someone could help?
Thanks in advance
Update
Here is another approach where to find only :checked items and remove white-space in text.
Checkbox
$('input[type=checkbox]').each(function () {
if ($(this).is(':checked')) {
var checkbox = $(this).prev('label').text();
alert('Checkbox: ' + checkbox.replace(/\s+/g, ' '));
}
});
Radio
$('input[type=radio]').each(function () {
if ($(this).is(':checked')) {
var radio = $(this).prev('label').text();
alert('Radio: ' + radio.replace(/\s+/g, ' '));
}
});
Updated Demo
Checkbox
$('div.ui-checkbox').find('span.ui-btn-text').text();
Radio
$('div.ui-radio').find('span.ui-btn-text').text();
Sorry if i answer myself, but i think i got it. At least for radio inputs.
Now, i have a custom binding handler at fieldset level, to keep the markup clean and more readable, as i can:
<fieldset data-role="controlgroup" id="front-colours" data-bind="frontColourLabel: frontColour">
<legend>Front Colour: <span data-bind="text: frontColourDescription"></span> (Value: <span data-bind="text: frontColour"></span>)</legend>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-1" value="red" />
<label for="fc-radio-1">Red</label>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-2" value="blue" />
<label for="fc-radio-2">Blue</label>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-3" value="green" />
<label for="fc-radio-3">Green</label>
</fieldset>
this is the binding handler i come up:
ko.bindingHandlers.frontColourLabel = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.utils.unwrapObservable(valueAccessor());
var id = $('input:radio[name='+element.id+']:checked').prop("id");
var radioText = $('label[for=' + id + ']').text();
viewModel.frontColourDescription(radioText);
}
};
the only tricky part here, is that the id of the fieldset is equal to the name of the radio-group, as it's easy to filter out what radio-group i want to address.
WORKING EXAMPLE: http://jsfiddle.net/h7Bmb/1/
I try now to get the checkbox part to work. Someone can help?

jquery-ui autocomplete works locally not on heroku

I am using jquery-ui's autocomplete on two input fields of an HTML form in a Sinatra app. They work on my local machine but not on Heroku. Jquery-ui's datepicker works on this same page, so I know the jquery and jquery-ui javascript files are being loaded correctly. Also, I can see that the variable that I am using as the source for the autocomplete is actually getting populated from the database. There are no console errors as well.
Here's the HTML:
<form action="/add-event" method="post">
Date: <input id="datepicker" class="required" type="text" maxlength="50" name="date" /><br />
Headliner: <input id="headliner" class="required" type="text" maxlength="50" name="headliner" /><br />
Venue: <input id="venue" class="required" type="text" maxlength="50" name="venue_name" /><br />
</form>
There are some other fields in the form, but they don't play a part in any of this.
Here's the Jquery:
<script type="text/javascript">
var artist_names = [<%= #artist_names %>];
var venue_names = [<%= #venue_names %>];
$(document).ready(function() {
//Set button disabled
$("input[type=submit]").attr("disabled", "disabled");
var submitForm = function(date, headliner, venue) {
//If form is validated enable form
if ((date != "") && ($.inArray(headliner, artist_names) != -1) && ($.inArray(venue, venue_names) != -1))
{
$("input:submit#event").removeAttr("disabled");
}
else
{
$("input:submit#event").attr("disabled", true);
}
$('#typing').html(date+headliner + venue);
}
$("#datepicker").datepicker({
onSelect: function(dateText, inst) { submitForm(this.value, $('#headliner').val(), $('#venue').val()) }
});
$("#headliner").autocomplete({
source: artist_names,
select: function(event, ui) {
submitForm($('#datepicker').val(), ui.item.value, $('#venue').val());
$('#add-artist').empty();
}
});
$("#venue").autocomplete({
source: venue_names,
select: function(event, ui) {
submitForm($('#datepicker').val(), $('#headliner').val(), ui.item.value);
$('#add-venue').empty();
}
});
//Append a change event listener to you inputs
$('#headliner').keyup(function() {
var val = $('#headliner').val();
if ($.inArray(val, artist_names) == -1)
{
if (val=="")
{
$('#add-artist').empty();
}
else
{
$('#add-artist').html("<strong>" + val + "</strong> isn't in our database. you must first add a profile for them to add this event!<br /><form action='/add-artist-event' method='post'><br />Artist Name: <input type='text' maxlength='50' name='artist_name' value='" + val +"' /><br /> Website: <input type='text' maxlength='50' name='artist_website' /><br /> Facebook: <input type='text' maxlength='50' name='artist_facebook' /><br />Twitter: <input type='text' maxlength='50' name='artist_twitter' /><br />Soundcloud: <input type='text' maxlength='50' name='artist_soundcloud' /><br />Bandcamp: <input type='text' maxlength='50' name='artist_bandcamp' /><br /><button type='button' id='add-artist-button' onclick='addNewArtist();'>Add New Artist!</button></form><br /><br />" );
}
$("input:submit#event").attr("disabled", true);
}
else
{
$('#add-artist').empty();
submitForm($('#datepicker').val(), $('#headliner').val(), $('#venue').val());
}
});
$('#venue').keyup(function() {
var val = $('#venue').val();
if ($.inArray(val, venue_names) == -1)
{
if (val=="")
{
$('#add-venue').empty();
}
else
{
$('#add-venue').html("<strong>" + val + "</strong>" + " is not in our database. you must first add a profile for this venue to add this event!<br /><form action='/add-venue-event' method='post'><br />Venue Name: <input type='text' maxlength='50' name='venue_name' value='" + val +"'/><br />Address: <input type='text' maxlength='50' name='venue_address' /><br />City: <input type='text' maxlength='50' name='venue_city' /><br />State: <input type='text' maxlength='50' name='venue_state' /><br />Zip: <input type='text' maxlength='50' name='venue_zip' /><br />Phone: <input type='text' maxlength='50' name='venue_phone' /><br /> Website: <input type='text' maxlength='50' name='venue_website' /><br /> Facebook: <input type='text' maxlength='50' name='venue_facebook' /><br />Twitter: <input type='text' maxlength='50' name='venue_twitter' /><br /><button type='button' id='add-venue-button' onclick='addNewVenue();'>Add New Venue!</button> </form><br /><br />");
}
$("input:submit#event").attr("disabled", true);
}
else
{
$('#add-venue').empty();
submitForm($('#datepicker').val(), $('#headliner').val(), $('#venue').val());
}
});
});
var addNewArtist = function() {
$.post('/add-event/new-artist', {
artist_name: $(':input[name="artist_name"]').val(),
website: $(':input[name="artist_website"]').val(),
facebook: $(':input[name="artist_facebook"]').val(),
twitter: $(':input[name="artist_twitter"]').val(),
soundcloud: $(':input[name="artist_soundcloud"]').val(),
bandcamp: $(':input[name="artist_bandcamp"]').val()
},
function(output) {
artist_names = output.split(',');
$('#add-artist').html(output);
$('#headliner').autocomplete("option", { source: artist_names });
});
};
var addNewVenue = function() {
$.post('/add-event/new-venue', {
venue_name: $(':input[name="venue_name"]').val(),
street_address: $(':input[name="venue_address"]').val(),
city: $(':input[name="venue_city"]').val(),
state: $(':input[name="venue_state"]').val(),
zip: $(':input[name="venue_zip"]').val(),
phone: $(':input[name="venue_phone"]').val(),
email: $(':input[name="venue_email"]').val(),
website: $(':input[name="venue_website"]').val(),
facebook: $(':input[name="venue_facebook"]').val(),
twitter: $(':input[name="venue_twitter"]').val()
},
function(output) {
venue_names = output.split(',');
$('#add-venue').html(output);
$('#venue').autocomplete("option", { source: venue_names });
});
};
</script>
I was hoping to avoid including all the javascript in the question, but I think it's best that I do. The only other piece is that when I "view source" in chrome I see the two variables are indeed getting populated with data:
var artist_names = [["'Bubonic Bear', "]];
var venue_names = [["'Electric Factory', "]];
UPDATE
If I hardcode a list for the "headliner" field's autocomplete function, the autocomplete works.
$("#headliner").autocomplete({
//source: artist_names,
source: ["band1", "band2", "band3"],
select: function(event, ui) {
submitForm($('#datepicker').val(), ui.item.value, $('#venue').val());
$('#add-artist').empty();
}
});
I'm still not sure of the solution, it seems odd that a variable would be accessible in a local instance of the app and not on heroku. Anyway, I will add more if I figure out more.
I don't see how that would work anywhere. Your data sources:
var artist_names = [<%= #artist_names %>];
var venue_names = [<%= #venue_names %>];
come out as:
var artist_names = [["'Bubonic Bear', "]];
var venue_names = [["'Electric Factory', "]];
and that's not the right format for the jQuery-UI Autocomplete widget. The source option should be a simple array of strings when you're using an inlined source.
You should be inlining your arrays in JSON format:
var artist_names = <%= #artist_names.to_json %>;
var venue_names = <%= #venue_names.to_json %>;
and that should produce things like this:
var artist_names = ["Bubonic Bear"];
var venue_names = ["Electric Factory"];
and the autocomplete widget will be happy with that.
You can play with this demo to see the difference:
http://jsfiddle.net/ambiguous/Brb9p/

Setting a minimum length for textarea

I am trying to make it so that this comment form on my wordpress website can not be submitted if the user does not enter enough data into the textarea.
I wrote this for the header
<script>
function CheckLength()
{
var msg_area = document.getElementById("Message");
msg_area.innerHTML = "";
if (document.getElementById("commentarea").value.length < 100) {
msg_area.innerHTML = "YOU DID NOT ENTER ENOUGH INFO FOR YOUR REVIEW";
}
else document.getElementById("commentform").submit();
}
</script>
And my form looks like this
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" name="commentform" id="commentform">
<p><input size="36" type="text" name="author" /> Name <span class="required">*</span></p>
<p><input size="36" type="text" name="email" /> Email <span class="required">*</span> (Not Published)</p>
<p><input size="36" type="text" name="url" /> Website</p>
<p><input size="36" type="text" name="server_ip" id="server_ip" /> Server IP/Hostname</p>
<p><?php show_subscription_checkbox(); ?></p>
<p><textarea name="comment" id="commentarea" cols="100%" rows="20"></textarea></p>
<p align="right"><input type="button" name="submit" id="submit" value="Submit Review" tabindex="5" onClick="CheckLength()"></p>
<span id="Message" style="color:#ff0000"></span>
<input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />
<?php /* do_action('comment_form', $post->ID); */ ?>
</form>
The form spits out the error "YOU DID NOT ENTER ENOUGH INFO FOR YOUR REVIEW" if I type in less then 100 chars, but if I type more then a 100 chars the form does not submit. If I change the input type to submit it does submit, but it doesn't matter if < 100
Change the name of your input button.
The error I get using your markup is that submit is not a function, because it thinks I'm referring to the submit button. The following should work:
<input type="button" name="submitbtn" id="submitbtn" value="Submit Review" tabindex="5" onClick="CheckLength()">
Could you do this?
Put the check in the "onsubmit" event for the form:
<form action="wp-comments-post.php" onsubmit="return CheckLength();" method="post" name="commentform" id="commentform">
You'll have to update you function to return a Boolean:
<script type="text/javascript">
function CheckLength()
{
var msg_area = document.getElementById("Message");
msg_area.innerHTML = "";
if (document.getElementById("commentarea").value.length < 100) {
msg_area.innerHTML = "YOU DID NOT ENTER ENOUGH INFO FOR YOUR REVIEW";
return false;
}
return true;
}
</script>
Then remove the onclick event from your submit button.
Can you try this?
<script>
function CheckLength()
{
var msg_area = document.getElementById("Message");
msg_area.innerHTML = "";
if (document.getElementById("commentarea").value.length < 100)
{
msg_area.innerHTML = "YOU DID NOT ENTER ENOUGH INFO FOR YOUR REVIEW";
return false;
}
else
{
document.getElementById("commentform").submit();
return true;
}
}
</script>

Resources