How do I save a file triggered by button click in CasperJS? - javascript

I am trying to download a log that is filled by date range, so I fill out the form with the dates I want and then when you click the "Export Call Logs" button it just automatically triggers a CSV file download in a regular browser.
How do I save that file that should be automatically triggered when 'clicking' the same button using Casper?
casper.then(function(){
console.log("Filling out form and getting CSV");
this.evaluate(function(){
document.getElementsByName("startdate")[0].value="08/30/2016";
document.getElementsByName("enddate")[0].value="08/30/2016";
document.getElementsByName("s1")[0].click();
});
});
The button HTML is as follows:
<td><input type="submit" name="s1" value="Export Call Logs"></td>
Also, as a side note, obviously I don't want to manually input the date, kinda defeats the point of a program in a way, I am most familiar with Pyhon, is their some sort of equivalent to the DateTime module or someway I can use Casper to get the previous days date and store as a Var to input accordingly? i.e todays date is 08/31/2016 I would want to input the previous day, 08/30/2016.
EDIT:
Tried implementing the example commented below.
casper.then(function(){
console.log("Filling out form and getting CSV");
this.page.onFileDownload = function(status){console.log("onFileDownload(' + status + ')");
return "downloadedfile.csv"; };
this.evaluate(function(){
document.getElementsByName("startdate")[0].value="08/30/2016";
document.getElementsByName("enddate")[0].value="08/30/2016";
document.getElementsByName("s1")[0].click();
});
});

You can try download() function, you can find more information here.
There is an example.

Related

Trouble sending JavaScript into <input type="date"> calendar

Goal: Attempting to automate a calendar on Chrome using Selenium(Python + behave).
The issue: The date is only being set when actually clicked through the calendar. Passing a value via JavaScript is not working.
Note: According to docs the inputs should allow users to send input in with keys by default but that doesn't even work. It does not accept keyboard input at all.
Problem Walkthrough
This is the original input fields. The div class they are contained in is inside a #shadow-root
(open):
Ignoring the Python. I will try and change the values with some simple JavaScript in the Chrome Dev Tools console:
x = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for From Date
x = "2022-05-12"
y = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for To Date
y = "2022-06-12"
After sending in the new values and clicking search. It does not recognize the values as being entered:
However, when manually selected through the calendar:
The dates are accepted and as inputs:
The HTML for the calendar is:
<input type="date" min="2022-01-01" max="2022-07-19">
Clearly. The JavaScript alone does not seem to be enough. If you use the same method above on this calendar it will work. However, on the calendar I am attempting this JS method will not work for some reason. Also, I cannot get Selenium to click and open the calendar on its own for some odd reason.
Solution: Manually trigger the event (Source)
let element = document.getElementById(id);
element.dispatchEvent(new Event("change")); // or whatever the event type might be
dispatchEvent() Documentatio
Event() Documentation

Append an Input Field Value to a URL on a .cshtml Page

I have a link to an SSRS report in my .cshtml page:
<div class="col-md-8">
<a href="http://xxx.xx.xx.x/ReportServer/Pages/ReportViewer.aspx?%2fCompany_Reporting%2fpayr0001&rs:Command=Render&StartDate=01/09/2017" target="_blank" >Timesheet Status Report</a>
</div>
I need to pass the value from my date control as a parameter as opposed to the hard-coded date above:
<div class="form-group">
<input type="date" class="form-control" id="datefrom">
</div>
I have tried appending an onclick=myfunction() to the url to add the date value, but can't get it to work.
function getStartDate() {
return document.getElementById("datefrom").value;
}
Any help would be much appreciated.
Cheers.
Create the href of the anchor tag on the date change attribute. Build the href on the go.
$('#datefrom').change(function(){
$('#IdOfAnchorTag').attr('href','http://xxx.xx.xx.x/ReportServer/Pages/ReportViewer.aspx?%2fCompany_Reporting%2fpayr0001&rs:Command=Render&StartDate=' + $('#datefrom').val() );
});
Check the strings accordingly..
This is what you're trying to do, as far as I can tell (duplicate question?):
append to url and refresh page
To get the date in the correct format, you'll have to do something like the following in the body of your function:
new Date($('input[type=date]').val()).toLocaleFormat();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat
Also, you're probably going to want to use 'onblur'/the blur event for the date input, or wire up your event handler function to a new button specifically for that purpose. This is because onclick/the click event will fire as soon as you click on the date input (which could open some sort of calendar widget, depending on the browser and browser version).
Before you pass your date value to the url, You try converting your date to dd-MM-yyyy or MM-dd-yyyy instead of dd/MM/YYYY.
Because I think that when the url will misunderstand "/", so you should replace with "-".
Then if necessary, you can convert back to the old format.

bootstrap datepicker and local storage

I would like the user to select a date from a bootstrap datepicker component and store the selected value in local storage. When the user has completed their selection they can select the button whereupon an ajax call will use the local storage.
At this moment I'm having trouble getting the datepicker component to set a value in the local storage. The date picker component renders when the user selects is and the user's selection becomes the value of the input field.
Here is the mark up:
<form>
<div class="form-group">
<label for="edge-name" class"control-label">Start:</label>
<input type="text" class="form-control" id="filterStart">
</div>
</form>
And the javascript
$(document).ready(function(){
$('#filterStart').datepicker();
$('#filterStart').on('changeDate' function(){
var newValue = $('#filterStart').datepicker('getFormattedDate')
localStorage.setItem('filterStart',newValue);
});
I've inserted console.log in various places throughout the javascript but the code never writes to the console therefore I know that its not writing to the local storage. I know that the local storage is working because I'm using it other parts of the code.
Also, any suggestions on how to do this better would be greatly appreciated.
If you are using this bootstrap-datepicker you can take a look to the following jsfiddle:
$('#filterStart').datepicker();
$('#filterStart').on('changeDate', function (e) {
var newValue = $('#filterStart').datepicker('getFormattedDate')
localStorage.setItem('filterStart', newValue);
});
$('#btn').on('click', function(e) {
$('#logMsg').val('Value saved in local storage is: ' +
localStorage.getItem('filterStart'));
})
I can't find if method 'getFormattedDate' exists but there is a standard getDate method for that. By the way you miss a semicolon in definition line of newValue;
I think you might be instantiating a new datepicker in your changeDate event. You could try getting the formatted date from the .data:
var newValue = $('#filterStart').data('datepicker').getFormattedDate('yyyy-mm-dd');

Textfield not displaying variable from javascript function

I am attempting to get the data displayed from a database (it displays it on a dynamic page within a table) and have it as the value for a textfield on a different html page (map.html).
The value will be some sort of postcode/address and I want that to go into my google map page within the destination textfield. So when users check the location of the event they press the 'View on Map' button which will open up the page of the map and the data from the event should already be populated within the textfield.
However nothing appears and instead it remains blank, even when I just put in some dummy text it still doesn't populate. I know that the location value is being fetched as the alert correctly displays the location, but the problem is having it populate in the textfield.
I am using JQuery Mobile/Cordova/JavaScript/JQuery/HTML. The app is a one-page structure, with the exception of map.html which has it's own page.
Any ideas?
Fetching the location value:
$(document).on("click", ".btnMap", function(e){
var location = $(this).data("rowlocation");
viewMap(location);
});
Snippet of Button:
<a data-rowlocation='" + response.rows.item(i).Location + "' href='map.html' onclick='viewMap(location)' data-role='button' rel='external' data-mini='true' class='btnMap'>View on Map</a></td></tr>"
viewMap Function:
function viewMap(location) {
alert(location);
$("#target-dest").val(location);
}
HTML:
<input type="text" name="target-dest" id="target-dest" />
the simplest way of passing the location to a new page - using your existing code would be to append the location as a query string to the href in the link.
<a ...href='map.html?loc='" + response.rows.item(i).Location + "'...
and then on the destination page - use JS to grab the querystring from the URL, split it from the rest of the UURL and pass it to the textbox.
//js on destination page
var locn=location.href;
var locationPortions = locn.split("?loc=");
$('#target-dest").val(locationPortions[1]);
Because the trigger for this is clicking an <a>, the link is causing a loading of the map.html page which negates the updating of the contents of the textbox:
<a ...href='map.html'...
This is taking precedence over the onclick event. You need to either change the link into a button and trigger the function as an onclick event or prevent the link from performing its normal function as other posters have noted with e.preventDefault().

"Bubble" validation message on non-form element

I have some elements on a page and I want to make use of the nice bubble style messages such as described here HTML5 form validation. It seems that to use them it is required they are within a form element and they only can be used on validation once the form is attempted to be submitted.
Taking from the linked example, I want to know how to get the following to work as described (i.e for this example pop a bubble message if the user sets a time before now)
Fiddle for this: My attempt without form
<body>
<label>
Arrival Date:
<input id="arrivalDate" type="date" onchange="dateChanged()" />
</label>
<input type="button" value="Test Reservation"></input>
<script type="text/javascript">
function dateChanged(e){
var arrivalDate = document.getElementById("arrivalDate");
var value = new Date(arrivalDate.value);
if (value < new Date()) {
arrivalDate.setCustomValidity("Arrival date must be after now!");
} else {
arrivalDate.setCustomValidity("");
}
arrivalDate.checkValidity();
}
</script>
</body>
Specifically in my case I have 2 KendoUI DateTimePickers being used to select the time range which is used to display information dynamically on the page. I'd like if I could use these bubble messages if the user tries to make the start time after the end time.
There's no way to manually trigger the validation. Using .checkValidity() will only return true/false if the context of what your checking is valid or not, i.e. if you did form.checkValidity() it will check if all form elements are valid, or input.checkValidity() only check the validity of that single element.
The only way to trigger the validation is on submit. You can simulate this by having a submit button and calling the click function.
if (!arrivalDate.checkValidity())
{
document.getElementById('submit_reservation').click();
}
Fiddle: http://jsfiddle.net/QGpQj/3/
Note: I've added window.dateChanged = .... because of your inline event listener. You really should be using .addEventListener or, ideally, jQuery for this to add backwards compatability support for those non-supported browsers.

Categories

Resources