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>
Related
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
I have this form, that is never submitted: it just triggers a calcularplazas() function when pressing a non-submit button:
<form name="what" id="what" action="">
<input id="mat" type="text"/>
<button id="btnEnviar" class="btn" onclick="calcularplazas();">SEND</button>
<input id="btnLimpiar" class="btn" type="reset" value="CLEAR" />
<p id="resultado"></p>
</form>
When clicking on the button, function works properly but no result can be shown, as the window reloads. I do not understand this behaviour as there's nothing on the function making it reload, neither is a form submitting.
As consequence of this, the result text is exported to <p id="resultado"></p> but on miliseconds dissapears, as window reloads.
Why this behaviour?
function calcularplazas(){
var mensaje = "MENSAJE FINAL";
document.getElementById("resultado").innerHTML = mensaje;
}
You say "non-submit" button, but since you haven't given your <button> element a type attribute, it is a submit button by default. You need to tell the browser to treat it as a "normal" button:
<button type="button" id="btnEnviar" class="btn" onclick="calcularplazas();">SEND</button>
Clicking this will now not submit the form, and not cause the page to reload.
You can prevent submit event to be dispatched.
myForm.addEventListener('submit', function(e) {
e.preventDefault();
calcularplazas();
// do anything else you want
})
And HTML
<form id="myForm">
<input id="input1" type="text"/>
<button type="submit" id="myButton">SEND</button>
</form>
It will works for Return key to do as well
The button in the form, have you tried giving it type="button" ?
Because in a form it gets type="submit" by default (or the form behaves like it would with a submit type).
You Need to make only 2 changes and the code will run .
Put return false in the javascript function.
when you call the function on onclick function write return calcularplazas.
check the below code for for your reference.
function calcularplazas(){
var mensaje = "MENSAJE FINAL";
document.getElementById("resultado").innerHTML = mensaje;
return false;
}
<button id="btnEnviar" class="btn" onclick="return calcularplazas();">SEND</button>
I have two submits, one to submit the form on page 1, the other to submit form on page 1 and redirect to form 2 on page 2.
<input type="submit" value="Submit and Add Expense" onclick="window.location.href='#Url.Action("Create", "Expense")';"/>
The issue is, when this secondary submit button is clicked it just submits the form just like the first submit button. It appears that the redirect #url.action is not firing. Thoughts?
The following code should do the trick.
<input type="submit" id="btnOne" value="One"/>
<input type="button" id="btnTwo" value="One"/>
<script>
var sample = sample || {};
sample.url = '#Url.Action("Create", "Expense")';
</script>
//you can move it to a separate file
<script>
$(function(){
$("#btnTwo").click(function(){
var form = $("form");
form.submit();
setTimeout(function() {
window.location.href = sample.url;
},100);
});
});
</script>
I wound up going the easy route of assigning value property to the button, and then checking the button value in the controller.
// View
<input type="submit" value="Submit" />
<button name="button" value="SubmitAndExpense">Submit and Add Expense</button>
// Controller
[HttpPost]
public ActionResult Create(string button)
{
if (button != "SubmitAndExpense") {...}
}
<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.
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()">