Select button with jQuery for casperjs - javascript

I want to select a button with casperjs, but my issue is that the button has changing IDsand classes. I can only "identify" the button, based on the text of a span 2 levels done:
<button class="changes-always" id="changes-always-too">
<div class="changes-always2">
<span class="changes-always3">Same text</span>
</div>
</button>
With jQuery I can select the button, by first selecting the span, because it always has the same content.
var span = $('span:contains("Same text")');
var button = span.parent().parent() // there is probably a nice way to do this
I got jQuery loaded by casperjs by including it as clientScripts, my issue is how to correctly get it working with the evaluate(function() as well as use the variables as selectors with casperjs (if that's even possible)
This is how far I got, but then I ran into problems with object and string issues.
casper.then(function() {
var items = this.evaluate(function () {
return $('span:contains("Some text")');
});
console.log(items);
});
Would be great, if someone could point me in the right direction, how to use jQuery as a selector and then let casperjs use it. Thanks many times in advance!

You can also use clickLabel() if the text is unique.
casper.clickLabel("Some text");
This should work for buttons, too.
Another option and still not with jquery should be getting the id's by text and if there are sometimes the same text, grab them out by the index:
...
var x = require('casper').selectXPath;
var buttonIDs;
// get button ID's with specific text by getElementsAttribute with xPath selector
buttonIDs = casper.getElementsAttribute(x("//button[contains(text(),'Some specific text')]"), 'id');
casper.then(function() {
casper.echo(buttonIDs);
});
casper.then(function() {
casper.click("button[id='" + buttonIDs[0] + "']");
});
...

Related

How can we update displayed text in cml:text or cml:textarea using javascript on crowdflower platform?

I am designing crowdsourcing interface on crowdflower platform, during design, I need cml:text or cml:textarea to accept workers's text input. Here is an example:
<cml:textarea label="my_name" id="my_id" validates="required" default="123456"/>
The default value shown in this text box is "123456", however, it will disappear after user clicking. What if I want to preload some content which can be reused (doesn't disappear) by the workers? I tried the following methods:
document.getElementById('my_id').html() = "678910";
document.getElementById('my_id').innerHTML ="678910";
document.getElementById('my_id').value = "678910";
document.getElementById('my_id').default = "678910";
document.getElementById('my_id').placeholder = "678910";
document.getElementByName('my_name').html() = "678910";
...
None of them works. Is it doable to update text in cml:text or cml:textarea on crowdflower platform?
I ran into this today! It seems that document.getElementById or its alternatives do not work for cml input tags. Here is a workaround using jQuery that worked for me. Put your cml:textarea in a div, then use find to get the inputs inside the parent div.
require(['jquery'], function($) {
var my_element = $("#parent_element_id").find("input")[0]; // first input element in the list
my_element.value = "678910";
});
Hope this helps!

Add a link to a form with jQuery (userscript) in Firefox

I'm trying to add a search link to an online form with a userscript using jQuery. I don't work too much in firefox and I feel like things that would normally work in chrome don't in ff 9/10 times for me. But anyway... this needs to be with ff.
I'm taking the text from a <p> element and creating a search url out of it (or trying to). Right now this is the function I'm trying that should be doing it... but it's doing nothing, not even any errors in console
$(function() {
var companyName = $('p')[7]; // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var mixRankUrl = $("<a></a>").innerHTML("Search Mixrank"); // Create an <a> element
mixRankUrl.href = 'https://mixrank.com/appstore/sdks?search=' + companyText; // Define the href of the a element
var sdkPara = $('label.control-label')[10]; // Where I want it to go
sdkPara.append(mixRankUrl); // Append the element
});
Also, whoever wrote the html uses hardly any ids, and most classes are assigned to 10 or more elements... so unless there's a better way, I'm sort of stuck using node selectors (which stay the same form to form).
The problem is that you try to use jQuery method on DOM element. Don't understand why you don't have any errors with your code.
For exemple : $('p')[7] return a DOM element while $('p').eq(7) return a JQuery object. So you can't use a jQuery method like text() on your DOM element. You need to deal with jQuery object.
For the same reason, you had a problem with the declaration of your label object and with the modification of the href attribute of your link.
Try like this :
$(function() {
var companyName = $('p').eq(7); // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var sdkPara = $('label.control-label').eq(10); // Where I want it to go
var mixRankUrl = $('<a>',{
text: 'Search Mixrank',
href: 'https://mixrank.com/appstore/sdks?search=' + companyText
}).appendTo(sdkPara); // Append the element
});

JQuery Cookies with dynamic div ID's

I hope you guys can give me a push in the right direction as this problem has been eating me up all day now..
What I'm basicly trying to accomplish is this. I have several div's on a page that can be collapsed independently from eachother with the use of a button. Every div has it's own specific ID, generated with a string of static text, and a numeric value based on a auto-incremented database-value. This ensures I never have two div's with the same ID on one page. To target each specific div with Javascript (jQuery) I use the following code:
http://jsfiddle.net/LU7QA/0/
This works really well and does what it's supposed to do. Only there is one problem. On every page frefresh, every div that was opened is closed. Everything resets, and that's why I want to use JQuery Cookies in this construction. Only problem is, I know how it works, but I can't get it to work in this specific construction as it has to deal with a completely unique ID every time and needs to store the values of that particular ID.
As seen here: http://jsfiddle.net/LU7QA/1/
I tried to fiddle around with it but I can't seem to get it working properly and I'm starting to lose my sight on the problem..
<div>
<button class="button_slide" value="1">Show hide</button>
</div>
<div id="slidingDiv_1" class="slidingDiv">Stuff</div>
<div>
<button class="button_slide" value="2">Show hide</button>
</div>
<div id="slidingDiv_2" class="slidingDiv">Stuff</div>
function initMenu() {
$(".slidingDiv").hide();
// Toggle Field
$(".button_slide").click(function(){
//alert($(this).val()); debugging purposes
var sliding_id = $(this).val();
div_sliding_id = '#slidingDiv_'+sliding_id;
$(div_sliding_id).next().slideToggle('slow', function() {
$.cookie(div_sliding_id, $(this).is(':hidden') ? "closed" : "open");
return false;
});
});
$('.button_slide').each(function() {
var sliding_id = $(this).val();
div_sliding_id = '#slidingDiv_'+sliding_id;
if ($.cookie(div_sliding_id) == "open") $(this).next().show();
});
}
jQuery(document).ready(function() {initMenu();});
May you have missed a dot on the last *button_slide* declaration?
Btw, look at https://code.google.com/p/sessionstorage/

How do you 'replace' numbers with 'x's' in jQuery with one button?

Does anyone know how to do replace multiple text by clicking a button with jQuery?
I've built a website that displays some text/data eg; "£100.00", but I what I need is to be able to 'replace' those monetary values with "£XXX.XX" with a 'Hide' button like you get on some banking websites. For example one web page has:
£100.00, £200.00, £130.00 etc etc..
...so when a user presses the Hide button, all of the numbers on the page turn to £XXX.XX. Ideally, the button should then display "Show" instead of "Hide" and switch back when toggled.
This is for a static dummy site, so no data base.
I suspect this is best handled with jQuery?
Thanks for your time,
D.
Case 1: Controlled Input
Assuming you can at least wrap all monetary values with something like this:
<span class="money-value">£200.00</span>
<span class="money-value">£300.50</span>
And that you can add button declared with:
<button id="secret-button">hide</button>
Then you could have some jQuery code doing this:
/**
* Simple search and replace version.
*/
$(function() {
$("#secret-button").click(function() {
$(".money-value").html($(".money-value").html().replace(/[0-9]/g,"X"));
});
});​
or a more advanced one with:
/**
* Complet version.
*
* 1) on button click, if asking to hide:
* 1.1) iterate over all entries, save their text, and replace it with markers
* 1.2) toggle the button's text to "show"
* 2) on button click, if asking to show:
* 2.1) iterate over all entries, restore previous text
* 2.2) clear the hidden store
* 2.3) toggle the button's text to "hide"
*/
$(function() {
var hiddenStore = [];
$("#secret-button").click(function() {
if ($(this).html() == "hide") {
$(".money-value").each(function () {
var text = $(this).html();
hiddenStore.push(text);
$(this).html(text.replace(/[0-9]/g,"X"));
});
$(this).html("show");
} else {
$(".money-value").each(function (i) {
var text = hiddenStore[i];
$(this).html(text);
});
hiddenStore = [];
$(this).html("hide");
}
});
});​
Complete solution is here: See here: http://jsfiddle.net/u79FV/
Notes:
this won't work for input field values
this assumes your text entries have been marked as shown above
Does what you want with the button's changing state.
Saves the values and puts them back.
Meant to work even if new fields are added dynamically.
Shankar Sangoli's answer uses a different way of saving the stored data, which you could as well consider (using the jQuery .data() method).
you may want to switch the button to an <input type="button" /> tag, in which case you'd use .val() instead of .html() to toggle its text.
Case 2: Uncontrolled Input
Assuming you don't have control over where the values may show up, then you need to do something a bit more complicated, which is to look in the whole page for something that would look like a currency format. I'd advise against it.
But, the jQuery Highlight plugin could be something to look at, as its code does something similar (in that it searches for pieces of code to modify), and you could then reuse some of solution 1 to make it fit your purpose.
That would be harder to design in a fool-proof fashion though.
You could use a regular expression:
var expression = /\d{1}/g;
var newString = myString.replace(expression,"X");
Then just dump newString into whatever control you need it to appear in.
Edit:
A jQuery idea for something like this would be to give all of the controls that have these numbers a common class identifier to make them easy to grab with the selector:
$(".numbers").each(function() {
$(this).text($(this).text().replace(/\d{1}/g, "X"));
}
... more readable ...
$(".numbers").each(function() {
var text = $(this).text();
var newText = text.replace(/\d{1}/g, "X");
$(this).text(newText);
}
If your markup is something like this you can try this.
<span>£1000.00</span><span class="showhide">Hide</span>
JS
$('.showhide').click(function(){
var $this = $(this);
var $prev = $this.prev();
if(!$prev.data('originalvalue')){
$prev.data('originalvalue', $prev.text());
}
if($this.text() == 'Hide'){
$this.prev().text($prev.data('originalvalue').replace(/\d{1}/g,"X"));
$this.text('Show');
}
else{
$prev.text($prev.data('originalvalue'));
$this.text('Hide');
}
});
In the above code I am basically storing the original value using jQuery data method within the span element itself which is used to display the actual value.
Once you click on Hide, get the previous span using prev() method and set its text with original value replacing all the numbers in it by X. Then change the link text from Hide to Show.
Next when you click on Show get the previous span using prev() method and set its text with the original value and change the link text from Show to Hide.
References: .prev(), .data()
$('#yourButton').click(function(){
var saveText = $('body').text();
$(this).data('oldText', saveText);
if ($(this).text() == "Hide"){
$('body').text($('body').text().replace(/\d{1}/, "X"));
$(this).text('Show');
}
else{
$('body').text($(this).data('oldText'));
$(this).text('Hide');
}
});
This is kind of a complicated problem actually. You will need to be able to save the state of the text when its in number form so you will be able to toggle back and forth. The above code is untested but hopefully it will give you an idea what you need to do.
function toggleMoney() {
$('.money').each(function() {
var $$ = $(this), t = $$.text();
$$.text($$.data('t') || t.replace(/\d/g, 'X')).data('t', t);
});
$('#toggleButton').text($('.money').text().match(/\d/) ? 'hide' : 'show');
}
http://jsfiddle.net/DF88B/2/

jQuery Clone inputs in two forms on the same page?

I have been trying to get two forms on the same page to work and the only issue i'm having is not getting the clone inputs to work, they seem to conflict with each other due to the div elements.
I have been using this tutorial as a guide:
http://www.9lessons.info/2009/06/submit-multiple-forms-jquery-ajax.html
Here is the code working with one form:
http://jsfiddle.net/yBdTA/
And this is what i want to achieve:
http://jsfiddle.net/c4Uce/
Notice when you click on the second 'Add More' link the first input clones rather than the second.
I know i could duplicate the jQuery function for the clone to match the second form:
$(function(){
var removeLink = ' <a class="remove" href="#" onclick="jQuery(this).parent().slideUp(function(){ jQuery(this).remove() }); return false">remove</a>';
jQuery('a.add').relCopy({ append: removeLink});
});
but i want this to be, how can i call it, dynamic? like the 9lessons guide, i can use PHP to create unique identifiers for the clone elements and want the jQuery to match the ID's,
Hope i made this clear.
Help appreciated.
U can try it , it work to multi form
http://jsfiddle.net/yBdTA/2/
(function($) {
function remove(){
$('.clone').each(function(i){
var input= $(this);
input.find('a.remove').click(function(){
input.remove();
});
});
}
$('form').each(function(i){
var form = $(this);
var removeLink = '<a class="remove" href="#">remove</a>';
var iputclone = form.find('p.clone').append(removeLink);
form.find('a.add').click(function(){
iputclone.clone().insertBefore(this);
remove();
});
});
})(jQuery);
Update :
iputclone.clone().insertBefore(this).find('.input').attr('value','');
//So easy, U can think a object when we start will is ifself, use it next, and next

Categories