Click visible button in protractor? - javascript

I have a page which looks something like this. It's a wizard with steps. Depending on the "step" scope variable, a different part of the wizard is shown:
<div ng-show="step == 'first'">
<button>Next</button>
</div>
<div ng-show="step == 'second'">
<button>Next</button>
</div>
<div ng-show="step == 'third'">
<button>Next</button>
</div>
To click the next button I run into problems though. Because there are three of them. The following code returns all of them:
var next = element(by.buttonText('Next'));
And doing:
next.click();
will click the first one. How can I find the visible button only, and click that one?

First I was confused by isDisplayed returning a promise. This function is what I came up with:
function clickButton(text) {
var buttons = element.all(by.buttonText(text));
buttons.each(function(button) {
button.isDisplayed().then(function(isVisible) {
if (isVisible) {
button.click();
}
})
});
}
Which can be used like this:
clickButton('next');

Here is a bit more cleaner version in terms of understanding that uses filter() to filter a single visible button and click it:
function clickButton(text) {
var buttons = element.all(by.buttonText(text));
var visibleButton = buttons.filter(function(button) {
return button.isDisplayed().then(function(isVisible) {
return isVisible;
});
}).first();
visibleButton.click();
}
As a bonus, you'll also get an error if there are no visible buttons found, as opposed to your current approach which would not fail in this case.

You should be able to chain the elements to specify which next button you want to click.
var firstNext = element(by.css('div[ng-show="step == \'first\'"]')).element(by.buttonText('Next'));
var secondNext = element(by.css('div[ng-show="step == \'second\'"]')).element(by.buttonText('Next'));
var thirdNext = element(by.css('div[ng-show="step == \'third\'"]')).element(by.buttonText('Next'));
// We are on the first step
firstNext.click();
// We are on the second step
secondNext.click();
// We are on the third step
thirdNext.click();

Related

ng-click function only works the first time

I have setup a simple ng-click function on a div that once clicked should change the color of a different div. Simple enough except it only works on first time I click the div...then nothing :( I am just trying to get functionality for a toggle function which I will use all over for different things.
HTML: (this code is part of a loop)
<img ng-click="changer()" src="{{m.img}}" style="width:100%;min-height:480px;max-height:600px;z-index:1;">
...
<div style="background-color:{{colorblur}}; width:100px;height:100px;"></div>
Controller:
$scope.colorblur="red";
$scope.changer = function () {
if($scope.colorblur="red"){
$scope.colorblur="yellow";
}
else{
$scope.colorblur="red";
}
}
Thanks in advance :)
change
if($scope.colorblur="red"){..
to
if($scope.colorblur === "red"){...
use === instead of =
if($scope.colorblur === "red"){

$(this) acts like both event and <div>

I'm a long-time procedural programmer now assigned to a web-app and studying jquery from a book. The exercise is to run some code on one div selected from a row of 4 <div>s using .each(). I attempted to store the div object that was clicked, then match it as the .each looped thru the 4 divs.
My following code works after trial and error, but the same $(this) seems to sometimes point to a div object, and sometimes to an event object.
How do you explain that behavior?
I understand that .context is deprecated. I tried .target but that didn't seem to work. Is there something else that I should be using?
My primary interest is to understand what is going on (question 1), so if you can provide an explanation and not just an alternative solution (question 2), I'd really appreciate it. Thank you in advance. Here are the code snippets:
<body>
<div id="header">
<h2>Jump for Joy Sale</h2>
</div>
<div id="main">
<div class="guess_box"><img src="images/jump1.jpg"/></div>
<div class="guess_box"><img src="images/jump2.jpg"/></div>
<div class="guess_box"><img src="images/jump3.jpg"/></div>
<div class="guess_box"><img src="images/jump4.jpg"/></div>
</div>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_script.js"></script>
</body>
Jscript
$(document).ready(function()
{
$(".guess_box").click(checkForCode);
function checkForCode()
{
var code_box = 2;
var discount_code = getRandomNum(1,100);
var clicked = $(this); // debugger says clicked is an event object
var iteration = 0;
$(".guess_box").each(function()
{
if ($(this).context === $(clicked).context) //act like event objs
{
if (iteration === code_box)
{
// clicked on correct box
$(this).addClass("discount"); //same $(this) acts like <div>
discount_msg = "<p>Your Code: CODE"+ discount_code +"</p>";
return(false);
}
}
else
{
if (iteration === code_box)
{
// if wrong box clicked, highlight the right one
$(this).addClass("no_discount");
discount_msg = "<p>Sorry, no discount this time</p>";
return(false);
}
}
iteration += 1;
});
$(".guess_box").unbind();
$(this).append(discount_msg); // don't worry about this line
} //checkForCode
}); //ready
The context of this depends on where and how it's used. if your function is called by an an event it will refer to the target of the event, otherwise it will refer to the object being called upon.
What youre seeing in your console is not this, or an event object, it's a jQuery object. If you want to inspect this you need to remove the jQuery wrapper function.
console.log(this);
Event example..
<div>click me</div>
$("div").click(function(){
// referring to the div itself
$(this).text("you clicked me");
// Note you can do it without jQuery as well
// this.innerHTML = "you clicked me";
});
object example
function something(){
this.something = "something";
this.doAThing = function(){
this.something = "something new";
}
}
var thing = new something();
thing.doAThing();
alert(thing.something);
Thanks to those that responded. As Pamblam indicated, I was confusing this and $(this). I replaced 2 lines in my code and it makes more sense:
clicked = $(this) becomes clicked = this
if ($(this).context === $(clicked).context) becomes
if (this === clicked)

Do I need to create multiple functions for multiple actions or can they all be housed in the same function?

I'm working on a script to simulate a page change in a Questionnaire I'm building. I figured maybe I could use a bunch of "if" statements to house all the logic but it's not working right, before I go and create separate functions I'd like to know if it's possible to put them all in one single function.
So far this is the script
function pageChange(){
var chng1 = document.getElementById("p1next");
var chng2a = document.getElementById("p2back");
var chng2b = document.getElementById("p2next");
var chng3a = document.getElementById("p3back");
var chng3b = document.getElementById("p3next");
var pg1 = document.getElementById("page01");
var pg2 = document.getElementById("page02");
var pg3 = document.getElementById("page03");
if (chng1.click){
pg1.style.display="none";
pg2.style.display="block";
}
if (chng2a.click){
pg1.style.display="block";
pg2.style.display="none";
}
the "p1next, p2back, p2next etc." are IDs I gave the buttons on the pages, which I have in DIVs that I respectively named "page01, page02, page03 etc."
Without the 2nd if statement the script works exactly how I want it, it changes the display for "page01" to none and the div for "page02" to block. When I add the second if statement it doesn't work.
The reason I want to do it like this rather than making actual pages is because I don't want the data to get lost when they load another page. Am I on the right track or do I need to create a new function for each page?
Not exactly on the right track, you should use onclick events, instead of if (x.click) like this:
var chng1 = document.getElementById("p1next");
var pg1 = document.getElementById("page01");
var pg2 = document.getElementById("page02");
// Events
chng1.onclick = function(){
pg1.style.display="none";
pg2.style.display="block";
};
This will save your function until the element is clicked and then execute that function. In your case, it is executed on page load, and at that moment the user is not clicking anything.
Why not try something like this:
HTML:
<div class="page" data-pg="1">...</div>
<div class="page" data-pg="2">...</div>
<div class="page" data-pg="3">...</div>
<input id="btnPrev" type="button" value="Prev" />
<input id="btnNext" type="button" value="Next" />
jQuery:
var pageNum = 1;
$(document).ready(function () {
$("#btnPrev").on("click", function () { ChangePage(-1); });
$("#btnNext").on("click", function () { ChangePage(1); });
ChangePage(0);
});
function ChangePage(p) {
$(".page").hide();
pageNum += p;
$(".page[data-pg='" + p + "']").show();
$("#btnPrev").removeAttr("disabled");
$("#btnNext").removeAttr("disabled");
if (pageNum === 1) $("#btnPrev").attr("disabled", "disabled");
if (pageNum === $(".page").length) $("#btnNext").attr("disabled", "disabled");
}
That way you can easily grow your number of pages without changing the script. My apologies by the way for doing this in jQuery.
Update:
Have a lot of time on my hands today and have not coded for while using vanilla Javascript. Here's the version of the code using plain js: https://jsfiddle.net/hhnbz9p2/

Javascript function changeImage: Issues using variables for getElementById or getElementsByName

I'm having some trouble getting my code to do what I want. I have multiple sections that I have set to toggle show/hide, and it functions correctly. However, I'm now trying to switch the images to where instead of always being static with "More," I'd like it to switch to "Less" when it's expanded.
It does work... but only for the first one. If I press the buttons on any of the others, it only changes just the first one. You can see the page here:
http://jfaq.us
I've tried several different solutions with variables, but I can't seem to get it to work.
Help? Thanks in advance!
function changeImage() {
if (document.getElementById("moreorless").src == "http://jfaq.us/more.png")
{
document.getElementById("moreorless").src = "http://jfaq.us/less.png";
}
else
{
document.getElementById("moreorless").src = "http://jfaq.us/more.png";
}
}
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none")
{
e.style.display="block"
}
else{
e.style.display="none"
}
return true;
}
<div>
Guestbook
<div>
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para3')" >
</div>
<div id="para3" style="display:none">
This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.
</div>
About
<div>
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para2')" >
</div>
<div id="para2" style="display:none">
This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.
</div>
</div>
The id attribute must be unique. That's why it's not working. Also, it's not a good idea to use inline event handlers like you are doing, you should register event handlers using addEventListener instead.
Without changing all your code, one thing you can do is pass a reference to the currently clicked element to the changeImage function.
function changeImage(el) {
var moreUrl = 'http://jfaq.us/more.png';
el.src = el.src === moreUrl? 'http://jfaq.us/less.png' : moreUrl;
}
Then change the inline handler for onclick="changeImage(this);"
You are using same Id for all inputs. This is causing the problem.
Give every element a unique Id.
If you want to perform grp operation use jquery class.
That's because you use the same id for the both images, and getElementById apparently takes the first one.
Here is the updated code:
html:
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage.call(this);return toggleMe('para3')" >
script:
// inside the event handler 'this' refers to the element clicked
function changeImage() {
if (this.src == "http://jfaq.us/more.png") {
this.src = "http://jfaq.us/less.png";
} else {
this.src = "http://jfaq.us/more.png";
}
}
check this
http://jsfiddle.net/Asb5A/3/
function changeImage(ele) {
if (ele.src == "http://jfaq.us/more.png")
{
ele.src = "http://jfaq.us/less.png";
}
else
{
ele.src = "http://jfaq.us/more.png";
}
}
<input type="image" src="http://jfaq.us/more.png" onclick="changeImage(this);return toggleMe('para3')" >

Get numerical value from parent with id like 'post-1' and use it in jQuery function

I'm trying to figure out the following.
I have following jQuery code:
var as = "";
var bPlay = 0;
audiojs.events.ready(function() {
as = audiojs.createAll();
$(".audiojs .play-pause").click(function() {
var e = $(this).parents(".audiojs").index(".audiojs");
$.each(as, function(t, n) {
if (t != e && as[t].playing) {
as[t].pause()
}
})
bPlay = !bPlay;
if (bPlay == 1) {
$(".bar").each(function(i) {
fluctuate($(this));
});
} else {
$(".bar").stop();
}
})
});
In a nutshell it preforms list of things when someone clicks particular .audiojs instance on a page. 1) checks if there is any other instance playing, if there is pauses it. And if it is playing applies fluctuate function to elements on a page that have class="bar". This is the issue! I don't want to apply it to all .bar's on a page, but only to a specific group that is associated with particular .audiojs instance (the one that is being clicked and is playing).
I thought of the following solution. Each .audiojs instance is inside a div tag that has id like "post-1", "post-2" etc.. where numerical value is post id from database. I can add this numerical id to bar, so it would be like bar-1, bar-2 etc... However after this I'm having issues.
For javascript to work I need to retrieve numerical value from "post-[id]" associated with audiojs instance that is being clicked and than store it somehow, so I can use it like this afterwards
bPlay = !bPlay;
if (bPlay == 1) {
$(".bar-[value retrieved from post-...]").each(function(i) {
fluctuate($(this));
});
} else {
$(".bar-[value retrieved from post...]").stop();
}
Could someone explain to me how it can be achieved?
Honestly, the easiest way would be to stick it in a custom data-* attribute on the <div id="post-X"> element, like so:
<div id="post-1" data-bar="bar-1">...</div>
Then, you said your .audiojs element is inside that <div>, so just go from this inside the event handler to that <div> element (using .closest()) and get the value of it:
var barId = $(this).closest('[id^="post-"]').attr('data-bar');
Then when you need to use it:
$("." + barId).each(function(i) {
fluctuate($(this));
});
Instead of embedding the value in a class or ID, use a data-* attribute:
<div class="audiojs" data-fluctuate-target="bar-1">
<button type="button" class="play-pause">
<!-- ... -->
</button>
</div>
<div class="bar-1">
<!-- ... -->
</div>
In your click event handler, use the following to fluctuate or stop the correct elements:
var fluctuateClass = $(this).closest('.audiojs').attr('data-fluctuate-target');
$('.' + fluctuateClass).each(function () {
if (bPlay == 1) {
fluctuate($(this));
} else {
$(this).stop();
}
});

Categories

Resources