I try to update this jquery script in pure js (with bootstrap 5). The goal is to not allow someone to click twice on the payment button. Sorry I am not very strong in js.
My goal is to have the same reaction that the jquery script.
I tried to follow the process on this page :
Disabling a button in vanilla JavaScript and in jQuery
Thank you
My current script
<form name="checkout_confirmation" action="http://............/Process" method="post" id="checkout_confirmation" role="form" onsubmit="return checkCheckBox(this)"><section class="checkout_confirmation" id="checkout_confirmation">
div class="text-end" id="process_button" class="processButton">
<button type="submit" data-button="payNow" class="btn btn-success">Confirmer la commande avec paiement</button> </div>
</div>
</form>
<script>
$('form[name="checkout_confirmation"]').submit(function() {
$('form[name="checkout_confirmation"] button[data-button="payNow"]').html('Confirm the payment').prop('disabled', true);
});
</script>
Now the script update
<script>
var button = document.getElementById('checkout_confirmation');
button.addEventListener('submit', function() {
alert('Confirm the payment');
});
button.disabled = false;
button.click(); // No output
button.prop("disabled", true);
</script>
setAttribute can be used in JavaScript to set the attribute of the button as disabled.
Element.setAttribute("disabled", true);
This can be used to disabled the button.
So when someone clicked on the submit button, you can disable the button till the data is processed.
Check the below demo code:
const btn = document.getElementById("submit-data");
btn.addEventListener("click", submitForm);
function submitForm(){
btn.setAttribute("disabled", true);
btn.innerText = "Submitting..";
let userName = document.getElementById("user-name").value;
console.log("Name: ", userName);
setTimeout(() => {
btn.removeAttribute("disabled");
btn.innerText = "Submit";
}, 3000);
}
<form type="POST">
<label for="user-name">Full Name</label>
<input type="text" id="user-name" placeholder="Your Full Name" />
<br /><br /><br />
<button id="submit-data">Submit</button>
</form>
You have two problems:
Submit events fire on form elements, not button elements.
getElementById gets an element by its id and neither your button nor your form has an id. (See this question).
Could you not use e.preventDefault() to stop the default behaviour of the button being pressed?
More can be read here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Related
I have stopped refreshing the page by using e.preventDefault but the code is not executing as I want.
Here is the most important part
Here is the complete code
<div class="page">
<form action="">
<input type="text" id="input-field" />
<input type="submit" value="Add Task" />
</form>
<section class="tasks" id="tasks"></section>
</div>
//here variables
let submitt =document.querySelector("input[type='submit']")
let val =document.getElementById("input-field");
let clickk =document.getElementById("cli");
let divv = document.createElement("div");
divv.title = val.value;
divv.id = "iddd";
divv.className ="classone";
//append the text in the div
divv.append(val.value)
divv.style.cssText = "width:100px;height:50px;background:red;color:white;"
let sec = document.getElementById("tasks")
//func to create new div
submitt.addEventListener("submit",function(e){
sec.append(divv)
e.preventDefault();
})
hi,sounds like the submit button does not trigger the submit event as only the form can listen submit event
you should listen submit on form, or use click
submitt.addEventListener("click",function(e){
sec.append(divv)
e.preventDefault();
})
<script>
function disableButton() {
var button = document.getElementById('accept');
button.disabled = true;
return true;
}
</script>
<form class="form-horizontal" name ="reg" method="post" action="" onSubmit="return disableButton()"/>
<button class="btn btn-info" name="sub" type="submit" id="accept">
<i class="icon-ok bigger-150"></i>
Submit
</button
When I hit submit button button is disbled but form is not submitted
Kindly any one please do favour
Instead of trying to add functions to your forms, you can simply catch your form submit, disable the button and allow it continue afterwards:
HTML Part:
<form class="form-horizontal" id="reg" name="reg" method="post" action="" />
Javascript Part:
<script type="text/javascript">
var form = document.getElementById('reg');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
function processForm(e) {
if (e.preventDefault) e.preventDefault();
var button = document.getElementById('accept');
button.disabled = true;
return true;
}
</script>
If you wish to test it out, change above to return false;. This will disable the form submit and only disable the button.
Try the following:
<?php echo "<pre>";var_dump($_POST); echo "</pre>";?>
<script>
function disableSubmit() {
var button = document.getElementById('accept');
button.disabled = true;
myNiceForm.submit();
}
</script>
<form class="form-horizontal" id="myNiceForm" name ="reg" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="myTestText"/>
<input id="accept" type="submit" onclick="disableButton()"/>
</form>
Things to consider:
If you want your HTML form to be posted, it needs to have a proper
value for the action attribute.
The button with the id of accept doesn't cause the form to be
posted, you also don't have any client-side script to do so, and it's
not a good practice, so a submit button has been added to the form.
When you click the submit button, the disableSubmit() function
invokes, and disables the button, and finally submits the form
programmatically, however, it's not necessary.
Your function does not follow proper syntax. But other than that there's no real reason to return true or false...
var acceptor = document.getElementById("accept");
acceptor.addEventListener("click", toggleButton);
function toggleButton() {
acceptor.disabled = "disabled"
}
<button class="btn btn-info" name="sub" type="submit" id="accept">
<i class="icon-ok bigger-150"></i>
Submit
</button>
Also, your button tag is not closed <button> </button>...
You can simply define the attribute are defined as a boolean true or false, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled".
You may want to consider a function buttonToggler... so you can later switch it back easily (although I'm not sure this will help you...
Also... have the script at the bottom of the body rather than the top in-case of a preloading issue (this is not a foolproof solution to the problem where the JS loads faster than the HTML).
<script type="text/javascript">
function toggleButton() {
var acceptor = document.getElementById('accept');
if acceptor.disabled === true{
acceptor.disabled=false;
} else {
acceptor.setAttribute('disabled', 'disabled');
}
</script>
Try that.
Just a very brief explanation of what a part of my code does:
I have two buttons that do different things.
One of them lets the user search through the table/database for whatever he/she wants to search for
The other lets the user insert things into the database
WHAT I'M TRYING TO DO:
I'm trying to check to see which button the user clicked on so that the appropriate code will be executed.
I've been looking around and pretty much everywhere I go, people are suggesting to use isset(), but it's not working for me. Perhaps I don't fully understand what isset() does, but doesn't it basically check to see whether a variable is set?
Here's my code:
<script>
function show(x, y){
<!-- Do something -->
}
</script>
<form>
<button name = "sButton" type = "button" onclick = 'show("searchForm", "insertForm");'>Perform Search</button>
<button name = "iButton" type = "button" onclick = 'show("insertForm", "searchForm");'>Insert Data</button>
</form>
<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">
<!-- Do something -->
</form>
<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">
<!-- Do something -->
</form>
<!-- This is the test2.php page -->
if(isset($_POST['sButton'])){
<!-- Do something -->
}
else{
<!-- Do something -->
}
To test it, I had the if statement print "Checked" and the else print "Not checked". When I run my code, it prints "Not checked". What am I doing wrong and what should I be doing?
Thanks in advance!
You are not passing your buttons sButton or iButton into test2.php because your second and third form do not have them as input. Only inputs inside each particular form will be submitted. and your form that has the buttons has no action only the buttons call the JS function.
What I suggest you do is to add hidden fields for each form that you are submitting to test2.php as follows:
<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">
<input type="hidden" name = "sButton" value="sButton" />
<!-- Do something -->
</form>
<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">
<input type="hidden" name = "iButton" value="iButton" />
<!-- Do something -->
</form>
This way your test2.php should work.
Add an
<input type="hidden" name="sButton" />
into the search form, and a
<input type="hidden" name="iButton" />
into the insert form.
After that. You need to submit the (selected) form in the show(...) javascript function
Use this:
onclick = 'show(this.name, "searchForm", "insertForm");'
Example:
<button name = "sButton" type = "button" onclick = 'show(this.name, "searchForm", "insertForm");'>Perform Search</button>
function show(name, x, y){
alert(name);
if(name === "sButton"){
do this....
}
}
Output:
sButton
DEMO
http://codepen.io/tuga/pen/RPNaXY
I'm not sure what you're trying to do, but I don't see why the buttons are in a form at all. Consider attaching the listeners dynamically, adding a name or ID to the buttons so you can tell which one was clicked then hide or show the forms depending on which was clicked:
// The buttons don't seem to need to be in a form, so use some other
// container so you don't need to worry about a useless form being
// submitted
<div id="buttonContainer">
<button id="searchButton">Perform search</button>
<button id="insertButton">Insert data</button>
</div>
// Forms for testing
<form id="searchForm"><input value="search"></form>
<form id="insertForm"><input value="insert"></form>
and the code:
<script>
// Hide and show forms depending on which button was clicked using the
// button's ID
function showForm(event) {
// If the search button was clicked, show the search form and hide the
// input form
if (/search/.test(this.id)) {
document.getElementById('searchForm').style.display = '';
document.getElementById('insertForm').style.display = 'none';
// If the insert button was clicked, do the opposite
} else {
document.getElementById('searchForm').style.display = 'none';
document.getElementById('insertForm').style.display = '';
}
}
// Attach listeners to the buttons
window.onload = function() {
Array.prototype.forEach.call(document.querySelectorAll('#searchButton, #insertButton'),
function(button) {
button.addEventListener('click', showForm, false);
}
);
// Hide the forms
Array.prototype.forEach.call(document.querySelectorAll('#searchForm, #insertForm'),
function(form) {
form.style.display = 'none';
}
);
}
</script>
I'm creating a simple website and a html page on it which contains a table that shows products. I load this table using AJAX and it work properly. Here is a screenshot:
Under the table I have buttons which perform CRUD operations using AJAX.
They communicate to a php script on a server outside of my domain using GET method.
When I click on Add product it opens a form with a button that whose onclick event calls a function which adds a product using AJAX. But, when I click, the whole page reloads and the product is not added. If I put the value that says wheter the call is async to false, it works as intended and the product is added to the table, however that is not the point of AJAX.
This is my code for adding a product(delete and update are almost the same).
<div id="addProductPopup">
<div id="popupContact">
<form id="form" method="post" name="form">
<img id="close" src="/servis/Resursi/Slike/close.png" onclick ="hide('addProductPopup');">
<h2>Dodavanje proizvoda</h2>
<hr>
<input id="name" name="naziv" placeholder="Naziv proizvoda" type="text" required>
<input id="kolicina" name="kolicina" placeholder="Količina proizvoda" type="text" required>
<input id="url" name="url" placeholder="URL slike" type="text" required>
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct()">
</form>
</div>
When I click on submit this function is called:
function addProduct(){
var isValid = true;
var url = "http://zamger.etf.unsa.ba/wt/proizvodi.php?brindexa=16390";
var amount = document.form.kolicina.value;
var naziv = document.form.naziv.value;
var slikaurl = document.form.url.value;
var validity = validateFields(naziv, slikaurl, amount);
if(!validity) return false;
var product = {
naziv: naziv,
kolicina: amount,
slika: slikaurl
};
var requestObject = new XMLHttpRequest();
requestObject.onreadystatechange = function(event) {
if (requestObject.readyState == 4 && requestObject.status == 200)
{
loadProducts();
event.preventDefault();
}
}
requestObject.open("POST", url, true);
requestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
requestObject.send("akcija=dodavanje" + "&brindexa=16390&proizvod=" + JSON.stringify(product));
}
It is because you are not preventing the default action of the submit button click.
You can return false from an event handler to prevent the default action of an event so
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct(); return false;">
But since you have a form with a submit button, I think it will be better to use the submit event handler like
<form id="form" method="post" name="form" onsubmit="addProduct(); return false;">
....
<input type="submit" value="Pošalji" class="popupButtons">
Your problem is that your submit button still executes a real submit. You could change your addProducts method. The method have to return false to prevent the real submit.
Submit button performs default Submit action for HTML code.
Try to change Submit tag into Button tag. Or after AddProduct() in OnClick JS Action put
return false;
Simple Change put input type="button" instead of tpye="submit"
<input type="button" value="Pošalji" class="popupButtons" onclick="addProduct()">
Any changes that I want does not take effect because the page refreshes itself whenever I click a button.
With the POST method on it. This the scenario, I clicked the button, then changes take effect like editing the inner html of a division, after that, the page refreshes itself that is why all the changes disappears. Please help me if there are any ways that changes can be made after the page refreshes.
This is my code. Can you tell me how to use ajax on it?
<form name="myForm" method="POST">
<button style="border-radius:0px;" type="submit" name="tabExe" id="tabExe" href="#Exec" onClick="myFunction('Executive');" class="btn btn-primary">Executive Room>
</button>
</form>
<script>
function myFunction(str){
if(document.getElementById(str) == tabExe){
document.getElementById('room1').innerHTML = "Room 101";
}
}
</script>
Consider this code of Javascript ajax as you need:
function submit()
{
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "yourpage.phtml?param1=2¶m2=10", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
return false;
}
HTML onsubmit method:
<form name="myForm" method="POST" onsubmit="return submit()">
When u clicked on submit button . form submitted. But when u use button as type, It will not refresh.
remove type ="submit". use type type ="button"
add return false; in onclick function. So it change bydefault property.
<form name="myForm" method="POST">
<button style="border-radius:0px;" name="tabExe" id="tabExe" href="#Exec"
onClick="myFunction('Executive'); return false;" class="btn btn-primary">
Executive Room>
</button>
</form>
<script>
function myFunction(str){
alert();
if(document.getElementById(str) == tabExe){
document.getElementById('room1').innerHTML = "Room 101";
}
}
</script>