How to programmatically click on a button - maybe Angular? - javascript

I'm trying to click on a html button programmatically.
Looking at the page source - I see
<div class="submitBtns">
<button class="btn btn-primary primaryBtn" type="button">Search</button>
</div>
I don't think this is standard html - maybe an extension.
I can get to the button object - but calling obj.click() on it doesn't work.
The document also has this header - maybe that'll identify the document type - also has a lot of class names starting with ng- prefix.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
More info...this is a third party web-page and I'm injecting javascript into it.
I entered something into an INPUT field and then would like to simulate a button press.
Pure javascript.

Created a Sample Demo in Stackblitz for Reference
In Angular, we can get access to any HTML elements using #ViewChild &ElementRef. We also have to add an unique identifier by prefixing # in the HTML element that you want to access programmatically.
In HTML:
<button class="btn btn-primary primaryBtn" #search type="button">Search</button>
In TS:
import { Component, ViewChild, ElementRef } from '#angular/core';
.
.
export class YourComponent{
.
.
#ViewChild('search') search: ElementRef;
.
.
.
. // In your function
this.subContent.nativeElement.click();
}

JavaScript Option
If you want to do this with pure JavaScript you could add an ID to the button and do this:
document.getElementById("myButton").click();
jQuery Option
If I were to do this with jQuery I would write this piece of code:
<script>
$(document).ready(function() {
$('.submitBtns button').click();
});
</script>
Now the problem with this is that if you have several forms on your page it would click all of the buttons that are identified using the $('.submitBtns button').click(); selector. You could probably add an ID to this button if you have access to the code. And just change it to:
<script>
$(document).ready(function() {
$('#myButton').click();
});
</script>
If you require to simulate a click to trigger events related to the click, but not actually click the button, you could use $("#myButton").trigger("click");.

I am assuming that the only JavaScript you are familiar with is what you've read from a browser extension source. There are a few fundamental steps you neglected to mention. Moreover the possibilities you had mentioned were scattered to say the least:
I don't think this is standard html...
It's very standard and valid, flawless HTML.
I can get to the button object - but calling obj.click() on it doesn't work...
It isn't very clear as how obj was obtained from obj.click().
There are other scattered snippets of info... ng-* classes are Angular -- you are correct. The <meta> has no relevance to the issue at hand.
More info...this is a third party web-page and I'm injecting JavaScript into it.
I entered something into an INPUT field and then would like to simulate a button press.
This is normally not possible unless you have editing privileges to said third-party site. I believe browser extensions can do so but it doesn't actually edit the site itself it's just what the browser is rendering just for the user.
Demo
Note: details are commented in demo -- also, I loaded a Bootstrap 4 because I was bored. Bootstrap of course is not required and is purely optional.
// Reference the button
const btn = document.querySelector('.searchButton');
/*
- Register the click event to button
- When clicked the handler function flipStatus() is called
*/
btn.onclick = flipStatus;
/*
- Event handler function passes the event object
- event.target always references the elements that the user
clicked.
- .classList.toggle('active') will add class .active if the
button doesn't have it and remove class .active if the
button has the class .active
*/
function flipStatus(event) {
event.target.classList.toggle('active');
}
/*
- Programatically click the button -- if successful, the
button text should be: "Searching..."
- If clicked by user afterwards the button text should be:
"Search"
*/
btn.click();
.input-group.input-group {
width: 85vw;
margin: 15px auto;
}
.active.active::after {
content: 'ing...';
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" rel="stylesheet" crossorigin="anonymous">
<section class="input-group input-group-lg">
<input class="searchTerms form-control" type="search" placeholder="Enter search terms...">
<section class="input-group-append">
<button class="searchButton btn btn-lg btn-primary" type="submit">Search</button>
</section>
</section>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>

Related

Form submitting when clicking button that invokes javascript function to hide inputs [duplicate]

I have a form. Outside that form, I have a button. A simple button, like this:
<button>My Button</button>
Nevertheless, when I click it, it submits the form. Here's the code:
<form id="myform">
<label>Label
<input />
</label>
</form>
<button>My Button</button>
All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.
<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>
I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.
<button type="button">My Button</button>
Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):
The missing value default and invalid value default are the Submit
Button state.
return false; at the end of the onclick handler will do the job. However, it's be better to simply add type="button" to the <button> - that way it behaves properly even without any JavaScript.
By default, html buttons submit a form.
This is due to the fact that even buttons located outside of a form act as submitters (see the W3Schools website: http://www.w3schools.com/tags/att_button_form.asp)
In other words, the button type is "submit" by default
<button type="submit">Button Text</button>
Therefore an easy way to get around this is to use the button type.
<button type="button">Button Text</button>
Other options include returning false at the end of the onclick or any other handler for when the button is clicked, or to using an < input> tag instead
To find out more, check out the Mozilla Developer Network's information on buttons: https://developer.mozilla.org/en/docs/Web/HTML/Element/button
Dave Markle is correct. From W3School's website:
Always specify the type attribute for
the button. The default type for
Internet Explorer is "button", while
in other browsers (and in the W3C
specification) it is "submit".
In other words, the browser you're using is following W3C's specification.
Another option that worked for me was to add onsubmit="return false;" to the form tag.
<form onsubmit="return false;">
Semantically probably not as good a solution as the above methods of changing the button type, but seems to be an option if you just want a form element that won't submit.
It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)
Some reference material
For accessibility reason, I could not pull it off with multiple type=submit buttons. The only way to work natively with a form with multiple buttons but ONLY one can submit the form when hitting the Enter key is to ensure that only one of them is of type=submit while others are in other type such as type=button. By this way, you can benefit from the better user experience in dealing with a form on a browser in terms of keyboard support.
Late in the game, but you don't need ANY JavaScript code to use a button as a button. The default behavior is to submit the form, most people don't realize that. The type parameter has three options: submit (default), button and reset. The cool thing about this is if you add an event handler it will bypass submitting the form.
<button type="button">My Button</button>
There is also way to prevent doing the submit when clicking the button.
To achieve this, you have to use event.preventDefault() method.
document.querySelector("button#myButton").addEventListener("click", (event) => {
document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you submit this!<br>";
event.preventDefault();
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<form id="myform">
<label>Label
<input />
</label>
<button id="myButton">My Button</button>
</form>
<div id="output-box"></div>
<script src="src/script.js"></script>
</body>
</html>

Button not executing window.location

Im actually having a problem with html5 button in visualforce pages. I have a requirement where when i click on a button, it should redirect to a certain page (user do not want link). For some reason which i don't know, the function i'm executing do not work with HTML5 button (in fact the page only refresh but do not redirect) but when i use input of type button, the function is executed as expected.
I want to use the html5 button as there are some specific css already defined for button in the plugin im using. Find below codes for my button and javascript function :
<button class="butt" onclick="newContact()" >Nouveau</button>
<script type="text/javascript">
function newContact(){
window.location = "/apex/VFP01_NewContact";
}
</script>
What did I do wrong here, and what is the limitation of html5 button ?
Got to know the answer. In visualforce page, the html5 button execute a submit of my form. A way to prevent this, was to specify the attribute type="button".
You really have two options.
You could consider wrapping a element with an anchor tag that points to the URL that you want to target as seen below :
<!-- Target the "YourAction" action in your "YourController" controller -->
<a href='#Url.Action("YourAction","YourController")'>
<input type="Button" id="mybutton" name="url button" value="Next" />
</a>
or you could handle this purely through Javascript and perform your navigation that way :
<!-- The onclick event will trigger a Javascript call to navigate -->
<input type="Button" id="mybutton" name="url button" value="Next" onclick="window.location.href='#Url.Action("YourAction","YourController")';" />

jsFunction's data is undefined when event starter is inside the form

here is my situation:
I'd like to test if anyway to link the java bean and xhtml, so I use the richfaces, a4j:jsFunction to deal it.
I succeed -- in some limit, that the event starter have to fire OUTSIDE the form, so WEIRD !!
there are 3 parts in my code: xhtml、js、java
xhtml:
<button id="succeed" onclick="showMessage()"> succeed_test </button>
<!-- this is the succeeded button -->
<h:form id="form1" prependId="true" >
<button id="fail" onclick="showMessage()"> fail_test </button>
<!-- this is the failed button -->
<a4j:jsFunction
name="showMessage"
data="#{javaBeanTest.showThings()}"
oncomplete="presentData(data)"
immediate="true" />
</h:form>
js:
function presentData(data){
alert(data);
}
java:
#Name("javaBeanTest")
public class JavaBeanTest implements Serializable{
public boolean showThings(){
System.out.println("--JavaBeanTest.showThings()");
return true;
}
}
when clicking the 「succeed_test」 button, I got a 「true」 alert and 「--JavaBeanTest.showThings()」 on console, but only got 「undefined」 alert and 「--JavaBeanTest.showThings()」 on console while clicking 「fail_test」 button.
obviously the DIFFERENCE is of inside or outside the form .....
CONFUSED !!!! PLEASE !!!
ps.in my richfaces version, it works with 「data」 instead of 「event.data」, should be 3.x
JDK 1.6
JBDS 4.1.0GA
seam 2.2
JSF 1.2
In your case HTML button submits the form if it is inside of one (behavior may differ from browser to browser). You need to specify explicitly the button type or prevent default submit behavior, e.g.:
<button id="fail" type="button" onclick="showMessage()">does not fail anymore</button>
or
<button id="fail" onclick="showMessage(); return false;">does not fail anymore</button>
There is a recommendation by W3C to always specify the type attribute:
Tip: Always specify the type attribute for the element.
Different browsers may use different default types for the
element.
Refer to: http://www.w3schools.com/tags/att_button_type.asp

Changes made to HTML output (ASP.Net) using JavaScript immediately undone

I have a page on which a list of properties is displayed (i.e houses). This list is made up using CSS. So I've built a second CSS class, which makes the properties/houses align properly in 2 columns. Until now I did this by pressing a button, posting back, and outputting different html (basicly the same, but with other Css class references).
Now I found this question on SO and I implemented a basic scenario. A div with the class "yellow" is written to the html page, and a button changes this class to "red". This happens, but the div immediately changes back to class "yellow".
I'm a very very beginner in JS but not a beginning programmer. This would be a great addition to my site, but I can't find a proper answer. I apologize if this question is redundant.
<script type="text/javascript">
function changeView() {
document.getElementById("box").className = " red";
}
Grtz, thanks in advance, Christophe,
By default a button element is of type 'submit' - which will cause your browser to post back to the server.
Try changing the type to button instead.
<input type="button" ....
More info on the difference here... Difference between <input type='button' /> and <input type='submit' />
If your button causes a postback (possibly a server control with an asp: tag), the javascript changes you made will be lost as by default an asp button submits a page to the server as a result of which your page reloads.
If all you need to change the class of a div make it a simple html button like
<input type="button" onclick="changeView()" value="Change" />

Creating fancy HTML buttons with images

I'm using a customized <img> element as a button on my site (with onclick for the form submit). The reason being I want the element to display one image when the button is up and another for when the button is down. I'm using onmousedown and onmouseup for that.
This is an AJAX-based site, and the submit is also AJAX-y. It is safe to assume that javascript is on.
Forms are being submitted by AJAX (via Prototype), so the regular <input type=button> is out of the question as it would cause a submit + page refresh (also, to my best understanding, it cannot be fully customized using images).
My question is: Should I expect any difficulties with the approach, and is there a better/easier way of generating customized buttons?
I am interested in usability and compatability issues: e.g. Accessability features (such as tab index) vs. support on all browsers (such as IE6).
Use a <button> or <input type="submit"/> with CSS background styles applied.
<html>
<head>
<style type="text/css">
.hoverable {
background: #FFFFFF url(path/to/background.png) top left no-repeat;
height: 32px; /* height and width match your background.png dimensions */
width: 64px;
}
.hoverable:hover {
background-image: url(path/to/background-hover.png);
}
</style>
</head>
<body>
<form>
...
<button type="submit" class="hoverable"></button>
<!-- or <input type="submit" class="hoverable"/> -->
<!-- or <button type="button" class="hoverable"></button> if you don't want submit behavior -->
</form>
</body>
</html>
Using a form input makes the most sense semantically, especially with your concerns about accessibility. People using accessibility tools probably aren't expecting to encounter a <div> or <img> and be expected to perform an input event on it (I could be wrong, I'm not entirely familiar with how such tools work).
The fact that the application is dynamic/ajaxy/etc. shouldn't be a barrier to you using the appropriate markup elements and using CSS to style it appropriately.
Edit:
Regarding the <input> not working: if you return false from whatever gets invoked when the button is clicked, it won't continue execution (i.e. submit the form). Example:
<button type="submit" onclick="handleClick();"></button>
...
function handleClick() {
// ajax call
return false;
}
On top of that, using a <button type="button"></button> shouldn't even submit the form at all. Some browsers default the type to "submit", so you'd want to explicitly define type="button" to make sure it's not treated as a submit.
Obviously, this will be different than your prototype code, but you get the picture; the gist of it is that the event handler needs to return false. And <button>/<input> can be styled just as well as an <img> or <div>.
You can improve these with CSS sprites, here's a good article explaining it: http://www.jaisenmathai.com/blog/2008/04/03/extremely-efficient-image-rollovers-using-css-sprites-and-no-javascript/
It's a css-only solution that uses 1 image for both the up & down states.

Categories

Resources