javascript validation on Submit button - javascript

Want to use javascript validation to work when i click submit button. What happens now is even if i enter a low value the value submits. but i need to check the validation before i click submit...
This is the Javascript:
$(function () {
$("#newMonoReading").on('focusout', function () {
var str = "";
var initialMonoReading = $('#InitialMonoReading').val();
var newMonoReading = $('#newMonoReading').val()
if (~~newMonoReading < ~~initialMonoReading) {
$('#MonoErrorMessage').text("New Mono Readings must be MORE than existing");
$('#MonoErrorMessage').show();
} else {
$('#MonoErrorMessage').hide();
}
});
});
Now on my form, you can see the input type (Submit)
<div class="modal-footer">
<input type="submit" value="Submit New Readings" class="btn btn-primary">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</fieldset>
</form>
How do i get the JavaScript function to the submit button, so when i enter submit it wont work because i have entered a low value.

function validateForm() {
var str = "";
var initialMonoReading = $('#InitialMonoReading').val();
var newMonoReading = $('#newMonoReading').val();
if (~~newMonoReading < ~~initialMonoReading) {
$('#MonoErrorMessage').text("New Mono Readings must be MORE than existing");
$('#MonoErrorMessage').show();
return false;
} else {
$('#MonoErrorMessage').hide();
}
}
This example will clear things
FIDDLE
<form onsubmit="return validateForm()" method="post">
<div class="modal-footer">
<input type="submit" value="Submit New Readings" class="btn btn-primary">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</fieldset>
</form>

You don't actually want the validation on the submit button, since there are other ways to submit a form. You actually want the validation the the form's onsubmit handler.
Now, that said, you haven't shown enough of your code to know where the problem is, but I can take a good guess.
Before this line:
$("#newMonoReading").on('focusout', function () {
Add this line:
alert($("#newMonoReading").length);
There is a good chance you are trying to run this code before the DOM has been rendered. If that returns 0, you have three choices:
Use event delegation (overkill in this case)
Move the code inside a $(function() {...}); block
Load the scripts at the bottom of the page.

Change the submit button to button
In this way, you will have full control of the submit. You can perform your own logic in the validate() function and decide whether allow the form to submit or not
<input type="button" onclick="validate()" value="Submit New Readings" class="btn btn-primary">
and your the validate function will be
function validate () {
var initialMonoReading = $('#InitialMonoReading').val();
var newMonoReading = $('#newMonoReading').val()
if (~~newMonoReading < ~~initialMonoReading)
{
alert("Value is not valid");
return;
}
///else submit
$("yourform").submit();
});

Related

Sending input names in Django form having javascript code

I have the following code:
<form id="buttonForm" action = "/goSomeWhere" method="post" >
<input type="submit" name="bnext" value="Next Page" >
<input type="submit" name="bprevious" value="Previous Page" >
</form>
When either one of this two buttons are submitted I receive "bnext" or "bprevious" values in Django View request.POST so I can further construct the logic that I need.
But when I'm trying to insert some javascript for the second button I loose those values:
<input type="submit" name="bnext" value="Next Page" >
<input type="submit" name="bprevious" id="bpid" onclick="disable()" value="Previous Page" >
function disable()
{
document.getElementById("bpid").disabled = true;
document.getElementById("buttonForm").submit();
}
There is a way to do this and still receiving input names values ?
Sorry I didn't fully understood that what you are trying to do
If you are trying to stop form submission then:
function disable() {
document.getElementById("bpid").disabled = true;
document.getElementById("buttonForm").preventDefault();
}
If you want that client should not click previous button again then, it is best to change inputType submit to hidden:
function disable() {
document.getElementById("bpid").type="hidden";
document.getElementById("buttonForm").submit();
}
Or
create new <input type=hidden>, set name values ,append to form and submit it:
function disable() {
document.getElementById("bpid"). disabled=true;
newip= document.createElement("input");
newip.type="hidden";
newip.name="bprevious";
newip.value="Previous Page";
document.getElementById("buttonForm").appendChild(newip);
document.getElementById("buttonForm").submit();
}
try to use button instead input like this
<button name="bprevious" id='bpid' onclick='disable()' value="Previous Page">Previous Page</button>

How to get the input type submit ID and apply javascript

I am using below jsp' form to submit the data. Before submitting I want to apply javascript.
<form name="inventory" method="post" action="<%=request.getContextPath() %>/Tdata_Main" class="form-light mt-20" role="form" onsubmit="return validate(this)">
Now, I have three input tags of 'Submit' type
<input type="submit" name="submit" class="btn btn-two" value="Update Inventory">
<input type="submit" name="submit" class="btn btn-two" value="Add Empty Row">
<input type="submit" id="submitDelete" name="submit" class="btn btn-two" value="Delete Row">
After adding three new columns and filling in the data one by one, I added forth one as shown below. Now, I am in no need of this forth empty row hence I want to delete it. But the javascript code is getting applied here too and asking me to fill in the blank fields.
Below is the javascript code that is getting executed on the onSubmit event initiated from form.
<script type="text/javascript">
function validate(form) {
//alert(form.id);
if(form.id != "submitDelete"){ // NOT WORKING
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].type == "text"){
if(form.elements[i].value.length == 0 || form.elements[i].value.length == "null"){
alert('No value entered in '+form.elements[i].name+'.');
form.elements[i].focus();
return false;
}
}
}
}
if (confirm("Would you like to proceed!") == true) {
return true;
}
else{
return false;
}
}
</script>
How could I avoid getting this javascript code being applied on Delete using Javascript. Kindly suggest.
Your code works fine. Only one thing you should remove the action attribute from your form element and post that data using javascript only.
Also your delete button is disabled. Enable it and it will work fine

Javascript: avoiding window to reload

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>

form buttom disable onsubmit but form is not submited in javasc

<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.

Process a Form Submit with Multiple Submit Buttons in Javascript

I have a form with multiple submit buttons, and I'd like to capture when any of them are pressed, and perform different JS code for each one.
<form id="my-form">
<input type="email" name="email" placeholder="(Your email)" />
<button type="submit" value="button-one">Go - One</button>
<button type="submit" value="button-two">Go - Two</button>
<button type="submit" value="button-three">Go - Three</button>
</form>
Looking at an older answer, I can process all of the submit buttons in JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
But how can I discriminate amongst the different submit buttons? Is there a way to get the value and perform logic from there?
I don't need to have three submit buttons, per se... I just need three different buttons in a form to perform three different actions.
Thanks!
you can attach a custom click handler to all buttons, and that way you can check which button is clicked before submitting the form:
Live Example
$("#my-form button").click(function(ev){
ev.preventDefault()// cancel form submission
if($(this).attr("value")=="button-one"){
//do button 1 thing
}
// $("#my-form").submit(); if you want to submit the form
});
use this
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
var submit_type = document.getElementById('my-form').getAttribute("value");
if(submit_type=="button-one"){
}//and so on
// You must return false to prevent the default form behavior
return false;
}
HTML:
<form id = "form" onSubmit = {handleSubmit}>
<input type="email" name="email" placeholder="(Your email)" />
<button type="submit" value="button-one">Go - One</button>
<button type="submit" value="button-two">Go - Two</button>
<button type="submit" value="button-three">Go - Three</button>
</form>
JS:
const handleSubmit = e => {
e.preventDefault();
var ans = document.activeElement['value'];
console.log(ans);
};
You can also use the read-only submitter property of a SubmitEvent.
HTML (same as you have):
<form id="my-form">
<input type="email" name="email" placeholder="(Your email)" />
<button type="submit" value="button-one">Go - One</button>
<button type="submit" value="button-two">Go - Two</button>
<button type="submit" value="button-three">Go - Three</button>
</form>
JS:
let form = document.getElementById("my-form");
form.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault()
alert(event.submitter.value) // shows a different value depending on button pressed
From there on, it's easy to use submitter as a control flow, e.g.:
let form = document.getElementById("my-form");
form.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault()
submitter = event.submitter.value
switch (submitter) {
case "button-one":
alert(1)
break;
case "button-two":
alert(2)
break;
case "button-three":
alert(3)
break;
}
}
But how can I discriminate amongst the different submit buttons? Is there a way to get the value and perform logic from there?
Yes, you can use querySelector to grab elements with attributes.
document.querySelector('#my-form button[value="button-one"]' )

Categories