ASP.Net MVC 4 Set 'onsubmit' on form submission - html

I have the following form:
#Html.BeginForm("ActionMethod","Controller",FormMethod.Post)
On submission I want to run a Javascript function, so I added the following:
#Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })
But, it doesn't work... What am I doing wrong? Thanks!

You need this instead:
#using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
//form
}
Notice the using this makes the form self closing, without the using you need to close it as detailed in this MSDN article.
You can confirm javascript is called with this to isolate the problem:
#using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
<input type="submit" value="test" />
}
This should pop up an alert.
If the first one fails and the second one works, there is a problem with your js script references. This would raise an error in your browser console.
Update
Instead of binding your form obtrusively, if you give your form an Id you could use the following jquery instead (jQuery reference):
#using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { id = "target"}))
{
//form
}
<script>
$(function () {
$("#target").submit(function (event) {
event.preventDefault();
myJsFunction();
});
});
</script>
This would bind when the form when the document is ready.

#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "form1Demo", onsubmit = "return CheckSubmit(event);" })){
//form
}
<script>
function CheckSubmit(e) {
var Name = $("#Name").val();
var Roll = $("#Roll").val();
var Price = $("#Price").val();
if (Name == "" || Roll == "" || Price == "") {
$("#msg").html("Please Enter All Values!");
swal("Validation Error!", "Please Insert All Values", "warning");
return false;
}
return true;
}
</script>

Related

Google sheet not being updated by setValues

I am writing a large file uploader for Google Drive and when I tried to implement writing some data to a Google Sheet I ran into a brick wall, for whatever reason I could not get it to ever write or even give a error as to why. I decided to start a whole new project and made it as simple as possible so all it does is grab similar data to what I will be grabbing and write it, but still no luck.
I am not super familiar with the Google Apps processes or the syntax of using them so I am probably just doing something really stupid.
Old code removed
I have tried removing some variables like file and email in case they needed to be written differently and changing how the form is passed to the function but the best I ever got was a "Cannot read Null" error when I passed it a form that didn't exist.
UPDATE:
Once I had it working I tried to slip it into the main script I am using (Which is basically a copy of this but now its not working, I am realizing this may be over my head unfortunately cause no matter what I try its doing the same, runs and uploads the file fine, but does not update the form.
Google Scripts:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Form.html');
}
function getAuth() {
return { accessToken: ScriptApp.getOAuthToken(), folderId: "1sFxs3Ga4xWFCgIXRUnQzCAAp_iRX-wdj" };
}
function setDescription({fileId, description}) {
DriveApp.getFileById(fileId).setDescription(description);
}
function updateform(formObject) {
try {
var ss = SpreadsheetApp.openById('1iCTNZ6RERnes1Y-ocfXzPN3jviwdIEK_dBKQ4LIu5KI');
var sheet = ss.getSheets()[0];
sheet.appendRow([myFile.getName(), myFile.getUrl(), formObject.myName], "If This Shows Up It Worked");
} catch (error) {
return error.toString();
}
}
HTML:
<form id="myForm" align="center" onsubmit="updatesheet(This)">
<input type="text" name="myName" placeholder="Your name..">
<input type="file" name="myFile">
<input type="submit" value="Submit Form" onclick="run(); return false;">
</form>
<div id="progress"></div>
<div id="output"></div>
<script src="https://cdn.jsdelivr.net/gh/tanaikech/ResumableUploadForGoogleDrive_js#master/resumableupload_js.min.js"></script>
<script>
function onSuccess() {
var div = document.getElementById('output');
div.innerHTML = '<a href="Spreadsheet Updated</a>';
}
function onFailure(error) {
alert(error.message);
}
function updatesheet(form) {
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).updateform(form);
}
function run() {
google.script.run.withSuccessHandler(accessToken => ResumableUploadForGoogleDrive(accessToken)).getAuth();
}
function ResumableUploadForGoogleDrive({accessToken, folderId}) {
const myName = document.getElementsByName("myName")[0].value;
const file = document.getElementsByName("myFile")[0].files[0];
if (!file) return;
let fr = new FileReader();
fr.fileName = file.name;
fr.fileSize = file.size;
fr.fileType = file.type;
fr.readAsArrayBuffer(file);
fr.onload = e => {
var id = "p";
var div = document.createElement("div");
div.id = id;
document.getElementById("progress").appendChild(div);
document.getElementById(id).innerHTML = "Initializing.";
const f = e.target;
const resource = { fileName: f.fileName, fileSize: f.fileSize, fileType: f.fileType, fileBuffer: f.result, accessToken, folderId };
const ru = new ResumableUploadToGoogleDrive();
ru.Do(resource, function (res, err) {
if (err) {
console.log(err);
return;
}
console.log(res);
let msg = "";
if (res.status == "Uploading") {
msg = Math.round((res.progressNumber.current / res.progressNumber.end) * 100) + "% (" + f.fileName + ")";
} else {
msg = res.status + " (" + f.fileName + ")";
}
if (res.status == "Done") {
google.script.run.withSuccessHandler(_ => {
document.getElementById('myForm').style.display = 'none';
document.getElementById('p').style.display = 'none';
document.getElementById('output').innerHTML = "All information submitted, thank you!";
}).setDescription({fileId: res.result.id, description: "Uploaded by " + myName});
}
document.getElementById(id).innerText = msg;
});
}
}
</script>
Several things about your updated code.
First it should be this not This.
Second you have onsubmit and onclick events for the same form. I believe the onclick is suppressing the submit event. Remove onclick entirely.
Third you use a try catch block in updateform so withFailureHandler will never execute. Instead the error message or null is returned to the success handler onSuccess(error).
Forth, I use a paragraph <p> instead of an anchor <a>. The href is malformed in your anchor.
Last, run() can be executed in updatesheet(form). Note run() is asynchronous which means it doesn't wait for google.script.run to finish before executing.
I can simply tell you that all the alerts are displayed and the execution log shows updateform did execute. So this code works for me.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm" align="center" onsubmit="updatesheet(this)">
<input type="text" name="myName" placeholder="Your name..">
<input type="text" name="myFile">
<input type="submit" value="Submit Form">
</form>
<div id="progress"></div>
<div id="output"></div>
<script>
function onSuccess(error) {
if( error ) {
alert(err);
return;
}
alert("onSuccess");
var div = document.getElementById('output');
div.innerHTML = "<p>Spreadsheet Updated</p>";
}
function run() {
alert("run");
}
function updatesheet(form) {
alert("updatesheet");
google.script.run.withSuccessHandler(onSuccess).updateform(form);
run();
}
</script>
</body>
</html>

Get auto update in id without clicking mouse point any ware

I'm trying to get ajax value get auto update in id without clicking mouse point any ware, now I'm able to get value vile pressing mouse point any ware it get update
input fled
<div class="form-control-wrap">
<input type="text" class="form-control form-control-outlined form-control-outlined" id="email" name="email" >
<label class="form-label-outlined" for="email">email</label>
<span id="error_email"></span>
</div>
My ajax code
<script>
$(document).ready(function(){
$('#email').blur(function(){
var error_email = '';
var email = $('#email').val();
var _token = $('input[name="_token"]').val();
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!filter.test(email))
{
$('#error_email').html('<label class="text-danger">Invalid Email</label>');
$('#email').addClass('has-error');
$('#register').attr('disabled', 'disabled');
}
else
{
$.ajax({
url:"{{ url('https://test.com/email_available/check') }}",
method:"POST",
data:{email:email, _token:_token},
success:function(result)
{
if(result == 'unique')
{
$('#error_email').html('<label class="text-success">Email Available</label>');
$('#email').removeClass('has-error');
$('#register').attr('disabled', false);
}
else
{
$('#error_email').html('<label class="text-danger">Email not Available</label>');
$('#email').addClass('has-error');
$('#register').attr('disabled', 'disabled');
}
}
})
}
});
});
</script>
To get the value to auto-update without clicking anywhere, you can use the keyup event instead of the blur event. The keyup event will fire every time a key is pressed and released in the input field, so the validation will happen in real-time.
Here is an updated version of your code using the keyup event:
$(document).ready(function(){
$('#email').keyup(function(){
var error_email = '';
var email = $('#email').val();
var _token = $('input[name="_token"]').val();
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!filter.test(email))
{
$('#error_email').html('<label class="text-danger">Invalid Email</label>');
$('#email').addClass('has-error');
$('#register').attr('disabled', 'disabled');
}
else
{
$.ajax({
url:"{{ url('https://test.com/email_available/check') }}",
method:"POST",
data:{email:email, _token:_token},
success:function(result)
{
if(result == 'unique')
{
$('#error_email').html('<label class="text-success">Email Available</label>');
$('#email').removeClass('has-error');
$('#register').attr('disabled', false);
}
else
{
$('#error_email').html('<label class="text-danger">Email not Available</label>');
$('#email').addClass('has-error');
$('#register').attr('disabled', 'disabled');
}
}
})
}
});
});
Note that with this approach, the validation will happen every time a key is pressed, which can be resource-intensive if you have a lot of input fields or if the validation involves a lot of processing. In that case, you might want to consider adding a delay using setTimeout or using a different approach, such as validating the input field when the form is submitted instead of in real-time.

My log in code seem not working properties

I want to get the file from json and compare them with the textbox that I get from the input form, but my code seems not working properties. I am very new to angular and this is my first try project not for work.
//This is JS file
(function () {
'use strict';
angular.module('routerApp').controller('LoginCtrl', function ($http, $scope, $location) {
$scope.loginUser = function () {
$http.get('data.json').then(function(data){
$scope.users = data;
var usr = $scope.usr;
var pwd = $scope.pwd;
if(data.username == usr && data.password == pwd){
$location.path('/laptop');
}
else{
alert("Username or password is incorrect");
}
});
};
});
})();
When I click login button it always true even I didn't input anything

AngularJS textbox value returns undefined

When I press my button, I want to print the value of my textbox in my console. But my textbox returns a undefined. It seems that all of the code are working perfect, I did it the same way as some other code I used before, but it isn't working now.
This is my html code:
<form class="form-horizontal">
<input type="text" ng-model="add" ng-model-instant><button class="btn" ng-click="order()"><i class="icon-plus"></i>Order!</button>
</form>
This is my script:
angular.module('MyApp', []).
config(function($routeProvider) {
$routeProvider.
when('/boeken', {templateUrl:'partials/boeken.html', controller:BoekenCtrl}).
when('/orders', {templateUrl:'partials/orders.html', controller:OrderCtrl}).
when('/home', {templateUrl:'partials/home.html', controller:HomeCtrl}).
otherwise({redirectTo:'/home'});
});
//BoekenCtrl
//HomeCtrl
function OrderCtrl($rootScope) {
$rootScope.order = function() { console.log($rootScope.add); $rootScope.add = ""; };
}
Why is it that my textbox is undefined?
Instead
function OrderCtrl($rootScope) {
$rootScope.order = function() { console.log($rootScope.add); $rootScope.add = ""; };
}
use:
function OrderCtrl($scope) {
$scope.order = function() {
console.log($scope.add);
$scope.add = "";
};
}
Since your form exists under OrderCtrl, you need to use $scope into OrderCtrl controller to fetch any data. But, sure, you can store it after in $rootScope
Please, see the example in Fiddle

Ajax form requires two clicks on submit before fades out

So there is obviously something wrong in my syntax. Validation is ok. When I click submit the form sends email to me and then it deletes the value of my inputs. Everything is ok until now. But it does not fade out as it should. If I click on submit again, then it fades out. Thanks!
<script type="text/javascript">
$(document).ready(function () {
$('#form1').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter a value for name');
return false;
}
if (!email[0]) {
alert('Please enter a value for email');
return false;
}
if (!message[0]) {
alert('Please enter a value for message');
return false;
}
else {
$("#form1").ajaxForm(function () {
$("#formplic").fadeOut(1000, function () {
$(this).html("<img src='images/postauto3.png'/>").fadeIn(2000);
});
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
}
}
});
OK. I figured it out. The issue was that after else I stated again ajax.Form. I deleted that line and it works pefectly. So, if someone makes the same mistake as me, delete $("#form1").ajaxForm(function ().