So, I've created a button element with javascript. All seems to have went quite well for that.
var btn = document.createElement("button");
btn.setAttribute('class', 'btn btn-primary');
btn.setAttribute('style', 'float: right; display: inline-block; margin-top: 3px; margin-right: 15px;');
btn.innerHTML = 'Remove Attachment';
btn.setAttribute('onclick', 'removeAttachment(' + i + ')');
Problem I'm encountering is that when I click the button, it doesn't call the removeAttachment function, but rather seems like it's submitting the page form. Am I missing something with making the button only be bound to the onclick event and not tied to the form?
All I'm really wanting to do is operate on some DOM elements rather than issue a post or get. Any help would be really appreciated. Thanks!
Since you are creating the button using javascript there really isn't a need to add the javascript to the html. So, use addEventListener
instead to add a click event to the javascript instead of the HTML.
To prevent the form from submitting, use preventDefault()
btn.addEventListener('click', (e) => {
e.preventDefault()
removeAttachment(i)
});
Another option is to set the type of button instead of preventDefault()
:
btn.type = 'button'
Here is a working example with preventDefault()
var i = 0;
var btn = document.createElement("button");
btn.setAttribute('class', 'btn btn-primary');
btn.setAttribute('style', 'float: right; display: inline-block; margin-top: 3px; margin-right: 15px;');
btn.innerHTML = 'Remove Attachment';
btn.addEventListener('click', (e) => {
e.preventDefault()
removeAttachment(i)
});
document.querySelector('form').appendChild(btn)
function removeAttachment(i) {
console.log('Remove Attachment:', i)
}
<form action="" method="post">
</form>
Here is a working example using type="button"
var i = 0;
var btn = document.createElement("button");
btn.setAttribute('class', 'btn btn-primary');
btn.setAttribute('style', 'float: right; display: inline-block; margin-top: 3px; margin-right: 15px;');
btn.innerHTML = 'Remove Attachment';
btn.type = 'button'
btn.addEventListener('click', (e) => removeAttachment(i));
document.querySelector('form').appendChild(btn)
function removeAttachment(i) {
console.log('Remove Attachment:', i)
}
<form action="" method="post">
</form>