Javascript: avoiding window to reload - javascript

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>

Related

Vue - how can i pass button value to submit in form?

I created a Vue form where there are two buttons. In my formSubmit() function i need to somehow find which button was used to submit the form. Here is what i tried:
<form #submit.prevent="formSubmit()">
<input type="text" class="form-control" v-model="name">
<input type="text" class="form-control" v-model="product">
<button class="btn btn-primary" v-model="buttonType" value="button1">BUTTON1</button>
<button class="btn btn-primary" v-model="buttonType" value="button2">BUTTON2</button>
</form>
And my function:
formSubmit(){
console.log(this.buttonType)
}
But once i click the button, i always get an undefined. Is there any other way to get the button used to submit the form? Any advice is appreciated.
You shouldn't really use v-model on a <button> element.
You can register separate event handlers for each button and call submit your form at the event of the respective event handlers.
<form #submit.prevent="onFormSubmit">
<button #click="onClickButton1">Button 1</button>
<button #click="onClickButton2">Button 2</button>
</form>
{
// ...
methods: {
onFormSubmit() {},
onClickButton1() {
// code for when button 1 is pressed
this.onFormSubmit()
},
onClickButton2() {
// code for when button 2 is pressed
this.onFormSubmit()
},
},
}

Validate form within ngDialog openConfirm before closing

I have a button that opens an ngDialog.openConfirm. Within that dialog I have a form, which includes a textarea which is required and needs to be a minimum 20 characters.
Here is a simplified version of my code:
someFunction() {
let newScope = $scope.$new();
newScope.vm = vm;
ngDialog.openConfirm({
scope: newScope,
template: 'componentDescription.html'
})
}
And my html:
<form role="form" name="subForm">
<textarea name="compDesc"
required="true"
ng-minlength="20"
ng-model="vm.compDesc">
</textarea>
<button type="button" ng-click="confirm(0)">Submit</button>
<button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>
I would like for the Dialog to only be submitted if the form is valid.
I tried to do this by creating a function in my controller , but that has trouble accessing the form/closing the dialog.
Any ideas?
UPDATE:
I've changed my html like so:
<form role="form" name="subForm" novalidate ng-submit="confirm(0)">
<textarea name="compDesc"
required="true"
ng-minlength="20"
ng-model="vm.compDesc">
</textarea>
<button type="submit">Submit</button>
<button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>
This works on the first click, which brings up my error messages, but on the second click it submits the form even though it's invalid. Seems that whenever the error messages are displayed the submit button ignores the validation.
You can manually decide whether to call $scope.confirm() or not,
Pass validation then call $scope.confirm().
Not Pass validation, don't call $scope.confirm().
e.g.
Template:
<button type="button" ng-click="ok(0)">Submit</button>
Controller:
$scope.ok = function () {
if(!validationHasPassed()){
//errorMsg.push('xxx')
return false;
}
$scope.confirm();
};
Simply you can add ng-disabled option with your form name
<button type="button" ng-disabled="subForm.$invalid" ng-click="confirm(0)">Submit</button>
you can disable submit button if length of input string is less then 20
<button type="button" ng-disabled="vm.compDesc.length < 20" ng-click="confirm(0)">Submit</button>
you can also display an error message below text area so users can understand why submit button is not enabled
<form role="form" name="subForm">
<textarea name="compDesc"
required="true"
ng-minlength="20"
ng-model="vm.compDesc">
</textarea>
<p ng-show="vm.compDesc.length < 20" style="color:#cc5965">Description should be at least 20 characters</p>
<button type="button" ng-click="confirm(0)">Submit</button>
<button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>

click event triggers without button click

Hi i'm new to JS and could use some help.
So I am basically trying to send some text from a textarea to a function called inputFromText on a submit button click event, but somehow the function is being triggered before the click (when opening the html window via electron) and nothing happens when you click the button afterwards.
How do I prevent this from happening?
<body>
<form>
<div class="form-group">
<textarea class="form-control" rows="5" id="txa_trainingText"></textarea>
<button type="submit" class="btn btn-default" id="btn_submit">Submit</button>
</div>
</form>
<script>
const trainingText = document.getElementById("txa_trainingText").value;
document.getElementById("btn_submit").addEventListener("click", inputFromText(trainingText));
function inputFromText(text) {
...
}
</script>
</body>
I found out that when using a function without the text argument one could solve the problem by writing:
function inputFromText(e) {
e.preventDefault();
...
}
I believe you need to wrap the click event handler as a function, so line would read:
document.getElementById("btn_submit").addEventListener("click", function() { inputFromText(trainingText)});
Just change the button type="submit" to button type="button"
<button type="button" class="btn btn-default" id="btn_submit">Submit</button>

React form with multiple buttons - how to choose one to handle onSubmit event?

Let's say I have this HTML:
<div id="container"></div>
<p>Output: <span id="output"></span></p>
and this JS:
function otherAction(e) {
document.getElementById('output').innerHTML = 'otherAction';
e.preventDefault();
}
function submit(e) {
document.getElementById('output').innerHTML = 'submit';
e.preventDefault();
}
ReactDOM.render(
<form onSubmit={submit}>
<input type="text" defaultValue="foo" />
<button onClick={otherAction}>Other Action</button>
<button type="submit">Submit</button>
</form>,
document.getElementById('container')
);
Actually, let's not just say it, let's put it in a JSFiddle example. What I want to happen is that:
Clicking the "Other Action" button triggers the otherAction function (it does!)
Clicking the "Submit" button triggers the submit function (it does!)
Putting your cursor in the text box and pressing enter triggers the submit function (this does not work currently!)
In #3, what happens instead is that otherAction gets triggered. How can I change that?
If you set the first button to type="button" (i.e. provide a type for each button) it should work.
<button type="button" onClick={otherAction}>Other Action</button>
https://jsfiddle.net/L0urqamz/3/
You should provide types for all buttons, otherwise it won't work:
<form onSubmit={handleSubmit}>
// form content
<button type="button" onClick={someButtonEvent}>DO STH</button>
<button type="submit">SUBMIT</button>
</form>

AJAX and submit button on form interaction

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()">

Categories