I notice that on modern browsers such as Chrome, when placing one text field and one button within a form element. If enter key is pressed from the text field, the button will get clicked with a mouse click event issued by browser.
Since the only button within the form isn't used for submitting the form, is there a way for that button to only accept user click instead of browser click?
<form action="javascript:void(0)">
<input type="text"/>
<button id="btn">Submit</button>
</form>
var btn = document.getElementById("btn");
btn.onclick = function() {
alert("button clicked");
}
You need to assign the "type" attribute to the "button" element. Like below:
var btn = document.getElementById("btn"); btn.onclick = function(e) { e.preventDefault(); debugger; alert(123); }
<form action="javascript:void(0)"> <input type="text"/> <button type="button" id="btn">Submit</button> </form>
That doesn't happen because it's the only button in the form, but rather because it's a submit
button.
<button>
elements default to type="submit"
when associated with a form.
To disable that behavior, set the type
attribute to button
manually:
<button id="btn" type="button">Submit</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.