JavaScript get recognize button to click - javascript

I am making a Chrome extension and I need this button to be clicked so how can I get the click to be recognized?
<button class="btn btn-lg btn-danger btn-bet" onclick="system.play.bet.red();">RED</button>
I tried var test= document.getElementsByClassName("btn btn-lg btn-black btn-bet");
test.click();
but it fails at the beginning.

Document.getElementsByClassName() returns an array-like object of all child elements which have all of the given class names. Unfortunately, it's not a true JS array. To work with it, you need to "Arrayify" it:
var testElements = document.getElementsByClassName('test');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
return testElement.nodeName === 'DIV';
});
In your case, this should work:
var test= document.getElementsByClassName("btn btn-lg btn-black btn-bet")[0];
test.click();

Related

How do i scrape the value of a element tag with puppeteer

<button class="button width-full button--primary" data-automation-id="signin-submit-btn" data-tl-id="signin-submit-btn" type="submit"><span class="button-wrapper">Sign in</span></button>
I need to scrape the value of "data-automation-id" with puppeteer which would be "signin-submit-btn". I know that I can grab the text by doing this
document.querySelector('button[class="button width-full button--primary"]').innerText;
but I need to know how to grab that value of "data-automation-id"
It looks like you're trying to capture the value of a Data Attribute. You can do it by referencing the button element's dataset like this:
let mybutton = document.querySelector('button[class="button width-full button--primary"]');
let autoId = mybutton.dataset.automationId;
console.log(autoId);
<button class="button width-full button--primary" data-automation-id="signin-submit-btn" data-tl-id="signin-submit-btn" type="submit"><span class="button-wrapper">Sign in</span></button>
Reference here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

How to concat #Url.Action with jquery syntax

I'm using bootstrap datatables to create a column displaying a link button to redirect to another view, the problem is that I'm getting syntax error from jquery and I'm not beign successful fixing it.
Here is the relevant part where I get the syntax error:
return '<button type="button"class="btn btn-default" onclick="location.href='#Url.Action("IncidentesDetalle", "ServiciosController", new { Id = "1" })'"><i class="fa fa-eye"></i></button>'
Any help will be appreciated.
I guess you should change your string to:
return '<button type="button" class="btn btn-default" onclick="location.href=\'#Url.Action("IncidentesDetalle", "ServiciosController", new { Id = "1" })\'"><i class="fa fa-eye"></i></button>'
Because in your original code single quotes just closed after href= and opened before ><i again. So part of the returning string like #Url.... became just invalid code. Hence the error.
Try this, it will work:
string path = "'#Url.Action('IncidentesDetalle', 'ServiciosController', new { Id = '1' })'";
return "<button type='button' class='btn btn-default' onclick='location.href="+path+"'><i class='fa fa-eye'></i></button>";

How to add variable to a href

I want to do something like this
var myname = req.session.name; <------- dynamic
<a href="/upload?name=" + myname class="btn btn-info btn-md">
But this does not work. So how do I properly pass in a dynamic variable to href? <a href="/upload?name=" + req.session.name class="btn btn-info btn-md"> does not work either
Actually there's no way to add a js variable strictly inside DOM. I would suggest you to apply an id attribute to that a element, refer to it and apply given variable as a new href attribute.
var elem = document.getElementById('a'),
myname = 'req.session.name'; //used it as a string, just for test cases
elem.href += myname;
console.log(elem.href);
<a id='a' href="/upload?name=" class="btn btn-info btn-md">Link</a>

Dynamic attribute value element locator in Protractor

When I add a new button with some value it gets dynamically added into DOM. Non-Angular HTML element for this button is:
<li class="ui-state-default droppable ui-sortable-handle" id="element_98" data-value="2519">
25.19 EUR
<button type="button" class="btn btn-default removeParent">
<span class="glyphicon glyphicon-remove" aria-hidden="true">
</span>
</button>
</li>
Once I remove this button I want to check it is not present anymore. Element that I'm searching for is data-value="2519"and this could be anything I set, like for example 2000, 1000, 500, 1050,...
In page object file I have tried to use the following:
this.newValueButtonIsNotPresent = function(item) {
newValueButton = browser.element(by.id("containerQUICK_ADD_POINTS")).all(by.css('[data-value="' + item + '"]'));
return newValueButton.not.isPresent();
};
And in spec file I call this function as follows:
var twentyEurosButtonAttributeValue = '2000';
describe("....
it ("...
expect(predefined.newValueButtonIsNotPresent(twentyEurosButtonAttributeValue)).toBeTruthy();
I know this is not correct, but how I can achieve something like that or is there another way?
Stupid me, I found a simple solution. Instead dynamically locating an element I located the first on the list, which is always the one, which was newly added and then checked if it's text does not match:
Page object file:
this.newValueButtonIsNotPresent = function() {
newValueButton = browser.element(by.id("containerQUICK_ADD_POINTS")).all(by.tagName('li')).first();
return newValueButton.getText();
};
Spec file:
// verify element 20.00 EUR is not present
predefined.newValueButtonIsNotPresent().then(function(value) {
expect(value).not.toEqual(twentyEurosText);
});

Pass Anonymous function that requires a parameter, to another function as an argument which will be assigned to an onclick

I have a function that I want to reuse throughout my program. Basically it's a bootstrap dialog box that has a confirm and a cancel button. I setup the helper function to accept two anonymous functions, one for the cancel and one for the confirm. I have everything working except I am not sure how to properly assign it to the onclick when building the html. I want to avoid using a global variable but this is the only way I was able to get this to work.
Custom function:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + cancelFunc + ')()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + confirmFunc + ')()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
I have to do, onclick = "(' + cancelFunc + ')()"> because if I do, onclick = "' + cancelFunc() + '"> it shows up as undefined. The current way will basically just print the anonymous function out and assign it to the onclick (almost as if I just typed out the anonymous function right at the onclick)
here is where I call the function:
var transTypeHolder;
$("input[name='transType']").click(function () {
var tabLength = $('#SNToAddList tbody tr').length;
if (tabLength == 0) {
var selection = $(this).attr("id");
serialAllowableCheck(selection);
resetSerialNumberCanvasAndHide();
$("#Location").val("");
$("#SerialNumber").val("");
}
else {
transTypeHolder = $(this).val();
var confirm = function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+transTypeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
var cancel = function () {};
confirmMessageBox("This is a test", cancel, confirm);
return false;
}
});
Is there a way to some how pass a variable to the anonymous function without using the global variable I have as, "transTypeHolder" ?
Before I get the, "Why are you doing it this way??" response; Javascript isn't a strong language of mine, as I am using ASP.NET MVC4. I haven't had a chance to sit down and learn Javascript in detail and I sort of picked it up and search what I need. So if there is a better way of tackling this, I am open for constructive criticism.
Don't make event handler assignments in HTML at all. If you want people to be able to supply their own functions for canceling and confirming use on:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default cancel" data-dismiss="modal">Cancel</button></td><td><button type="button" class="btn btn-default confirm" data-dismiss="modal">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$("#confirmMsgContainer").off('click', '.confirm').on('click', '.confirm', confirmFunc);
$("#confirmMsgContainer").off('click', '.cancel').on('click', '.cancel', cancelFunc);
$('#ConfirmMsgModal').modal('show');
}
Note that I've edited the HTML you're using to remove the onclicks and added a class to each button. I'm also using off to be sure any previously added event handlers are removed.
As far as passing the variable to the confirm function without using a global, use a closure:
var transTypeHolder = $(this).val();
var confirm = (function (typeHolder) {
return function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+typeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
})(transTypeHolder);
That tells JavaScript to create a function, which returns a function that does what you want it to do. That "function creator" takes in the variable you want to keep around, allowing it to be used elsewhere.
Now, I haven't tested this, so you may have some debugging in your future, but hopefully it gives you a jumping-off point.
You should be able to do it by having the function being acessible from global context under a generated name (which can be multiple if you have more than one instance of the box), like so:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
window['generatedCancelFunctionName1'] = cancelFunc;
window['generatedConfirmFunctionName1'] = confirmFunc;
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedCancelFunctionName1()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedConfirmFunctionName1()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
This way you are not obliged to expose the function code. You can also set an id attribute to the element and set a jquery click() function like in the second part (but you would need the html to be created before you set the click)

Categories