Hilios Jquery Countdown localization - javascript

Hi I'm using Hilios Jquery Countdown https://github.com/hilios/jQuery.countdown
Example of multiple instances:
<div data-countdown="2014/06/20 20:00"></div>
<div data-countdown="2014/06/21 20:00"></div>
<div data-countdown="2014/06/22 20:00"></div>
Js:
$('[data-countdown]').each(function () {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function (event) {
var format = '%H:%M:%S';
if (event.offset.days > 0) {
format = '%-d day%!d ' + format;
}
if (event.offset.weeks > 0) {
format = '%-w week%!w ' + format;
}
$(this).html(event.strftime(format));
});
});
The problem here is, that if I select some European language(German, Slovenian) in the browser, the browser automatically formats string date from 2014/06/20 to 2014.06.20 which makes the script not working. Why is this happening? Am I passing the date value to data attribute wrong?
When I see their examples here: http://hilios.github.io/jQuery.countdown/examples/multiple-instances.html it works properly with all languages... but they dont have an example of HTML implementation, only the way I am doing it, but somehow for them it works.
Anyone had issues with this?

I had to use CultureInfo.InvariantCulture.

Related

Having difficulty building a form summary with JS

Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.

Ajax/jQuery live search is duplicating the output results

I'm currently working on Ajax and jQuery live search which finds a results in a JSON file. Script is working fine, but the is only one problem - it's duplicating the result data.
EXAMPLE:
MARKUP:
<div class="row">
<h3>Live Search Results</h3>
<div id="update-results">
<p>event_name | club_name | memberid</p>
<ul id="update">
<!-- <li></li> -->
</ul>
</div>
</div>
SCRIPT:
$('#search').keyup(function() {
var searchField = $('#search').val();
var $update = $('#update');
$update.empty();
$.get("getEventsWithVideos.php?text=" + searchField, function(data) {
var vals = jQuery.parseJSON(data);
if($.isArray(vals['Event'])) {
$.each(vals['Event'], function(k,v){
$update.append("<li value='"+v['id']+"'><a href='#'>" + v['event_name'] + "</a></li>");
});
} else {
$update.append("<li value='"+vals['Event']['id']+"'><a href='#'>" + vals['Event']['event_name'] + "</a></li>");
}
});
});
I've tried to debug and stop the error, but it was unsuccessful. Can anyone help me please with that?
Put the empty() inside the response handler:
$.get("getEventsWithVideos.php?text=" + searchField, function(data) {
$update.empty();
basically you are clearing the list on every keystroke (rapid), then requesting the data, then (sometime later) appending the results that come back (which could be multiple results depending on the timing).
I didn't reproduce your error but I suspect that you have problem with multiple request to server and adding them all instead of last one. Probably adding below code will fix your problem
$update.empty();
Anyway I suggest you to use 2 more functions: throtlle and debounce from underscore to prevent too much request on every keyup.
Also you could try Rx.js witch give following example (https://github.com/Reactive-Extensions/RxJS):
var $input = $('#input'),
$results = $('#results');
/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent($input, 'keyup')
.map(function (e) {
return e.target.value;
})
.filter(function (text) {
return text.length > 2;
});
/* Now debounce the input for 500ms */
var debounced = keyups
.debounce(500 /* ms */);
/* Now get only distinct values, so we eliminate the arrows and other control characters */
var distinct = debounced
.distinctUntilChanged();
Try changing this line $update.empty(); of your code to $update.find('li').remove(); and put it inside the response handler.
This removes all the previous data before you append the new values. Hopefully it might work.

rails 3 jQuery UI Datepicker want to enable only specific dates

I have a Registration model and form which uses a datepicker. I want the user to be only able to select dates which correspond to events (another model).
My problem is I can't find the right way to pass the event array to javascript.
this is in the controller:
#available_dates = Event.pluck(:start_time).as_json
this is in the view:
<script>
var availableDates = [<%= #available_dates.to_s.html_safe %>] ;
</script>
and this is the js:
function available(date) {
ymd = date.getFullYear() + "-" + ('0' + (date.getMonth()+1)).slice(-2) + "-" + ('0' + date.getDate()).slice(-2);
console.log(ymd+' : '+($.inArray(ymd, availableDates)));
if ($.inArray(ymd, availableDates) != -1) {
return [true, "","Available"];
} else {
return [false,"","unAvailable"];
}
}
$("#registration_date").datepicker({ beforeShowDay: available, dateFormat: "yy-mm-dd"});
I think I'm doing something wrong in the view since the js array seems to be empty looking at the console...
any help would be greatly appreciated
In the question comments you have mentioned #available_dates.to_s returns "[\"2013-01-05\", \"2013-02-02\", \"2013-03-02\"]". This itself will render the array on the page so no need to "box it up" again.
Try changing the following line:
var availableDates = [<%= #available_dates.to_s.html_safe %>] ;
to this:
var availableDates = <%= #available_dates.to_s.html_safe %>;
Hope it helps.
If it doesn't you are either clearing the value of #available_dates somewhere further in your code or #available_dates is not available in the context of your view. Have your tried stepping through the code using debugger;?

Regex for AM PM time format for jquery

I am being frustrated by a regular expression to mask the input field. I want to Limit input to hh:mm AM|PM format and I can't get this regex to work.
I use this regex in conjunction with a jquery tool from www.ThimbleOpenSource.com. It was the filter_input.js tool or whatever.
It seems to work for a simple regular expression but the one I came up with doesn't seem to work. This is my jsFiddle test link below.
jsFiddle
I have made a jsfiddle example, based on the regular expression of the answer von Yuri:
http://jsfiddle.net/Evaqk/
$('#test1, #test2').blur(function(){
var validTime = $(this).val().match(/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/);
if (!validTime) {
$(this).val('').focus().css('background', '#fdd');
} else {
$(this).css('background', 'transparent');
}
});
First of all, if you using it for input field, you should never let users input date or time information using text fields and hoping it will be in strict format.
But, if you insist:
/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/
This regex will validate time in AM/PM format.
You can't do that with that plugin because here you need to check each character.
HTML:
<form>
<p>When?</p>
<input type="text" id="test1" placeholder="hh:mm(AM|PM)"/>
</form>
JavaScript:
$("#test1").keypress(function(e) {
var regex = ["[0-2]",
"[0-4]",
":",
"[0-6]",
"[0-9]",
"(A|P)",
"M"],
string = $(this).val() + String.fromCharCode(e.which),
b = true;
for (var i = 0; i < string.length; i++) {
if (!new RegExp("^" + regex[i] + "$").test(string[i])) {
b = false;
}
}
return b;
});
Example
So I'm pretty sure this is solved by now, but I was recently struggling with this and couldn't find an answer fast enough. I'm using Bootstrap Validator (bootstrapvalidator.com by #nghuuphuoc) in conjunction with Eonasdan's DateTimepicker to validate an hour (PS: You can disable the date in Eonasdan's plugin).
Since Bootstrap Validator doesn't yet have a validator for time, you have to use a Regex. This one worked perfectly for me:
^([0-1]?[0-9]|2[0-3]):[0-5][0-9] [APap][mM]$
the follwing function return (true/false) value
function CheckTime(HtmlInputElement) {
var dt = HtmlInputElement.value;
return (/(0?[1-9]|1[0-2]):[0-5][0-9] ?[APap][mM]$/.test(dt));
}
Check this solution too.
<!DOCTYPE html>
<html>
<body>
<p>This demo used to validate time with 12 hours format</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var regexp = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/;
var res = regexp.test('12:00 AM'); //try with alphabets or wrong format
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

Javascript functions

So I have a textbox which allows a max entry of 5 characters.
The user should enter the time in the format hh:mm or hhmm , into the textbox.
Supposing the user enters 1:2:3 or 1::2 etc, then it should show an alert message('Incorrect time format')
Is there any way I can check all other occurences of : EXCEPT for the first : , and alert the user?
(This needs to be done within a javascript function)
This is what I used to check for non-digit values(excluding :) entered into textbox:
<script type='text/javascript'>
function getClks(){
...
var re=":";
var found = clks.match(re);
if (clks.match(/^[0-9:]/)){
alert('Invalid time value');
}
if (found=:){
var splitime = clks.split(":");
var hours = splitime[0];
var mins = splitime[1];
......
}
}
</script>
Unless you have a very good reason to change the user's input. I would recommend only alerting the user that their input doesn't match the correct format.
If you really want to remove characters, you can use the replace function with some regex to remove the extra : chars.
You can use search or match to test whether the input is in the correct format.
Something like /^\d{1,2}:\d{2}$/ should work.
try to use this jquery plugin: http://digitalbush.com/projects/masked-input-plugin/
It will mask your textbox:
$("#hour").mask("99:99");
#alexl's jQuery plugin is probably enough, but for completeness sake..
Outside jQuery contexts I'd use a RegExp, /([0-9][0-9]):([0-9][0-9])/, and test the number string like so:
var timestr = /* .. get the text .. */
if(timestr.match(/([0-9][0-9]):([0-9][0-9])/) {
console.log('Good number string');
} else {
console.log('Bad number string');
}
Everyone else explained what to do. Here's a more concrete example of how to use it.
var regex = new RegExp("\\d{2}[:]\\d{2}");
if (regex.test(input)) {
var array = input.split(":");
var hours = array[0];
var minutes = array[1];
} else {
alert("malformed input");
}
You could do something like this
markup
<input id="myinput" maxlength="5" type="text" />
<input type="button" onclick="test()" value="test" id="testbtn" />
js
var re = new RegExp("^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$");
var myInput = document.getElementById('myinput');
function test(){
alert(re.test(myInput.value)); //alerts true if the input is well-formed
}
example => http://jsfiddle.net/steweb/rRZLx/

Categories

Resources