Html.BeginForm not submitting when using .trigger('submit') - javascript

So I'm using razor views and JS/jQuery. I have a form that I simply cannot get to work the way I need it to. Based on my debugging, I'm just not hitting the controller at all. I think the form is just never actually submitting. I feel like the solution below should help, but I just dont understand why it isnt. Any help would be greatly appreciated.
<script language="javascript" type="text/javascript">
function CheckSubmit() {
// do some stuff
$('#myForm').trigger('submit');
return true;
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
</script>
<div id="stuff" style="display: none">
<div id="otherStuff">
#using (Html.BeginForm("MyControllerMethod", "MyController", FormMethod.Post, new { id = "myForm" }))
{
#Html.HiddenFor(x => x.UserItem.UserId)
#Html.HiddenFor(x => x.UserCert.CertificateSubject)
#Html.HiddenFor(x => x.comments)
#Html.HiddenFor(x => x.IsReactivationRequest)
<div>
<a id="btnHideDetails">
<span>Close</span>
</a>
</div>
// displays some information
<div style="padding-bottom: 15px">
#Html.RadioButtonFor(x => x.radioBtnValue, "approve")Approve <br />
#Html.RadioButtonFor(x => x.radioBtnValue, "reject")Reject <br />
</div>
<div id="txtComments" style="display: none; padding-bottom: 15px;">
<div>Comments:</div>
<div>
#(Html.TextArea("commentBox", new { maxlength = 2000, cols = 70, rows = 5 }))
</div>
</div>
}
</div>
<div>
<div id="btnSubmitDiv" style="display: none;">
<input id="btnSubmit" onclick="return CheckSubmit();" type="submit" value="Submit"/>
</div>
</div>
</div>
Right now all of the js is contained in the cshtml file. I know there are other ways of submitting this form, but for some reason this specific solution is not working and I need to understand why. Thank you!

I use the following code,and it can work:
View:
<div id="stuff" >
<div id="otherStuff">
#using (Html.BeginForm("TestJquery", "Test", FormMethod.Post, new { id = "myForm" }))
{
<input name="UserId" />
<div>
<a id="btnHideDetails">
<span>Close</span>
</a>
</div>
// displays some information
<div style="padding-bottom: 15px">
</div>
<div id="txtComments" style="display: none; padding-bottom: 15px;">
<div>Comments:</div>
<div>
#(Html.TextArea("commentBox", new { maxlength = 2000, cols = 70, rows = 5 }))
</div>
</div>
}
</div>
<div>
<div id="btnSubmitDiv">
<input id="btnSubmit" onclick="CheckSubmit()" type="button" value="Submit" />
</div>
</div>
</div>
js:
<script language="javascript" type="text/javascript">
function CheckSubmit() {
// do some stuff
$('#myForm').trigger('submit');
}
</script>
action:
[HttpGet]
public IActionResult TestJquery() {
return View();
}
[HttpPost]
public IActionResult TestJquery(string UserId)
{
return View();
}
result:

Related

Asp.net core delete button not working properly

I have a view like this:
<div class="GridContainer">
<div>
<div class="row gridHeader">
<div class="small-9 columns">Member Name</div>
<div class="small-2 columns">Date Registered</div>
</div>
#foreach (var member in Model.Members)
{
<div class="row">
<div class="small-9 columns">#member.MemberName</a></div>
<div class="small-2 columns">#member.DateRegistered</div>
<input type="hidden" asp-for="#member.Id" />
<a id="btnMemberDelete" href="#">Delete</a>
</div>
}
</div>
my javascript:
<script type="text/javascript">
$(document).ready(function () {
$('#btnMemberDelete').click(function () {
var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
var url = '#Url.Action("DeleteMembers", "Member")' + "?id=" + id;
openMemberDialog(url);
});
});
</script>
The delete button only works for the very first row at the moment. If say I have 4 rows the other 3's delete button won't even register. It won't even open the dialog box. Is there something I'm missing here as the code seems to be correct to me.
Thanks!
Fiddle here
As answerd above you need to have a uniqe ID or use a class. in my solution above I use a class like so:
$(document).ready(function () {
$('.btnMemberDelete').click(function (e) {
e.preventDefault();
var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
console.log(id)
});
});
Also correct your html:
#foreach (var member in Model.Members)
{
<div class="row">
<div class="small-9 columns">#member.MemberName</a></div> // remove the '</a>' here
<div class="small-2 columns">#member.DateRegistered</div>
<input type="hidden" asp-for="#member.Id" />
<a class="btnMemberDelete" href="#">Delete</a>
</div>
}
You need to give a unique id for each delete button. Or you can give a classname instead of id to your anchor tag.
<div class="GridContainer">
<div>
<div class="row gridHeader">
<div class="small-9 columns">Member Name</div>
<div class="small-2 columns">Date Registered</div>
</div>
#foreach (var member in Model.Members)
{
<div class="row">
<div class="small-9 columns">#member.MemberName</a></div>
<div class="small-2 columns">#member.DateRegistered</div>
<input type="hidden" asp-for="#member.Id" />
<a class="btnMemberDelete" href="#">Delete</a>
</div>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.btnMemberDelete').click(function () {
var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
var url = '#Url.Action("DeleteMembers", "Member")' + "?id=" + id;
openMemberDialog(url);
});
});
</script>

$ is not a function at b.$scope.SaveUser

I am currently working on Angular Js with Sql Database . I am trying to creating user registration system though Angular Js with Sql Database but when I click the submit button I got following error ...
angular.js:14642 TypeError: $ is not a function
at b.$scope.SaveUser (Module.js:6)
at fn (eval at compile (angular.js:15500), <anonymous>:4:144)
at e (angular.js:27285)
at b.$eval (angular.js:18372)
at b.$apply (angular.js:18472)
at HTMLInputElement.<anonymous> (angular.js:27290)
at kg (angular.js:3771)
at HTMLInputElement.d (angular.js:3759
Here is code in Register Controller...
public class RegisterController : Controller
{
public ActionResult Register()
{
return View();
}
//To check that user entered is already present or not.
public bool CheckUser(string user)
{
bool Exists = false;
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var uName = context.UserLogins.Where(x => x.UserName == user).ToList();
if (uName.Count != 0)
{
Exists = true;
}
}
return Exists;
}
//For saving the user details in database table.
public string AddUser(UserLogin usr)
{
if (usr != null)
{
if (CheckUser(usr.UserName) == false)
{
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
UserLogin createUser = new UserLogin();
createUser.UserName = usr.UserName;
createUser.Firstname = usr.Firstname;
createUser.Lastname = usr.Lastname;
createUser.Email = usr.Email;
createUser.DateTimeCreated = DateTime.Now;
createUser.Password = Utility.Encryptpassword(usr.Password);
context.UserLogins.Add(createUser);
context.SaveChanges();
}
return "User created !";
}
else
{
return "User already present !";
}
}
else
{
return "Invalid Data !";
}
}
}
}
Here is my Code for Module.js ..
var app = angular.module("myApp", [])
.controller('Ctrl', ['$scope', function ($scope) {
$scope.SaveUser = function () {
$("#divLoading").show();
var User = {
FName: $scope.fName,
LName: $scope.lName,
Email: $scope.uEmail,
Password: $scope.uPwd,
UserName: $scope.uName
};
var response = myService.AddUser(User);
response.then(function (data) {
if (data.data == "1") {
$("#divLoading").hide();
clearFields();
alert("User Created !");
window.location.href = "/Register/Login";
}
else if (data.data == "-1") {
$("#divLoading").hide();
alert("user alraedy present !");
}
else {
$("#divLoading").hide();
clearFields();
alert("Invalid data entered !");
}
});
}
function clearFields() {
$scope.fName = "";
$scope.lName = "";
$scope.Email = "";
$scope.Password = "";
$scope.UserName = "";
}
}])
.service("myService", function ($http) {
this.AddUser = function (User) {
var response = $http({
method: "post",
url: "/Register/AddUser",
data: JSON.stringify(User),
dataType: "json"
});
return response;
}
})
Here is my HTML CODE ...
#{
Layout = null;
}
<html ng-app="myApp">
<head>
<title>Register</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="~/Scripts/MyScript/Module.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container" ng-controller="Ctrl">
<br />
<div class="row">
#*<img src="~/Content/Images/user.png" />*#<h4>Register User</h4>
<hr />
<br />
<div class="col-md-6">
<form name="userForm" novalidate>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
First Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="First Name" name="fName" ng-model="fName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Last Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Last Name" name="lName" ng-model="lName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de">
Email :
</div>
<div class="col-md-6">
<input type="email" class="form-control" placeholder="User's Email" name="uEmail" ng-model="uEmail" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Username :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Username" name="uName" ng-model="uName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Password :
</div>
<div class="col-md-6">
<input type="password" class="form-control" placeholder="Password" name="uPwd" ng-model="uPwd" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-3">
<input type="button" value="Save" ng-click="SaveUser();" class="btn btn-success" />
</div>
<div class="col-md-3">
#Html.ActionLink("Sign in", "Login", "Register", new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">
<p style="position: absolute; top: 30%; left: 45%; color: White;">
please wait...<img src="~/Content/images/load.png">
</p>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Here is screen shot when I run the application
what is best solution to solved this problem ..Thanks
You will need to include jquery in your scripts path.
Something like this:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
Make sure you add it before Module.js.
Also to make that function work you will need to add jquery-ui and bootstrap.js.

Send vote after click radio button

On my website I have a form that allows you to send select a vote and after that the choice of the vote allows you to send (optional) a comment or photo or audio, this button allows you to send everything.
The form of the vote appears after searching for a specific location.
Now I would like to change the functionality, I wish that after clicking on the vote is saved directly right away, and afterwards appear as always the ability to send comments and photos.
This is my form:
<script type="text/javascript">
$(".sinButtonVote > img").click(function(e){
$(this).parents("div.sinWebQuestion").addClass("voteChosen");
$("#sendVoteButton").removeClass("hidden");
$("#sendOpinion").removeClass("hidden");
});
$("div.sinBottomVoteButton").click(function(e){
$("#sendVoteButton").removeClass("hidden");
});
function afterOpinionSent() {
$("#wsCompany").val("Select Location").change();
}
</script>
<form th:action="#{/opinion/vote}"
enctype="multipart/form-data" method="post"
data-successHandler="afterOpinionSent"
class="s_ajaxForm">
<input type="hidden" name="webLocationId" th:value="${webLocation.id}" th:if="${webLocation!=null}"/>
<div th:each="webQuestion : ${webQuestions}" class="row WebQuestion">
<div class="col-sm-6">
<div th:text="${webQuestion.question}" class="sinButtonVoteLabel">Question?</div>
</div>
<div class="col-sm-6">
<label th:each="vote : ${ {3, 2, 1, 0} }" class="radio-inline ButtonVote">
<input type="radio" th:name="|questionVote[${webQuestion.id}]|" th:value="${vote}"/>
<img yada:src="#{|/res/img/question/${webQuestion.iconName+vote}.png|}" th:alt-title="|Voto ${vote}|">
</label>
</div>
</div>
<div style="text-align: center; margin-top: 15px;" id="sendOpinion" class="s_ajaxForm hidden">
<div style="float: left; width: 35%;" class="BottomVoteButton">
<label class="btn btn-default" data-toggle="collapse" data-target="#voteComment">
<img yada:src="#{/res/img/question/comment.png}" title="Comment">
<span>Opinion</span>
</label>
</div>
<div style="float: left; width: 30%;" class="BottomVoteButton">
<label class="btn btn-default btn-file">
<img yada:src="#{/res/img/question/photo.png}" height="35px" title="Photo"><br />
<span>Photo</span>
<input type="file" accept="image/*" capture="camera" class="hidden" name="photo">
</label>
</div>
<div style="overflow: hidden; width: auto;" class="BottomVoteButton">
<label class="btn btn-default btn-file">
<img yada:src="#{/res/img/question/Audio.png}" title="Audio">
<span>Audio</span>
<input type="file" accept="audio/*" capture="microphone" class="hidden" name="audio">
</label>
</div>
<div id="voteComment" class="collapse" th:if="${webLocation!=null}">
<div class="form-group">
<textarea class="form-control" rows="5" maxlength="1024" name="comment" placeholder="Comment..."></textarea>
</div>
</div>
</div>
<button id="sendVoteButton" type="submit" class="s_ajaxForm btn btn-default btn-block hidden">Send</button>
</form>
And this is my opinionController.java:
#RequestMapping("/vote") // Ajax
public String voto(FormOpinioni formOpinioni, HttpServletRequest request, HttpServletResponse response, Model model) {
WebLocation webLocation = null;
if (formOpinioni.getWebLocationId() != null) {
webLocation = webLocationRepository.findOne(formOpinioni.getWebLocationId());
}
if (webLocation==null) {
return "/yada/ajaxError";
}
YadaBrowserId yadaBrowserId = yadaBrowserIdDao.ensureYadaBrowserId(COOKIE_UUIDNAME, COOKIE_EXPIRATIONSEC, request, response);
// Save WebResult
String ipAddress = request.getRemoteAddr();
for (Map.Entry<Long,String> idAndVote : formOpinioni.getQuestionVote().entrySet()) {
long questionId = idAndVote.getKey();
int vote = Integer.parseInt(idAndVote.getValue());
boolean stored = webResultDao.storeResult(questionId, vote, yadaBrowserId, ipAddress);
}
// Save il comment
String commento = formOpinioni.getCommento();
if (!StringUtils.isBlank(comment) && webLocation.isEnabled()) {
boolean stored = webAttachmentDao.storeAttachment(WebAttachment.TYPE_COMMENT, comment, ipAddress, webLocation, yadaBrowserId);
}
// Save photo
saveUpload(WebAttachment.TYPE_IMAGE, formOpinioni.getPhoto(), webLocation, yadaBrowserId, ipAddress, response, model);
// Save audio
saveUpload(WebAttachment.TYPE_AUDIO, formOpinioni.getAudio(), webLocation, yadaBrowserId, ipAddress, response, model);
return thanksForOpinion("Registered opiniono", model);
}
private String thanksForOpinion(String title, Model model) {
return YadaNotify.instance(model)
.yadaOk().yadaAutoclose(2000)
.yadaTitle(title)
.yadaMessage("<p style='text-align:center; min-height:60px;'>Thanks You for opinion</p>")
.yadaSave();
}
How do I change the code?
You have to make following changes
<script th:inline="javascript">
$(".sinButtonVote > img").click(function(e){
$(this).parents("div.sinWebQuestion").addClass("voteChosen");
$("#sendVoteButton").removeClass("hidden");
$("#sendOpinion").removeClass("hidden");
});
$("div.sinBottomVoteButton").click(function(e){
$("#sendVoteButton").removeClass("hidden");
});
function afterOpinionSent() {
$("#wsCompany").val("Select Location").change();
}
$(document).ready(function(){
$("input[#name='YOUR_RADIO_INPUTNAME']").click(function(){
$("#YOUR_FORM_ID").ajaxSubmit({url: '/vote', type: 'post'});
});
});
</script>
Make a Action method which will can process only vote entry .

How can I show alert box in struts 1.3.10?

How can i show alert box for validation in login form?
I got below output but i want alert box?
This is my index page: index.jsp
<html:form styleId="validate" action="/account_login" styleClass="account" method="post">
<div class="content controls single_advance">
<!-- <div class="form-row user-change-row">-->
<div class=form-row>
<div class=col-sm-3></div>
<div class=col-sm-4>
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-user></span> </div>
<!--<input type=text class=form-control placeholder="Account Name"/>-->
<html:text property="name" styleClass="validate[required] form-control" styleId="Account_Name"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-key></span> </div>
<!--<input type=password class=form-control placeholder="Password"/>-->
<html:password property="password" styleClass="validate[required] form-control" styleId="Password"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-6 col-md-offset-3">
<input class="btn btn-default btn-block btn-clean btn-success" value="Log In" type="submit">
</div>
</div>
<!--<div class=form-row>
<div class="col-md-12"> Forgot your password? </div>
</div>-->
<div class=form-row>
<div class="col-md-12 tac"><strong>OR USE </strong></div>
</div>
<div class=form-row>
<div class="col-md-12"> <a class="btn btn-primary btn-block imeino"><span class="icon-mobile-phone"></span> IMEI NO LOGIN</a> </div>
</div>
</div>
</html:form>
This is my struts action class: account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
HttpSession http_session = request.getSession(true);
http_session.setAttribute("login_name", acc_name);
ArrayList<String> name_list = new ArrayList<String>();
Query enc_password = session.createQuery("from account_dao");
List list = enc_password.list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
account_dao account = (account_dao) iterator.next();
System.out.println("Id : " + account.getId());
System.out.println("Account Name : " + account.getName());
System.out.println("Account Password : " + account.getPassword());
int i = 0;
name_list.add(i,account.getName());
i++;
}
request.setAttribute("namelist", name_list);
dealer_bean Bean = new dealer_bean();
Bean.setCustomerList(name_list);
System.out.println("List : "+name_list);
return mapping.findForward(SUCCESS);
} else {
fromBean.setError("<span style='color:red'><h6>Login failed.</h6></span>");
return mapping.findForward(FAILURE);
}
How can I show error (or) success message in alert box?
Append after the html:form close tag the next code and try:
<logic:present name="account_bean" property="error">
<div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
// When DOM is ready
$(function() {
$("#errorDialog").dialog({
title: "Login",
autoOpen: false,
resizable: false,
show: "clip",
hide: "clip",
modal: true,
dialogClass: "ui-state-active"
});
});
// When Window is ready
$(window).load(function() {
$("#errorDialog").dialog("open");
});
</script>
<div id="errorDialog">
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
</logic:present>
Simply try using struts logic tags for your purpose. Here i used jQuery ready() function,
<logic:present name="account_bean" property="error">
<script>
$(document).ready(function() {
alert('Login failed.');
});
</script>
</logic:present>
Hope this helps..
I haven't tried it and I am not even sure if this works. It was too long to be written as a comment.
Create a field in your form bean as follows:
public class MyForm{
String isUserValid;
//its getters and setters
}
And then in your account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
//rest of your code
formBean.setIsUserValid("Y")//------------Add this
return mapping.findForward(SUCCESS);
else {
formBean.setIsUserValid("N")//--------And this
return mapping.findForward(FAILURE);
}
In your jsp file add a hidden input and the following script as follows:
<head>
<script type="text/javascript">
$(document).ready(function(){
var isLoggedIn = $("#isUserValid").val();
if(isLoggedIn == "N"){
alert("Log in failed");
}
});
</script>
</head>
<body>
<input type="hidden" id="isUserValid" name="isUserValid" />

Input submit only working after second click

I've created the following form that allows uploading pictures, it has a submit button that is not working fine on IE (it only submits after the second click):
<fieldset id="form-fieldset" data-listurl="#Url.Action("Index", "Partners", new { Area = "Panel" })">
<legend></legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Logo)
</div>
<div class="editor-field">
#if (ViewData["Logo"] != null && !String.IsNullOrWhiteSpace(ViewData["Logo"].ToString()) && File.Exists(Server.MapPath("~/Content/uploads/" + ViewData["Logo"])))
{
<img src="#Url.Content("~/Content/uploads/" + ViewData["Logo"])" style="max-height: 150px" />
}
<div id="file-upload">
<span class="input-xlarge uneditable-input">#(ViewData["Logo"] == null || String.IsNullOrWhiteSpace(ViewData["Logo"].ToString()) ? "No files selected" : ViewData["Logo"].ToString()) </span><input type="button" class="btn btn-primary select-button" value="Selecionar" /><input type="button" class="btn remove-button" value="Remover" />
<input type="file" name="image" id="image" style="visibility: hidden" />
</div>#Html.HiddenFor(model => model.Logo)
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Salvar" />
<input type="button" class="btn" id="btnCancel" value="Cancelar" />
</div>
The form above has a button to open the file dialog, instead of displaying the normal input file control.
I use the following script to open the file dialog and set a span tag content to the filename.
<script type="text/javascript">
$(document).ready(function () {
$('#btnCancel').click(function () {
location.href = $('#form-fieldset').data('listurl');
});
$('#file-upload .select-button').click(function () {
$('#file-upload input[type=file]').click();
});
$('#file-upload input[type=file]').change(function () {
var entireValue = $("#file-upload input[type=file]").val();
var fileNameOnly = entireValue.substring(entireValue.lastIndexOf('\\') + 1, entireValue.length);
$("#file-upload span").html(fileNameOnly);
});
$('.remove-button').click(function () {
$('#file-upload span').html('No files selected');
$('#file-upload input[type=file]').val('');
});
});
</script>
The problem happens only on IE (I've tested only on IE10). Firefox and Chrome works perfectly.

Categories