jQuery: Reverse inserted date in input - date

I'm using a jQuery plugin called masked input for inserting date in wanted format. The problem is, when someone wants to insert a date which is in format of dd.mm.yyyy and I want the input as yyyy-mm-dd, sort of reverse.
Example, if you want to insert "17.06.2013", you got in input 2013-06-17. Now, the slash part is solved, but right order can be fixed with reversing of numbers or something else?
Here is my jsfiddle: http://jsfiddle.net/dzorz/ubMMb/
HTML:
<input id="date" tabindex="1" type="text">
Script:
jQuery(function($){
$("#date").mask("9999-99-99");
});
How can it be solved? Is there some simple solution or I must look for something more serious?

How about this?
jQuery(function($){
$("#date").mask("9999-99-99", {completed:function(){
var date = this.val();
var matches = date.match(/(.*)\-(.*)\-(.*)/);
var date_format = matches[3] + "." + matches[2] + "." + matches[1];
console.log(date_format);
} });
});

Related

autocomplete with Materialize - text instead of optional image

I am using Materialize Autocomplete and I wonder if there is a way to use text instead of "optional image". Why? In case the text is not unique then the user will not know which one to choose. It might happen that the options will be names and there might two people with the same name and surname.
When typing my question I found out that I cannot use duplicate entries in data
data: {
"Radek": myself,
"Radek": some other Radek,
"Radoslav": 'http://placehold.it/250x250'
},
js fiddle example
When you look at the source you find the following lines relevant for the images:
autocompleteOption.append('<img src="'+ data[key] +'" class="right circle"><span>'+ key +'</span>');
and
var img = $el.find('img');
$el.html("<span>" + beforeMatch + "<span class='highlight'>" + matchText + "</span>" + afterMatch + "</span>");
$el.prepend(img);
This prevents us from using the image-attribute for anything other than images.
We can insert something like this to trick Materialize
"Radoslav": " style="display: none;">Inserted Text <br><span style="display: none`
but it will just be converted to text resulting in a option equivalent to
"Inserted Text Radoslav": none
So there is sadly nothing to be gained here.
If you are looking to insert a linebreak, however, you can use this answer on How to force Materialize autocomplete text to flow to new line?

How to serialize html form in dart as a string for submission

In jQuery, there is a function to serialize a form element so for example I can submit it as an ajax request.
Let's say we have a form such as this:
<form id="form">
<select name="single">
<option>Single</option>
<option selected="selected">Single2</option>
</select>
<input type="checkbox" name="check" value="check1" id="ch1">
<input name="otherName" value="textValue" type="text">
</form>
If I do this with the help of jquery
var str = $( "form" ).serialize();
console.log(str);
the result would be
single=Single2&check=check1&otherName=textValue
Is there such functionality in dart's FormElement or I have to code it myself? Thanks.
I came up with my own simple solution that might not work in all cases (but for me it is workikng). The procedure is this:
First we need to extract all input or select element names and values from the form into Dart's Map, so the element name will be the key and value the value (e.g. {'single': 'Single2'}).
Then we will loop through this Map and manually create the resulting string.
The code might look something like this:
FormElement form = querySelector('#my-form'); // To select the form
Map data = {};
// Form elements to extract {name: value} from
final formElementSelectors = "select, input";
form.querySelectorAll(formElementSelectors).forEach((SelectElement el) {
data[el.name] = el.value;
});
var parameters = "";
for (var key in data.keys) {
if (parameters.isNotEmpty) {
parameters += "&";
}
parameters += '$key=${data[key]}';
}
Parameters should now contain all the {name: value} pairs from the specified form.
I haven't seen anything like that yet.
In this example Seth Ladd uses Polymers template to assign the form field values to a class which get's serialized.

Jquery onselect datepicker: if specific date then alert

This is my first question on stckoverflow so I hope I'm asking right.
On my website i'm using a jquery datepicker. This works fine. However, I need the following addon:
- When a user selects a date which is a specific date (var specificDate), alert with hello world.
This code already triggers the alert when selecting a date. However I am not able to figure out how to compare the "var date" with the array of specifc dates.
onSelect: function(dateText, inst){
var date = $(this).datepicker('getDate');
var specificDate = ["12-12-2013","11-12-2013"];
for (i=0; i < specificDate.length; i++){
if (date == specificDate [i]){
alert("hello world");
}
}
});
I think I need to know more about the date formats. My question is to get me a bit further with this how to make the comparison.
Thank you in advance!
Reference
if ($.datepicker.parseDate('dd-mm-yy', specificDate[0]) > $.datepicker.parseDate('dd-mm-yyyy', specificDate[1])){
alert(specificDate[0] + 'is later than ' + specificDate[1]);
}

Adding a (automatic) date field in data entry form using Sharepoint Designer 2010

I have a Sharepoint data entry Form for my List (Inspection Table), which has a field called "Date Entered". I want to automatically populate today's date and time when a user clicks on "Add new entry", as I want to use that as audit data.
Now, I wanted to use java script (as after research, this seems the most straight forward way to do so), so I added the following to the NewForm.aspx page:
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
<script language="javascript" type="text/javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
{dd='0'+dd;}
if(mm<10)
{mm='0'+mm;}
var formattedToday = mm+'/'+dd+'/'+yyyy;
alert(formattedToday);
document.getElementById('<%= ((TextBox)this.onetIDListForm.FindControl("ff10_1")).ClientID %>').value = formattedToday;
</script>
</asp:Content>
The alert(formattedToday); is just to test if the java script is picked up of course and will be removed in later stage.
Ok.. I get the popup, so the value is calculated correctly and java script works. The problem I have, is putting this value to the "Date Entered" field.
What would be the correct method to call the document.getElementByID?
I have tried multiple variations:
document.getElementById('<%= ((TextBox)this.onetIDListForm.FindControl("ff10_1")).ClientID %>').value = formattedToday;
Or..
document.setElementById("Date Entered").value = formattedToday;
Or..
document.setElementById("ff10_1").value = formattedToday;
Can somebody point me to the correct format, or the way to make this work?
Next to the script above, I think I need the Form field "Date Entered" behavior (enable view) to be set to "False" but that is out of scope at the moment.
Thanks,
Chris
Take a look at this article. It talks about how you can achieve this using jQuery. See sample below and try it out. You will have replace the column name with your corresponding name "Date Entered". This should populate the appropriate textbox for you.
<script type="text/javascript">
$(function() {
$('input[title=DefaultMeFieldNoSpaces]').attr(
{value: 'You are in a twisty maze of passages, all alike.'});
});

How can I remove empty fields from my form in the querystring?

I have a simple form with four inputs. When I submit my form, I want to use the GET http method.
For the example :
aaa : foo
bbb : ____
ccc : bar
ddd : ____
I want to have this query string :
/?aaa=foo&ccc=bar
The problem is I have this query string :
/?aaa=foo&bbb=&ccc=bar&ddd=
How can I remove empty fields from my form in the query string ?
Thanks.
You could use jQuery's submit function to validate/alter your form:
<form method="get" id="form1">
<input type="text" name="aaa" id="aaa" />
<input type="text" name="bbb" id="bbb" />
<input type="submit" value="Go" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").submit(function() {
if($("#bbb").val()=="") {
$("#bbb").remove();
}
});
});
</script>
The current solutions depend on the client running Javascript/jQuery - which cannot be guaranteed. Another option is to use a rewrite rule. On an Apache server, I've used the following in order to strip out empty $_GET values from form submissions;
RewriteCond %{REQUEST_URI} \/formpage\/?
RewriteCond %{QUERY_STRING} ^(.*)(&|\?)[a-z-_]+=(?=&|$)(.*)$ [NC]
RewriteRule .* \/formpage?%1%2 [R,L,NE]
... which would turn this ..;
http://www.yoursite.com/formpage?search=staff&year=&firstname=&surname=smith&area=
... into this;
http://www.yoursite.com/formpage?search=staff&surname=smith
A quick explanation:
RewriteCond %{REQUEST_URI} \/formpage\/? is a means to limit the scope of your regular expression to a particular sub-page of your site's address (for example, http://www.yoursite.com/formpage). It's not strictly required, but you may wish to apply the expression only to the page on which the form appears. This is one way of accomplishing this.
RewriteCond %{QUERY_STRING} ^(.*)(&|\?)[a-z-_]+=(?=&|$)(.*)$ [NC] is a second condition, which then matches against the query string (i.e. anything that appears from (or including) the question mark, such as ?firstname=sam$surname=smith). Let's break it down;
^(.*) - The ^ symbol signifies that this is the START of the query string, and the period . is saying ANY character. The asterisk * is a modifier against the period wildcard, saying that any number of them should be included in the scope.
(&|\?)[a-z-_]+=(?=&|$) - This is the most interesting bit (if you like this kind of thing ...). This finds your empty query string. Between the first parenthesis, we're stating that the string begins with an ampersand OR a literal question mark (backslash makes the following character literal, in this case - otherwise the question mark has a different meaning). Between the square brackets, we're saying match any character from a-z, OR hyphen - OR underscore _, and immediately after that the plus symbol + is stating that we should match any of those preceding characters 1 or more times. The equals sign = is just what it looks like (the equals between your query string name and its value). Finally, between the next parenthesis, we have a lookahead clause ?=that states that the next character MUST BE an ampersand OR the very end of the line, as indicated by the dollar sign $. The intention here is that your query string will only be considered a match if it's followed by the start of another query string or the end of the line without including a value.
The final bits (.*)$ [NC] are just matching against any and all content that follows an empty query string, and the [NC] clause means that this is cASe iNsENsiTIve.
RewriteRule .* \/formpage?%1%2 [R,L,NE] is where we tell mod_rewrite what to do with our matched content. Essentially rewriting the URL to your pagename followed the whole query string except the matched empty strings. Because this will loop over your URL until it ceases to find a match, it does not matter if you have a single empty value or 50. It should spot them all and leave only parameters that were submitted with values. The [NE] clause on the rewrite rule means that characters will not be URL encoded - which may or may not be useful to you if you are expecting special characters (but you obviously need to sanitize your $_GET data when you're processing it, which you should be doing anyway).
Again - this is obviously an Apache solution using mod_rewrite. If you are running on another operating system (such as a Windows server), this will need to be adjusted accordingly.
Hope that's of some use to someone.
I love the idea given by RaphDG
But I modified the code a little. I just use the disabled property rather removing the field.
Here is the changed code:
<form method="get" id="form1">
<input type="text" name="aaa" id="aaa" />
<input type="text" name="bbb" id="bbb" />
<input type="submit" value="Go" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").submit(function() {
if($("#bbb").val()=="") {
$("#bbb").prop('disabled', true);
}
});
});
</script>
Thanks once again for the idea RaphDG (y)
With JQuery:
$('#form').submit(function (e) {
e.preventDefault();
var query = $(this).serializeArray().filter(function (i) {
return i.value;
});
window.location.href = $(this).attr('action') + (query ? '?' + $.param(query) : '');
});
Explanations:
.submit() hooks onto the form's submit event
e.preventDefault() prevents the form from submitting
.serializeArray() gives us an array representation of the query string that was going to be sent.
.filter() removes falsy (including empty) values in that array.
$.param(query) creates a serialized and URL-compliant representation of our updated array
setting a value to window.location.href sends the request
See also this solution.
With jQuery:
$('form[method="get"]').submit(function(){
$(this).find(':input').each(function() {
var inp = $(this);
if (!inp.val()) {
inp.remove();
}
});
});
I use this to remove all empty parameters from all GET forms on my site. The :input pseudo selector covers all inputs, textareas, selects and buttons.
If you want to remove all empty inputs, you can iterate over the form inputs like this:
<script type="text/javascript">
$(document).ready(function() {
$("#form1").submit(function() {
$(this).find('input').each(function() {
if($(this).val() == '') {
$(this).remove();
}
});
});
});
</script>
Here's a very similar answer to the other ones, but it factors in select and textarea inputs as well:
$(document).ready(function() {
$("form").submit(function() {
let form = $(this);
form.find('input, select, textarea').each(function() {
let input = $(this);
if (input.val() == '') {
input.prop('disabled', true);
}
});
});
});