get value of input in casperjs - javascript

Hi allm I would like to know how to get an input value with casperjs
This is my html element
<input type="hidden" name="key" value="newkey">
This is what I have tried:
view = 'users/registered';
casper.test.begin("Activating account", 5, function register(test){
casper.start(webroot + view, function(){
}).then(function(){
this.echo("Retrieving data from hidden input key", "COMMENT");
activationKey = this.evaluate(function() {
return __utils__.getFieldValue('key');
});
}).then(function(){
this.echo("Activating account with the key \"" + activationKey + "\"", "COMMENT");
window.location = webroot + activationKey;
});
casper.run(function() {
this.echo('Account activated successfully', 'SUCCESS').exit();
test.done();
});
});
casper.viewport(page.width, page.height);
In this case return null
I have also tried:
activationKey = __utils__.getFieldValue('key');
but return me this error:
FAIL ReferenceError: Can't find variable: __utils__

Try using this :
this.getElementAttribute('input[type="hidden"][name="key"]', 'value');

If the value is set dynamically, then this.getElementAttribute won't work, nor will __utils__.getFieldValue. The only way, as of 1.1.3, is to call the underlying document object's querySelector.
var value = this.evaluate(function() {
return document.querySelector('[name="key"]').value
})
A bit verbose, but at least it works.
Also, regarding why __utils__ couldn't be found, use the following to import it:
var __utils__ = require('clientutils').create()
In the OP's example, __utils__ is in the evaluate() function. It shouldn't be, as __utils__ is a casper thing, not a DOM/javascript thing.

Related

Javascript redirect using windows.locaton.href OR windows.locaton.replace is not working. Error: window not defined

I have looked at all of the questions around windows.locaton.href and windows.locaton.replace not working, but still can't figure out why this redirect is not working in JavaScript. There are two JS functions I am calling when a button is clicked with submit.
<input type="submit"
onclick="NotifyUserOfNewBudgets('#Field1');redirect2MainLookup('#primaryFilename');"
class="SaveChangeButton" value="Create New Budget">
The two functions are defined in Javascript as:
<script>
function NotifyUserOfNewBudgets(val) {
alert("New Budget will be saved. NewVal=" + val);
var ireturn;
document.getElementById("NewBudgetID").value = val;
document.getElementById("formMode").value = "Update";
}
function redirect2MainLookup(primaryFilename) {
var loc = window.location.pathname;
var host = document.location.host;
var dir = loc.substring(0, loc.lastIndexOf('/'));
//Replace the word Edit with blank so this redirects correctly
var newdir = dir.replace("NewBudget", "");
var newpath = host + newdir + primaryFilename;
alert('newpath location = http://' + newpath);
try {
windows.locaton.href = "http://" + newpath;
//window.location.replace('http://' + newpath);
} catch (err) { alert("Error: " + err);}
}
</script>
The error I get in the try()catch() is windows is not defined and then is stays on the same page. I get the same error using windows.locaton.replace() too. I have lots of pages doing redirects, can't figure out why this one fails.
You have a number of spelling mistakes. window is the object you are looking to reference. location is the property you are looking to access. Right now, you are using windows.locaton. windows is not a thing, nor is locaton. Keep an eye on undefined errors, they can tell you a lot about the state of your code.

Use value from Input and set it to URL

I have an Input that takes a name, and I want to take that name from input and set the url accordingly .. Here's the code, and an example
.form-group
%input.form-control{'type':'name','placeholder':'Name',id:'wisher_name'}
%input.form-control{'type':'name','placeholder':'Special Message'}
%button.btn.btn.btn-success{'id':'wisher_btn'} Wish
Javascript
$(document).ready(function() {
$(document).on('click', '#wisher_btn', function() {
var e = document.getElementById("wisher_name");
var diwali_wisher = e.value
location.replace("localhost:3000" + "/loccasion/diwali/" + diwali_wisher);
});
});
But the last statement is never reached, I don't know why?
This is a very basic problem, but I am a beginner so need some help.
You need to use a full url, like https://stackoverflow.com.
Add the http protocol.
diwali_wisher= Input parameter name in receiver function
diwali_wisher = e.value
location.replace("localhost:3000" + "/loccasion/diwali?diwali_wisher=" + diwali_wisher);

Firebase "Uncaught TypeError: myDataRef.push is not a function"

I'm making PHP game, which uses Firebase-powered chat.
I have included code below. Its element of
$text = "(...)";
(where (...) means the code)
I have a problem, when I click Enter on the input to send the message nothing happens. Chrome shows that
Uncaught TypeError: myDataRef.push is not a function
but that makes no sense. My code is most copy of the Firebase Tutorial, but modified, that input is before the messages, and when new one appears it goes to up, not down.
<input type='text' id='messageInput' placeholder='Wiadomość'>
<div id='messagesDiv'></div><br>
<script>
var myDataRef = new Firebase('https://********.firebaseio.com/').limit(15);
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = '".$user->username."';
var text = $('#messageInput').val();
myDataRef.".'push'."({name: name, text: text});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
myDataRef.on('child_removed', function(snapshot) {
//do nothing
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).prependTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
I have searched for any answers, but I haven't found anything.
Thanks
Note: the game is available here: Automaty, but its in Polish.
You are trying to write a transaction on a Query object.
var myDataRef = new Firebase('https://********.firebaseio.com/').limit(15);
The limit() returns a Query object and not a DatabaseReference.
Instances of Query are obtained by calling startAt(), endAt(), or limit() on a DatabaseReference.
Try:
var myDataRef = new Firebase('https://********.firebaseio.com/');
myQuery = myDataRef.limit(15);
// ...
myDataRef.push({name: name, text: text});

Get JSON data from external URL and insert in a div as plain text

I have written a function to display some paragraph tags from an external webpage. For some reason the results are displayed in firebug console but not showing on the web page as I wanted (blank page).
function requestCrossDomain(callback){
var querylink = "select * from html where url='http://somedomain.com'" +
" and xpath='/html/body/div/div/div[2]/div/div/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
if (typeof callback === 'function'){
callback(data);
}
});
}
My firebug console shows the below value.
{"query":{"count":1,"created":"2013-12-23T06:31:46Z","lang":"en-US","results":{"dd":{"p":"Hills: High"}}}}
How can I modify the code to display the value of the P tag, which is "Hills: High"
I'm calling the function from HTML code and trying to display the value inside "#targetWrapper"
requestCrossDomain(function(results){
$('#targetWrapper').html(results);
});
Edited to reflect a functional fiddle
$(document).ready(function(){
requestCrossDomain();
});
function requestCrossDomain(){
var querylink = "select * from html where url='http://www.bom.gov.au/wa/forecasts" +
"/armadale.shtml' and xpath='/html/body/div/div/div[2]/div/div" +
"/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
$('#targetWrapper').html(data.query.results.dl.dd[0].p);
$("#targetWrapper").append("<br/><strong>" + JSON.stringify(data) + "</strong>");
});
}
Your data format was very much off the mark AND you cannot have two functions with the same name.
The object you get back from $.getJSON is a simple Javascript Object. You can access it just as you would any other object:
In this case, you'd use:
requestCrossDomain(function(results) {
$("#targetWrapper").html(results.query.results.dd.p);
}
I would highly recommend that you read the MDN documentation I linked above. Having MDN bookmarked is also a good idea; it's a great resource to have easy access to.

how do i find what's going wrong with my code

I have this function for my sql javascript
PATH="http://localhost/dhodia/";
try{
var tags=url.replace(PATH,"");
var spl=tags.split("/");
if(spl[0]=="i"){
if(spl.length>=2 && spl[1]=="hdd"){
}
addtoopen($("#"+spl[1]+"opn").attr("jso"));
menu_action(spl[1],url)
}
}catch(err){
var txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
i found there is problem at replace statement
if i use url as "http://localhost/dhodia/i/hdd" it will do replace
but if i use "http://localhost/dhodia/i/hdd/tarun" it is not doing replace
i want to track why it is not taking replace at this line
EDIT
I am using this in function as shown below
function hstppst(url){
config.pre=url;
if(url==PATH || url==PATH+"i/dashboard"){
$E("#"+current.open).hide();
unfixbox()
$E("#dashboard").show();
addtoopen(dsjsn);
document.title="My DashBoard";
current.open="dashboard";
}else{
var tags=url.replace(PATH,"");
var spl=tags.split("/");
if(spl[0]=="i"){
if(spl.length>=2 && spl[1]=="hdd"){
}
addtoopen($("#"+spl[1]+"opn").attr("jso"));
menu_action(spl[1],url)
}
}
}
and this function call when window.onpopstate changes
in onpopstate i pass url to this function
problem is that code is not executing after var tags=url.replace(PATH,""); and because i am using this function in onpopstate function if any error occurs poage refreshed and i am track what is error i am getting.
Please take a look at the usage of replace method of the string object:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
You mistakenly use replace.

Categories