How to pass an ajax date to jquery? - ruby-on-rails

I have a datepicker, and I want to use the picked date in a query in a Movements table, to retrieve corresponding turnover. But "currentDate" does not load with the picked date : I have a "invalid date" exception caught. How should I do it ?
$("#datepicker").change(function(){
var currentDate = $( "#datepicker" ).datepicker( "getDate" );
var wantedTO = <%=Movement.where(:movementDate =>Date.parse("currentDate")).sum("turnover")%>;
$(document).ajaxComplete(function(){ $("#result").html("<p>Result here : </p>" + wantedTO);
});
});
Note that if I replace
var wantedTO = <%=Movement.where(:movementDate =>Date.parse("currentDate")).sum("turnover")%>;
by
var wantedTO = <%=Movement.where(:movementDate =>Date.today).sum("turnover")%>;
it's giving me today's turnover. So I might not be so far !
EDIT :
To be sure of the date format, I added a line
var dateString = $.datepicker.formatDate("yy-mm-dd", currentDate);
And checked OK that if I put a manual date in that format then, it's working. It seems that it's a problem of how to pass this variable, but I can't fix it. Any idea ?

OK I have my answer. In case other newbies would face the same problem, I will summarize it. There was a big mistake in my code : you can't do a ruby query inside the Ajax code. So waht, you have to do :
1- Create a new method (sort) in your controller (movements_controller.rb) :
def sort
selected_date = params[:date]
new_html_to_return = Movement.where(:movementDate =>Date.parse(params[:date])).sum("turnover")
render :text => new_html_to_return
end
2- Create a POST ajax function in your view (index.html.erb) :
<script>
$(document).ready(function(){
var $datepicker = $("#datepicker"),
currentDate = new Date(),
dateString = "";
$datepicker.change(function(){
currentDate = $datepicker.datepicker( "getDate" );
dateString = $.datepicker.formatDate("yy-mm-dd", currentDate);
$.ajax({
type: "POST",
// You're sending the variable to your Ruby on Rails controller
url: "movements/sort/",
data: {"date":dateString},
}).done(function(data) {
$("#result").html("<p>Turnover: </p>" + data)
});
});
});
</script>
3- Create the associated route in your routes.rb :
post "movements/sort"
And you're done ! Enjoy !

Related

using katex, '&' alignment symbol displays as 'amp;'

I am using katex to render math.
https://github.com/Khan/KaTeX
Generally, to get this to work I link to the files katex.min.js and katex.min.css from a cdn, which is one of the ways the directions suggest.
I wrap what needs to be rendered in tags and give all the same class. For example:
<span class='math'>\begin{bmatrix}a & b \\c & d\end{bmatrix}</span>
And inside a script tag I apply the following:
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].innerHTML, math[i]);
}
So, my implementation works but there is a problem in what katex returns. The output of the above gives me:
This exact same question is asked here:
https://github.com/j13z/reveal.js-math-katex-plugin/issues/2
But I can't understand any of it.
The solution is to use element.textContent, not element.innerHTML.
If I use a form like what follows, the matrix will be rendered properly.
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].textContent, math[i]); // <--element.textContent
}
A solution that works for me is the following (it is more of a hack rather than a fix):
<script type="text/javascript">
//first we define a function
function replaceAmp(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
//next we use this function to replace all occurences of 'amp;' with ""
var katexText = $(this).html();
var html = katex.renderToString(String.raw``+katexText+``, {
throwOnError: false
});
//hack to fix amp; error
var amp = '<span class="mord mathdefault">a</span><span class="mord mathdefault">m</span><span class="mord mathdefault">p</span><span class="mpunct">;</span>';
var html = replaceAmp(html, amp, "");
</script>
function convert(input) {
var input = input.replace(/amp;/g, '&'); //Find all 'amp;' and replace with '&'
input=input.replace(/&&/g, '&'); //Find all '&&' and replace with '&'. For leveling 10&x+ &3&y+&125&z = 34232
var html = katex.renderToString(input, {
throwOnError: false});
return html
}
Which version are you using?
Edit the src/utils.js and comment line number 51 to 55 after updated run in terminal npm run build command.

Select2 multiple values doubles prepopulated values on init, and still sends

There are a lot of questions about select2 doubling values, and many of them don't have accepted answers.
On the surface everything looks fine but when I delete a token it's still sending it in params.
Checking the values of the input (which select2 is hiding)
Prior to initializing select2
$('#language_list').val() //=> "english spanish italian"
After init
$('#language_list').val() //=> "english spanish italian,english,spanish,italian"
// It's clearer what's going on like this.
// And I don't know if it's significant but tokenSeparators: [",", " "]
$("#user_language_list").select2("val") //=> ["english spanish italian", "english", "spanish", "italian"]
Lots of issues are coming up like when the form repopulates after an error I'll have
$('#language_list').val() //=> "english-spanish-italian english spanish italian,english,spanish,italian"
Hidden in my input which I have to address on the backend.
What worked was cleaning the value before sending your data to the callback
You'll probably recognize this as basically the code from the docs.
initSelection: function (e, callback) {
var tags = e.val().split(/, |,| /);
for (var i = 0; i < tags.length; i++) {
var tag = tags[i].trim();
tags[i] = {id: tag, text: tag};
}
callback(tags);
}
But you just need to clean the val
initSelection: function (e, callback) {
var tags = e.val().split(/, |,| /);
e.val("")
for (var i = 0; i < tags.length; i++) {
var tag = tags[i].trim();
tags[i] = {id: tag, text: tag};
}
callback(tags);
}

How do I get the ASP.Net MVC Password HTML Helper to show characters as I type?

I'm using the Password HTML Helper in MVC5 to hide the social security number as it is entered.
#Html.Password("s", null, new { #maxlength = 9, autocomplete = "off" })
The problem I see with it is you just see dots as you type. Is there any way the helper behavior can be modified to show the characters you are typing in for a second or two then have them transformed to dots? That behavior would let the user confirm they are typing in the correct character. If the helper behavior cannot be modified is there another way to accomplish this?
I found this fiddle maybe you can use this as an option
http://jsfiddle.net/Ngtp7/
$(function(){
$(".showpassword").each(function(index,input) {
var $input = $(input);
$('<label class="showpasswordlabel"/>').append(
$("<input type='checkbox' class='showpasswordcheckbox' />").click(function() {
var change = $(this).is(":checked") ? "text" : "password";
var rep = $("<input type='" + change + "' />")
.attr("id", $input.attr("id"))
.attr("name", $input.attr("name"))
.attr('class', $input.attr('class'))
.val($input.val())
.insertBefore($input);
$input.remove();
$input = rep;
})
).append($("<span/>").text("Show password")).insertAfter($input);
});
});

How to auto-format dates in custom tooltip formatter?

Highcharts does a great job auto-formatting dates both on the x-axis and in tooltips. Unfortunately I need a custom function to format my y-values, and /plotOptions/line/tooltip/pointFormat accepts only a format string and not a function, so I have to set /tooltip/formatter instead. How do I get hold of the formatted date (e.g. Oct'13 or 20. Oct) as shown on the x axis? I don't seem to have access to point.key from there, only the raw millis value.
http://jsfiddle.net/9Fke4/
You can use dateFormat()
tooltip: {
formatter: function() {
return '<b>' + Highcharts.dateFormat('%b\' %d',this.x) + ':</b> ' + this.y;
}
},
http://jsfiddle.net/9Fke4/1/
FWIW, this was answered in a Highcharts issue on Github
formatter: function() {
var tooltip = this.series.chart.tooltip,
item = this.point.getLabelConfig(),
header = this.series.chart.tooltip.tooltipFooterHeaderFormatter(item);
return header + this.y;
}
Corresponding fiddle:
http://jsfiddle.net/9Fke4/12/
If you are using a shared series:
tooltip: {
formatter: function (tooltip) {
var header,
s = [];
$.each(this.points, function(i, point) {
if(header == null) {
var config = point.point.getLabelConfig();
header = tooltip.tooltipFooterHeaderFormatter(config);
}
s.push(point.y);
});
return header + s.reverse().join('<br>');
},
shared: true
}
conver the raw milliseconds to a date object using
var currentDate = new Date (tome in milliseconds)
in the tootip/formatter function you have defined.
this will give you good control over the date. you can use currentDate.getMonth(), getDate(), getDay(), etc methods to get the information you want from that date.
build a string with the above info and return.
I hope this will help you.
The solution I ended up with is to pre-format the y-values and store them as part of the series data; the pre-formatted values can then be referenced from the tooltip headerFormat and pointFormat, where they can be used along with {point.key}, which contains the auto-formatted date (and which is not available when providing a custom tooltip formatter):
http://jsfiddle.net/uG3sv/

Geting DataTime from database through Javascript

I have a MVC Web Application Im trying to Ajax call an action method to retrieve some datetime from the database, the problem is the value comes as "/Date(386028000000)/"
its a DateOfBirth actually which I m using a java script function to calculate the age:
function (DOB) {
var birthday = +new Date(DOB);
return ~~((Date.now() - birthday) / (31557600000));
}
Anyway i can fix the Date Format and get only the date in a proper format or change the Java-Script method to accept the current format of the date value ?
I got it
var FixedDate = new Date();
FixedDate .setTime(DOB.replace("/Date(", "").replace(")/", ""));
return ~~((Date.now() - FixedDate) / (31557600000));
Click here to check the Demo
Sample Javascript/JQuery
var = MyDate_String_Value = "/Date(386028000000)/"
var value = new Date
(
parseInt(MyDate_String_Value.replace(/(^.*\()|([+-].*$)/g, ''))
);
var dat = value.getMonth() +
1 +
"/" +
value.getDate() +
"/" +
value.getFullYear();
Result - "3/27/1982"

Resources