Send vote after click radio button - javascript

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 .

Related

Dynamic Form Post Method on html with array in ASP.NET MVC

I'm building a view that with a modal opens a barcode scanner and every time that I scan a barcode I call a function startScanning() dynamically I'm building inputs inside a form.
When I click submit button I would like to send an array with all the barcodes the problem is that I'm not sure how to call the controller or what I should add in the Action in order to send the array or I if I need to change something in the elements.
My Modal Footer View
<div class="modal-footer">
(What I should write here to pass the array in the action)?
<form action="~/PurchaseOrder/ReceivedFromBarCode" method="post">
<label for="fname">Barcode:</label>
<div id="scanned-result" style="margin-bottom: 25px;"></div>
<div class="box-footer">
<button type="submit" class="btn btn-primary pull-right">
<i class="fa fa-paper-plane">
</i> Submit</button>
</div>
</form>
</div>
Javascript Function
function startScanning(facingMode) {
console.log(facingMode)
var results = document.getElementById('scanned-result');
var lastMessage;
var codesFound = 0;
function onScanSuccess(qrCodeMessage) {
if (lastMessage !== qrCodeMessage) {
lastMessage = qrCodeMessage;
++codesFound;
results.innerHTML += '<br><input placeholder="' + qrCodeMessage +']" name="barcode[' + codesFound + ']" type="text" id="barcode' + codesFound + '" value="' + qrCodeMessage + '" >';
}
}
Controller
[HttpPost]
public async Task<ActionResult> ReceivedFromBarCode(string[] barcode)
{
try
{
return RedirectToAction($"Details");
}
catch (VTHIS.CommunicationException cex)
{
throw cex;
}
}
Elements Console
<div class="modal-footer">
<form action="/secure/specialapp/admin/PurchaseOrder/ReceivedFromBarCode" method="post">
<label for="fname">Barcode:</label>
<div id="scanned-result" style="margin-bottom: 25px;">
<br>
<input placeholder="https://www.kwch.com" name="barcode[1]" type="text" id="barcode1" value="https://="www.kwch.com"><br>
<input placeholder="http://www.qrstuff.com" name="barcode[2]" type="text" id="barcode2" value=" http://www.qrstuff.com">
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary pull-right"><i class="fa fa-paper-plane"></i> Submit</button>
</div>
</form>
</div>

AJAX I must double click to submit second textarea! (Laravel)

$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('homepage.update')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
I use this to save form without refresh
Here is my route
Route::post('/homepage/update', 'AdminController#Update')->name('homepage.update');
And my html
{{ csrf_field() }}
<div class="form-group">
<label for="title"><b class="fa fa-pencil"></b> Title</label>
<input id="title" class="form-control" value="{{ $article->title }}" name="title">
<br />
<label for="content"><b class="fa fa-home"></b> Desc</label>
<div class="box-body pad">
<textarea id="content" name="content" rows="10" cols="80">
{{ $article->content }}
</textarea>
</div>
</div>
<center>
<div class="form-group">
<button type="submit" class="btn btn-success btn-sm"><b class="fa fa-save"></b> Submit</button>
</form>
My function who update ajax data
public function HomePage(Request $r) {
$article = Article::find(1);
$article->title = $r->input('title');
$article->content = $r->input('content');
$article->homepage = 1;
$article->save();
}
The problem is i must click twice button to save two forms when i click one it submit only title! Please help how to fix that

Do not submit form before jquery validate is okay

I am looking for a way, so that my FormMethod.Post Dosen't submit, before jquery validation is done. I have tried by making it so that the button just is at disabled, and then remove disable on keydown, if form is okay. But that didn't work, and neither isn't secure. What can i do?
Html
#using (Html.BeginForm("_Kontakt", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-sm-6">
<div class="col-sm-12">
<b>Facebook Url</b>
<input id="FacebookUrl" name="FacebookUrl" type="text" class="form-control" />
</div>
<div class="col-sm-12">
<b>Steam Url</b>
<input id="SteamUrl" name="SteamUrl" type="text" class="form-control" />
</div>
<div class="col-sm-12">
<button id="SendBtn" class="btn btn-success pull-right" onclick="return validateUrl();">Send</button>
</div>
</div>
</div>
}
Jquery/Javascript
function validateUrl() {
facebookURL = $("#FacebookUrl").val();
steamURL = $("#SteamUrl").val();
var facebook = /^(?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?$/;
var steam = /(?:https?:\/\/)?steamcommunity\.com\/(?:profiles|id)\/[a-zA-Z0-9]+/;
if (facebook.test(facebookURL)) {
}
else {
alert("Ikke et facebook gyldigt url!");
}
if (steam.test(steamURL)) {
}
else {
alert("Ikke et steam gyldigt url!");
}
return facebook.test(facebookURL);
return steam.test(steamURL);
}
ANSWERE
return facebook.test(facebookURL) && steam.test(steamURL);
There is an "onsubmit" event that allows you to control form submission http://www.w3schools.com/tags/ev_onsubmit.asp
If you put the inputs and button in a form element and use the pattern and required attributes in combination with the :invalid selector the browser can do the validation for you:
/* Add the .focused class when the user focuses
an input to only show the error message once */
$("#the-form input").focus(function(){
this.classList.add("focused");
});
.input-error-message {
color: red;
}
/* Show elements with the class .input-error-message
if they come after an input with invalid data if the
user isn't typing or if it has not been focused yet */
:invalid:not(:focus).focused + .input-error-message {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<form class="col-sm-6" id="the-form" onsubmit="return isValid()">
<div class="col-sm-12">
<b>Facebook Url</b>
<input id="FacebookUrl" name="FacebookUrl" type="text" class="form-control" pattern="^(?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?$" required/>
<div class="input-error-message" hidden>Ikke et facebook gyldigt url!</div>
</div>
<div class="col-sm-12">
<b>Steam Url</b>
<input id="SteamUrl" name="SteamUrl" type="text" class="form-control" pattern="(?:https?:\/\/)?steamcommunity\.com\/(?:profiles|id)\/[a-zA-Z0-9]+" required/>
<div class="input-error-message" hidden>Ikke et steam gyldigt url!</div>
</div>
<div class="col-sm-12">
<button id="SendBtn" class="btn btn-success pull-right">Send</button>
</div>
</form>
</div>

How to display the updated data in front end without refreshing page?

I want to save the edited data into DB and also display in frond-end on clicking save button in the form .. i did the first part but i struggling to show this in frond end with out refreshing the page
<div class="leftbar_menu">
<div class="short_res_header">
<h3 style="margin-top: 10px;">
<span style="float:left;">About</span>
<span style="font-size:small;float: right;"><a data-edit-id="40322" data-clickmode="edit" class="pers" data-id="40322" style="display: inline;">edit</a></span><span style="font-size:small;float: right;"><a class="pers" data-close-id="40322" data-clickmode="close" data-id="40322" style="display: none;">close</a></span> </h3>
</div>
<div class="leftbar_content">
<div data-id="40322" style="display: none;" class="about_toggle formarea">
<script type="text/javascript">
window.onLoad = imageRefreshBig();
$(document).ready(function(){
$('#profileshortresume').attr('maxlength','250');
$("#profileshortresume").css({
"max-width": "350px"
});
});
</script>
<div class="ajaxfiy_edit_profile">
<form enctype="multipart/form-data" method="post" action="http://10.0.1.21/firstplanet/dev/action/profile/edit/" onsubmit="return validateForm()" style="margin-left: 10px;" id="profile_edit_form" class="profile_edit_form_40322" name="profile_edit_form" novalidate="novalidate">
<div style="float:left;width:100%;" id="mypage_about" class=""><dl class="profileshortresume"><dt>About you<font style="color:#FF1800;font-size: 11px;padding-left: 3px;"> *</font><br></dt><dd>
<textarea title="" required="" id="profileshortresume" name="profileshortresume" class="input-textarea" maxlength="250" style="max-width: 350px;">good</textarea></dd></dl></div><input type="hidden" value="90d0e928746b45b9886292d1d0e08d5e" name="__elgg_token"><input type="hidden" value="1396426813" name="__elgg_ts"><input type="hidden" value="40322" name="cat_id"><input type="hidden" value="39242" name="custom_profile_type"><input type="hidden" value="job_1394777243" name="username">
<div class="subt_butt">
<a class="buttonS"><span><input type="button" value="Save" class="edit_save_button" style="text-align:center;"></span></a>
</div>
<br>
</form>
</div>
</div>
<div style="padding-right: 6px; display: block;" class="short_res" data-content-id="40322">
good
</div>
</div>
</div>
// Below script will open the form when edit is clicked
<script type="text/javascript">
$('a.pers').click(function(){
var formid = $(this).attr('data-id');
var clickmode = $(this).attr('data-clickmode');
/*Closing All Open Div */
$('div.short_res').show();
$('div.formarea').hide();
if(clickmode == 'edit') {
$('a[data-clickmode=create]').show();
$('a[data-clickmode=edit]').show();
$('a[data-clickmode=close]').hide();
$('a[data-create-id='+formid+']').show();
$('a[data-close-id='+formid+']').show();
$('a[data-edit-id='+formid+']').hide();
$('div[data-id='+formid+']').show();
$('div[data-content-id='+formid+']').hide();
}
if(clickmode == 'close') {
$('a[data-create-id='+formid+']').show();
$('a[data-edit-id='+formid+']').show();
$('a[data-close-id='+formid+']').hide();
$('div[data-id='+formid+']').hide();
$('div[data-content-id='+formid+']').show();
}
if(clickmode == 'create') {
$('a[data-clickmode=close]').hide();
$('a[data-clickmode=edit]').show();
$('a[data-close-id='+formid+']').show();
$('a[data-create-id='+formid+']').hide();
$('div[data-id='+formid+']').show();
$('div[data-content-id='+formid+']').hide();
}
});
// am using below script for update the data in db and display in front end
$(".edit_save_button").click(function(){
var formid = $(this).parent().parent().parent().parent().attr("class");
var url = $("form."+formid).attr('action');
var data = $("form."+formid).serialize();
$(".thewire_previous_img").show();
var details = $(this).parent().parent().parent().parent().parent().parent().next().attr("class");
$.ajax({
type: "POST",
url: url,
data: data,
context: details ,
success: function(data){
$(".formarea").hide();
$('div.short_res').show();
$('a[data-clickmode=close]').hide();
$('a[data-clickmode=edit]').show();
$(".thewire_previous_img").hide();
}
});
});
That's simple if you not want the page to refresh just not use <form> element and button as <input>,
Just get the elements value with JQuery .val() and get click event of a <button type="button"> element.
When you send a form the navigator automatically always will refresh the page or redirect you to the page that is referenced in the form.

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" />

Categories