Fire javascript function after all xval validations in MVC - javascript

I want to fire a JavaScript function when the user clicks on a button.
This JavaScript should fire only after the page does the xval validation.
How can this be achieved?

Do you want it to run only if the form is valid or it doesn't matter? If you want to run it only if the form is valid try this...
<form method="post" id="formToValidateID" >
<input type="button" onclick="ButtonClicked();" />
</form>
<script type="text/javascript">
function ButtonClicked() {
if($("#formToValidateID").validate.form(){
ExecuteJavascriptMethodIfValid();
}
}
function ExecuteJavascriptMethodIfValid() {
/* awesome code */
}
</script>
If you don't care if the form is valid, you can leave off the if condition.

Related

prevent form submission (javascript)

I have a form with a text input:
<form name="form1">
<cfinput type="text" name="text1" id="text1" onChange="someFunc();">
</form>
I only want it to submit in certain cases. (I run some error-checking first)
<script>
function someFunc() {
if (1==2) {
document.form1.submit();
} else {
alert("Not submitting");
}
</script>
The problem is: even though the alert is triggering fine, somehow, the form is still submitting (There are no other submit statements aside from the one!).
Many thanks if anyone can shed some light on this . . .
There's a fundamental flaw with this approach. You are currently telling the form that when text1 changes, then call someFunc(). If true, use JavaScript to submit the form. If false, go on about your business. If you hit enter in the text input, the form still submits. If there is a submit button that gets clicked, the form still submits.
The basic way to approach this is like so:
<form name="form1" onsubmit="return someFunc()">
<input type="text" name="text1" id="text1">
</form>
When the from is submitted, call someFunc(). This function must return either true or false. If it returns true, the form submits. If false, the form does nothing.
Now your JavaScript needs a slight alteration:
<script>
function someFunc() {
if (1==2) {
return true;
} else {
alert("Not submitting");
return false;
}
}
</script>
You can still have other functions called when a field is changed, but they still won't manage the form's final submission. In fact, someFunc() could call the other functions to do a final check before returning true or false to the onsubmit event.
EDIT: Documentation on implicit form submission.
EDIT 2:
This code:
$(document).ready(function(){
$("#text1").on('change', function(event){
event.preventDefault();
});
});
is stopping the default processing for the change event associated with that element. If you want to affect the submit event, then you'd do this:
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
});
});
Which would allow you to do something like this:
$(document).ready(function(){
$("#form1").submit(function(event){
if ( $('#text1').val() !== "foo" ) {
alert("Error");
event.preventDefault();
}
});
});
var form = document.getElementById("Your Form ID");
form.addEventListener("submit", function (e) {
if ("Your Desired Conditions.") {
e.preventDefault();
}
});
use the following code it will work perfectly fine
<form onsubmit="return false;" >

Serialize with javascript (jquery) to new window

I’m trying to submit a form to with javascript (jquery) to another page that export the result to excel. Below is the code I use to send form data a page and return the results to a div on the same page.
<script type="text/javascript">
function get3() {
$.post('chartprojecttype.php',
$('form[name="reportform"]').serialize(),
function (output) {
$('#info').html(output).show();
});
}
</script>
I tried to modify it like this,
<script type="text/javascript">
function get4() {
$.post('openticketsexcel.php',
{
document.getElementById(‘reportform’).submit();
});
</script>
But it does not work. I have another way to do this and have to different pages that export it in different format.
<input type="image" name="excel" onclick="submitForm('openticketsexcel.php')" value="Export To Excel" src="../pix/excel.png" class="submit_button"><input type="image" name="word" onclick="submitForm('openticketsword.php')" value="Export To Word" src="../pix/word.png"class="submit_button">
and
<script type="text/javascript">
function submitForm(action)
{
document.getElementById('reportform').action = action;
document.getElementById('reportform').submit();
}
</script>
This works but only in IE. Chrome and FireFox can used the first code that returns the submitted data but not the code that submits it to the export pages. Any ideas?
You have MANY issues
1) input type=image is a submit button. Do NOT submit in the onclick of the submit button since you will actually interfere with the event
2) why would you need to submit a form after you post the form to the server? If you need the server to return a word or excel, you need to GET (I GET below by chaning location) or POST a form - but not using $.post since the browser needs to open the file, you cannot ajax word or excel
You likely just want this:
<button class="button" id="excel"><img
alt="Export To Excel" src="../pix/excel.png"/></button>
<button class="button" id="word"><img
alt="Export To Word" src="../pix/word.png"/></button>
using
$(function() {
$(".button").on("click",function(e) {
e.preventDefault();
location="opentickets"+this.id+".php?"+$('form[name="reportform"]').serialize();
});
});
The simpler solution is just
<form action="export.php" target="_blank">
<input type="submit" name="exportformat" value="Excel" />
<input type="submit" name="exportformat" value="Word" />
</form>
and have the php sort things out
You forgot the function and an ending curly brace, and your single quotes were curly instead of straight. Try this:
<script type="text/javascript">
function get4() {
$.post('openticketsexcel.php', function() {
document.getElementById('reportform').submit();
});
}
</script>
jQuery post should be like this
$.post( "some/url", function( data ) {
// code goes here
});
REFERENCE
http://api.jquery.com/jQuery.post/

Avoid page submission on button click if condition false in javascript

I am checking the textbox value in javascript. and saving to database. where as my save is of submit type. I want if textbox value is greater than 100 then it should alert. and after alert , page should not submit.
Firstly, bind the click event of that button to a function. Secondly, use event.prevent default to stop that button from submitting the form. Thirdly, validate the value you want. If validated, use form id to submit the form. Something like this:
$("#ButtonId").on("click", function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
if ($("#InputBoxID").val() < 100) {
$("#FormId").submit();
}
else {
alert("your message");
}
});
Above code is in jQuery, so do not forget to add the reference to jQuery.
I think you're looking for something like:
<form id="myForm" onsubmit="return validateForm();">
<input type="text" id="textfield"/>
<button type="submit">submit</button>
</form>
<script>
function validateForm(){
var value=parseInt(document.getElementById('textfield').value);
if(value>100){
alert('value is no good. larger then 100');
return false;
}
}
</script>
If you can show me your code I'd be happy to help you implementing such a feature.
Here you have an example of how to do it. I used a limit of 10 characters to make the test easier: Try if yourself
HTML:
<input type="text" id="myTextBox" onkeyup="checkValue(this)" maxlength="10"></input>
<input id="sendButton" type="submit" value="SEND"></inpu
JAVASCRIPT:
function checkValue(textbox) {
if (textbox.value.length > 10) {
alert("TEXT TOO LONG");
document.getElementById("sendButton").disabled = true;
}
else
document.getElementById("sendButton").disabled = false;
}

jquery, alert when trying to submit empty field in form

I'm sure I must have missed something really obvious, but can't for the life of me see what it is.
I have the below javascript, that (in theory) looks at the form when I click submit, and tells me if I have left the 'RefNo' field blank (in the final form there will be various fields to check, so I have used class='required' to identify them all). But so far, when I click submit, nothing happens (except the form is submitted with the missing data).
I've tried various options that I have found on the internet, and this seemed the most promising.
If anyone can see what I have done wrong it would be really appreciated.
<html>
<head>
<script language="JavaScript" src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function submitForm()
{
$("#Form1").submit(function()
{
$('.required input').each(function()
{
if ($(this).val() == '')
{
$(this).addClass('highlight');
}
}
);
if ($('.required input').hasClass('highlight'))
{
alert("Please fill in a Ref Number and try again");
return false;
}
}
);
}
</script>
</head>
<body>
<form method="POST" action="test9.php" name="Form1" ID="Form1">
<input TYPE="text" ID="RefNo" NAME="RefNo" VALUE="" size="25px" class="required"></input>
</br>
<p>
<input type="submit" Name="submit" id="submitButton" value="Report History" onClick='submitForm()'></input>
</p>
</form>
</body>
Your selectors should be $('input.required'), not $('.required input').
First, I think you should use Jquery validation plugin.
Ohterwise, this code should work :
-add a onsubmit="return submitForm()" in your Form tag
<form method="POST" action="test9.php" name="Form1" ID="Form1" onsubmit="return submitForm();">
-get rid of the onclick on the submit button
-and here is the submitForm function :
function submitForm() {
var valid = true;
$('input[class="required"]').each(function() {
if ($(this).val() === '') {
alert("One field is empty and try again");
valid = false;
}
});
return valid;
}
But I really recommend jquery.validate.js
Your selector appears to be a bit off:
It should be $('.required')
The way you have it tries to select an input nested inside a Required class.
Instead of doing it on form submit, remove the submit input type from the button and just have it be a regular button.
With that in mind, your javascript should be:
<script>
$('#submitButton').click(function () {
$('input.required').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
}
});
if ($('.highlight').length > 0) {
alert("Please fill in a Ref Number and try again");
return false;
}
else {
$('#Form1').submit();
}
});
</script>
Otherwise, the way that you're doing it, you would have to cancel the event until you run your check for missing data, and then submit the form anyway. This way keeps you from having to cancel the action, as older IE browsers do that differently than the other browsers, and even newer versions of IE. So it makes your code more readable.
The selector should be either $('input.required') or $('#RefNo').
$('#RefNo') is more faster since it uses native getElementById method.

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';

Categories