casperjs: can't get jquery to use global variables - javascript

I'm hoping this is a stupid question with an easy answer.
(I've googled for a day and a half without joy)
I am writing a casperjs script which changes a pulldown menu
I've dumbed down the test code to get to the crux of the problem
My test HTML is as follows:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body style="background-color:powderblue;">
<form>
<select id="down">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
</form>
</body>
</html>
A working Casperjs script using jquery:
casper.start("http://192.168.0.14/test.html", function(){
//change the pulldown selection
casper.then(function () {
this.evaluate(function(){
$('#down').val('vw').change();
});
});
casper.then(function(){
this.capture("screen.png");
});
});
casper.run();
Now I want to parameterise the code, and use variables instead of strings for the selector and the value. But this code does not work:
var x1='#down';
var y1='vw';
casper.start("http://192.168.0.14/test.html", function(){
//change the pulldown selection
casper.then(function () {
this.evaluate(function(){
$(x1).val(y1).change();
});
});
casper.then(function(){
this.capture("screen.png");
});
});
casper.run();
This shouldn't be difficult (and probably isn't) but all combinations of "window." or square bracket notations have failed me.
jquery is refusing to play nice.
Please help, I didn't think this would put me out of my depth, but it clearly has

Try this:-
this.evaluate(function(x1, y1){
$(x1).val(y1).change();
}, x1, y1);
Anything inside evaluate is sandboxed and you will need to pass in any params you want to use inside

Related

Select all multi-select Option using javascript

I tried to select all options of multi-slect flower[ ] using javascript but nothing happened when I click on submit, please tell what wrong ?
<html>
<head>
<script language="javascript" type="text/javascript">
$("#submit").click(function() {
$('#flower option').each(function() {
$(this).attr('selected', true);
});
});
</script>
</head>
<body>
<form method="Get" action="#">
<select name="flower[ ]" id="flower" multiple>
<option value="flower">FLOWER</option>
<option value="rose">ROSE</option>
<option value="lilly">LILLY</option>
<option value="jasmine">JASMINE</option>
<option value="lotus">LOTUS</option>
<option value="tulips">TULIPS</option>
</select>
<input type="submit" id="submit" name="submit" value="submit">
</form>
</body>
</html>
You must put your javscript click function inside document ready function. Like this
$(document).ready(function(){
$("#submit").click(function(e){
$('#flower option').each(function () {
$(this).attr('selected', true);
});
});
});
Cheers.. :)
You are missing:
$(document).ready(function(){
above your script and then close it with:
});
but as mentioned above:
$('#flower option').attr('selected', true);
Should do the trick as well
$('#flower option').attr('selected', true);
You've already selected all of the options so the each loop is unnecessary.
Put your javascript on the end of body or use $(document).ready(). It must be executed when form is already rendered.
You can do it with .val(). $('#flower').val(ARRAY OF VALUES), i.e.
$('#flower').val(['lilly', 'lotus']);
For selecting all you can use
$('#flower').val($('#flower option').map(function(){
return $(this).attr('value');
}));
You do not specify in your question, but it looks like you are using jQuery. If you do, first make sure that you have placed your code inside of a $(document).ready(function(){...}) block so that you are waiting until the DOM is ready for you to begin attaching event listeners. Also, you shouldn't need the .each(function(){...}) call. Finally, to ensure cross-browser compatibility and to conform to standards, set the selected attribute to 'selected' rather than true. See code below.
$(document).ready(function() {
$('#submit').click(function() {
$('#flower option').attr('selected', 'selected');
});
});
EDIT
Actually, it's better to use jQuery's .prop() here, since using .attr() only is only to be used for setting the option's initial state. So...
$(document).ready(function() {
$('#submit').click(function() {
$('#flower option').prop('selected', true);
});
});
More info on this can be found in this question...
Jquery select all values in a multiselect dropdown

Javascript only works when assigning variable to function?

I'm working on a project that uses bootstrap. In the project, some additional functionality was needed so that when a user selects a certain option from the drop down it hid/showed certain content. It look as follows:
<select class="form-control" id="state-text" onChange="test()" name="selected-state" >
<!-- Select options here -->
</select>
Then I had the JS as follows:
function test()
{
// Code here
}
Now this didn't work, and would throw an error that function test was not defined. However, when I repalced it with:
test = function test()
{
//Code here
}
it worked as intended. I don't understand why one worked and the other didn't? Does it maybe have something to do with the other JS files that the bootstrap file is importing?
As you tagged the question as jQuery here's a fiddle I made quickly
http://jsfiddle.net/nYmF8/
markup
<select class="form-control" id="state-text" name="selected-state" >
<option value="a">A</option>
<option value="b">B</option>
<option value="b">C</option>
</select>
jquery
$(function(){$('#state-text').on('change', function () {
alert('changed value to to '+$(this).val());
});});
maybe you forgot to put your jQuery in the document ready function?
try to avoid adding JS in the middle of your HTML. Try doing that instead:
$(document).ready(function() {
$('#state-text').on('change', function () {
//Code Here
});
});
I am assuming here that you are using jQuery since it's a requirement for bootstrap. If not, let me know.

append() text value to div onclick()

I am creating an instant messenger using jquery and am having trouble taking the message typed into the message field after clicking the "send" button
I have the html
<body>
<div class="main-window">
<div class="chat-screen"></div>
<div class="bottom-wrapper">
<input class="text-bar"></input>
<input type="button" value="Send"class="send-btn">Send</input>
</div>
</div>
<body>
and I have tried to append it using this jquery
$('.send-btn').click(function() {
$(".text-bar").text().appendTo(".chat-screen");
});
But it doesn't seem to work. Can someone please point me in the right direction?
JSFiddle
you need .val()
change
$(".text-bar").text()
to
$(".text-bar").val()
you code becomes
Fiddle DEMO
use .append()
$('.send-btn').click(function () {
$(".chat-screen").append($(".text-bar").val());
});
Clear Textbox and new chat in new line.
$(document).ready(function () {
var chat_screen = $(".chat-screen");
var text_bar = $(".text-bar")
$('.send-btn').click(function () {
chat_screen.append(text_bar.val() + '<br/>');
text_bar.val('');
});
});
Updated Fiddle DEMO
The .text() (and correct .val()) functions return strings, not jQuery objects, and therefore don't have the appendTo() function available on them. You'll need to do this instead:
$('.chat-screen').append($('.text-bar').val());
Also make sure that, if the script is in the <head> of your HTML page, or comes before the actual HTML of the elements, you wrap it in a DOM ready handler:
$(document).ready(function() {
$('.send-btn').click(function(){
$('.chat-screen').append($('.text-bar').val());
});
});
And, of course, check that jQuery is being loaded correctly (it wasn't in your jsFiddle at all).
Since this is going to (probably) be running a lot of times, you'd want to cache the selectors for the chat screen and the text input, like so:
$(document).ready(function() {
var $chatscreen = $('.chat-screen'),
$textbar = $('.text-bar');
$('.send-btn').click(function(){
$chatscreen.append($textbar.val());
$textbar.val('');
});
});
Updated jsFiddle
Here is you fiddle updates: jsfiddle
Use val() instead text()
$('.send-btn').click(function(){
//$(".text-bar").val().appendTo(".chat-screen");
$(".chat-screen").append($(".text-bar").val())
$(".chat-screen").append('<br />')
});
please see http://jsfiddle.net/K95P3/15/
Several issues:
Add space between value and class attributes in input
Change .text() to .val() - inputs don't have text nodes, just values
Use $('.chat-screen').append($(".text-bar").val());
Make sure you have jQuery included
See updated fiddle http://jsfiddle.net/K95P3/11/
Try this.
$('.send-btn').click(function(){
$('.chat-screen').append($(".text-bar").val());
});
Actually, you really should append an html tag, not just text. I mean, you could, but shouldn't.
What i would recommend is this:
Create a base container for a message like:
<div class="message-container" style="display:none;">
<span class="message"> </span>
</div>
You then clone this container, stuff it the value of the input in the chat and append it to the chat screen.
The code could be something like:
$('.send-btn').click(function(){
var container = $('.message-container:hidden').clone(true).show();
container.find('.message').text($(".text-bar").val());
container.appendTo($('.chat-screen'));
});
Append text and dropdown value sametime
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
//var x=$("#cars option:selected").text();
//var y=$("#bus").val();
//alert(''+x+' '+y+'');
$(".chat-screen2").append($("#cars").val()+'<br/>');
$(".chat-screen").append($("#bus").val()+'<br/>');
$("#bus").val('');
});
});
</script>
</head>
<body>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<input id="bus" type="text">
<button type="submit">submit</button>
<br><br>
<div class="chat-screen2" style="float:left;"></div>
<div class="chat-screen" style="float:left;margin-left:10px;"></div>
</body>
</html>

JavaScript not working in Grails/GSP

I have the following JavaScript code:
<script type="text/javascript"><!--
​$(function () {
$('#add').click(function() {
$(this).before($('select:eq(0)').clone());
if ($('select').length > 5) $(this).hide();
});
});​
//-->
</script>
Here is the HTML code:
<select name="dropdown">
<option value="a">Apple</option>
<option value="b">Bee</option>
<option value="c">Cat</option>
<option value="d">Donkey</option>
<option value="e">Elephant</option>
</select>
Add
In the jsfiddle demo its working fine, but its not working on my gsp. Any idea or I am missing out something? Whenever I click on the "Add" it just display /# on my url.
The error message I managed to figure out through inspecting the element is as follows:
Uncaught SyntaxError: Unexpected token ILLEGAL
Screenshot
There are probably some illegal characters in the <script> block.
Did you copy/paste it from somewhere else? I would suggest you put cursor at the start and end of each line and delete all characters till you are sure there are no non-visible characters.
Alternatively delete the whole script block and retype it manually
Try uncommented version (w/o <!-- and //-->):
<script type="text/javascript">
​$(function () {
$('#add').click(function() {
$(this).before($('select:eq(0)').clone());
if ($('select').length > 5) $(this).hide();
});
});​
</script>
You can probably avoid issues like this if you just put the JavaScript in an external file.

Why is'nt this JavaScript function not redirecting to selected option value?

I have a JavaScript function:
function redirect(location) {
window.location.href=location;
}
Which I'm using like so:
<select onChange="redirect(this.options[this.selectedIndex].value)">
<option value="http://mysite.com/videos">One</option>
<option value="http://mysite.com/music">Two</option>
</select>
I'm expecting for it to redirect to the selected option value, but does'nt seem to do anything? - bare in mind im new to JavaScript.
Hope someone can help! :)
Try this:
<select onChange="redirect(this.value)">
try this
<script>
function redirect() {
var location=document.getElementById("i").value;
window.location.href=location;
}
</script>
<select onChange="redirect()" id="i">
<option value="http://mysite.com/videos">One</option>
<option value="http://mysite.com/music">Two</option>
</select>
Your code itself is functional (i tried).
Where have you placed the function definition?
Is there any other javascript code on the page?
In which browser are you testing this?
If you're running it in Firefox check the error console (Tools->error console).
I also noticed that Internet Explorer 8 blocks this javascript, I haD to check allow blocked content for this to work.
can be because location is a short way to call window.location, so just rename your input parameter - _location, newLocation, loc, whatever else.
UPDATE
Nope, this should work. Having only
<select onChange="redirect(this.options[this.selectedIndex].value)">
<option value="http://mysite.com/videos">One</option>
<option value="http://mysite.com/music">Two</option>
</select>
<script type="text/javascript">
function redirect(location) {
window.location.href=location;
}
</script>
on the page gave me the desired result, so the error may be somewhere around - just give us more code!

Categories