I have the following function that is meant to get called after a form I submitted (this method is in my application.js folder in my rails app):
var addToTopics = function() {
var result = "";
var checkedTopics = $(".topic-checkbox:checked");
$.each(checkedTopics, function(i, topic) {
if(i == 0) {
result = result + $(topic).attr('value');
}
else {
result = result + ", " + $(topic).attr('value');
}
});
return result;
};
$("#new_comment").submit(function() {
var ListOfTopics = addToTopics();
$('#comment_topics').val(ListOfTopics);
alert($('#comment_topics').val());
return true;
});
HTML
<form method="post" id="new_comment" class="new_comment" action="/comments" accept-charset="UTF-8"><div style="margin:0;padding:0;display:inline"><input type="hidden" value="✓" name="utf8"><input type="hidden" value="8vLhtuco+TAkeB+9kQ0gERvA54BD/BnjJuguWxuXWHQ=" name="authenticity_token"></div>
<div class="field">
<label for="comment_comment">Comment</label>
<br>
<textarea rows="20" name="comment[comment]" id="comment_comment" cols="40"></textarea>
</div>
<div class="field">
<input type="hidden" value="28" name="comment[review_id]" id="comment_review_id">
</div>
<div class="field">
<input type="hidden" value="1" name="comment[user_id]" id="comment_user_id">
</div>
<div class="field">
<input type="hidden" value="" name="comment[topics]" id="comment_topics">
</div>
<div class="actions">
<input type="submit" value="Create Comment" name="commit" id="comment_submit">
</div>
</form>
But this dosen't seem to be getting called as the alert dosent even go off when I submit my form.
Any idea why? Thanks
You need to ensure the code attaching the listener runs after the form has been rendered to the dom. this is one way of doing it:
$(function() {
$("#new_comment").submit(function() {
var ListOfTopics = addToTopics();
$('#comment_topics').val(ListOfTopics);
alert($('#comment_topics').val());
return true;
});
});
has an element with the id new_comment been added to the dom prior to you running $("#new_comment").submit(function(){...});
If not, then $("#new_comment") will return no selections and jquery will silently 'fail'.
i had this same issue yesterday, my issue was an unrelated javascript error on the page
add a simple alert above this line
$("#new_comment").submit(function() {
to check (or check your browser js console)
Try changing $("#new_comment").submit(function() to $("#comment_form").submit(function(), from what I'm seeing in your code those two selectors are not matching. Hope it helps. Cheers
And since you have an action attribute in your form "action='/Comment'" either remove it if you do not have a valid reason why you have it there or prevent the default behavior which will force the form to redirect to your current url + /Comment
So the code will look like :
$("#comment_form").submit(function(evt) {
evt.preventDefault();
// rest of function below
});
Related
I would like to 'post' a form with vanilla JS. There are other questions similar, but I cannot get mine to work. The data is simply not passing to the controller.
I have several options for user on page, displayed as buttons. When the user clicks one button, a hidden form gets filled, and then the JS will submit the form to the controller.
the hidden form below:
[for testing, I have not 'hidden' the form fields yet, so I can monitor the correct information is getting to the form]
<form action="RetailTimePriceDisplayOne" method="post" id="postForm" name="postForm">
<input type="text" id="fmZero" value="#ViewBag.zero" />
<input type="text" id="fmVehicle" />
<input type="text" id="fmTeam" />
<input type="text" id="fmTLabor" />
<input type="text" id="fmRouteCost" />
<input type="text" id="fmRouteD" value="#ViewBag.vehicleMile"/>
<input type="text" id="fmRouteT" value="#ViewBag.vehicleTime"/>
</form>
My JS:
<script>
function fillForm(vehicleType, teamCount, travelLabor, routeCost) {
document.getElementById("fmVehicle").value = vehicleType;
document.getElementById("fmTeam").value = teamCount;
var x = #ViewBag.rateTravelDrvr;
if (teamCount > 1) {
x = #ViewBag.rateTravelDrvr + (#ViewBag.rateTravelCrew * (teamCount - 1));
}
document.getElementById("fmTLabor").value = x;
var y;
if (vehicleType == "V") {
y = #ViewBag.vVPrice;
}
if (vehicleType == "H") {
y = #ViewBag.vHPrice;
}
if (vehicleType == "T") {
y = #ViewBag.vTPrice;
}
document.getElementById("fmRouteCost").value = y;
SubmitForm();
}
function SubmitForm() {
var myForm = document.getElementById('postForm');
//document.forms["postForm"].submit();
myForm.method = 'post';
myForm.submit();
}
</script>
The form gets filled correctly, but no data is submitted to the controller. You can see that I played around with it a bit. One thought I had was that the method was changing to 'get' and that by explicitly specifying the method, I might solve the issue. But no such luck. Thanks!
EDIT:
As requested, one of the 6 buttons on the page that fire the JS function.
<button class="btn btn-secondary btn-lg" style="width:100%; height:100%;" onclick="fillForm('T',3)">
<strong>#ViewBag.TrkThr</strong>
<p>with 3 persons</p>
<p>+ #ViewBag.TrkMinute per labor minute*</p>
</button>
Usually when I want to submit the form, I am using button, then do onClick event
The "name" of the inputs wasn't defined, and hence data wasn't getting posted.
I am using a Wordpress theme that unfortunately is duplicating the header HTML for desktop, mobile and tablet. As a result, a login form I have appears to be submitting multiple times even though "Login" is only clicked once.
Here is the HTML for the form:
<div id="user-login">
<div class="com_row">
<div class="com_panel_body">
<div id="error_message91" class="com_alert com_alert_danger" style="display: none;">
</div>
<form method="post" id="validation_form83">
<input type="hidden" name="login_form_flag" value="1">
<div class="login-username">
<label for="email" class="main_label">Email Address</label>
<input id="email68" type="email" name="email" required="required">
</div>
<div class="login-password">
<label for="password" class="main_label">Password:</label>
<input id="password82" type="password" name="password" required="required">
</div>
<ul class="login-links" style="margin-top:-30px"><li>Forgot Password?</li></ul>
<div class="login-submit" style="margin-top:-20px">
<input type="submit" value="Login"></div>
<div style="padding-top:20px"><a class="button green small borderd-bot" href="/client_account">Register</a></div>
</form>
</div>
</div>
</div>
Here is the relevant JS:
$("[id^='validation_form']").each(function(i) {
//necessary because there are 3 form duplicates on the page, so this button works on all
jQuery(document).on("submit", this, SubmitValidationForm);
});
function($) {
SubmitValidationForm = function (event) {
event.preventDefault();
var formk = "#"+event.target.id;
var k = $(formk).serialize();
k += "&action=wcap_requests&what=validate_login";
jQuery("input[type=email]",formk).prop("disabled", true);
jQuery("input[type=password]",formk).prop("disabled", true);
jQuery("input[type=submit]",formk).prop("disabled", true).val(WCAP_Working_text);
var childf = $(formk).closest('div','.com_alert').children( ".com_alert");
$(childf).hide();
var login_form_flag = jQuery("input[name=login_form_flag]",formk).val();
jQuery.post(wcap_ajaxurl, k, function (data) {
data = JSON.parse(data);
console.log(data);
if (data.status === "OK") {
//== if client login through wcap login form
if (login_form_flag === '1'){
window.location.href = client_area_url;
}
else {
if (redirect_login !== "0") {
window.location.href = redirect_login;
} else {
window.location.reload();
}
}
}
else {
jQuery("input[type=email]",formk).prop("disabled", false);
jQuery("input[type=password]",formk).prop("disabled", false);
jQuery("input[type=submit]",formk).prop("disabled", false).val('Login');
$(childf).html(data.message).show();
}
});
};
};
The problem is because there are 3 duplicate forms on the page HTML (with only 1 visible to the user), the SubmitValidationForm function is called 3 times every time. The issue is pronounced when there is a valid login submitted, but the error box still appears saying invalid email after a few seconds (even though the login is actually correct and the user gets automatically redirected properly to the client area ). This error seems caused by the fact the SubmitValidationForm function is called 2 subsequent times after the first 'valid' submission which makes it think it's invalid, when it's not... the interesting thing is it doesn't seem caused by the other duplicate forms in the HTML, as the form ID attribute that I display in browser console shows only the 'valid' form being submitted (albeit multiple times -- perhaps because of the jquery.on() for each function).
Any ideas how to fix?
Thanks!
I figured out the issue. If anyone else is looking at this in future the issue was with respect to the 'on' function, it was referencing the 'document' before instead of 'this'. So it should be changed to:
$("[id^='validation_form']").each(function(i) {
jQuery(this).on("submit", this, SubmitValidationForm);
});
I have a form and java script that checks if text filed was not empty. problem is, code works with IE and Firefox but do not work with chrome.
<form action="editor.php?id=<?=$id_book?>" method="post" name="form1" onsubmit="return check_form(this)" >
<script language="javascript">
function check()
{
if ((document.all.title.value==""))
{
alert("Отсутствует название книги!");
}
if ((document.all.price.value==""))
{
alert("Отсутствует цена книги!");
}
if ((document.all.descrip.value==""))
{
alert("Отсутствует описание книги!");
}
else
{
document.all.form1.submit();
}
}
</script>
<div class="list-group">
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Название:</div></span>
<input type="text" name="title" class="form-control" value="<?=$value['title']?>">
</div><br />
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Цена:</div></span>
<input type="text" name="price" class="form-control" value="<?=$value['price']?>">
</div><br />
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Описание</div></span>
<textarea type="text" name="descrip" class="myform-control" rows="5"><?=$value['descrip']?></textarea>
</div><br />
<?php endforeach; ?>
<div class="col-md-12">
<div class="col-md-2"><button type="button" value="Submit" class="btn btn-primary" onclick="check()">Редактировать</button>
</form>
</div>
any ideas? More problem is that if I have just one filed check in chrome, scripts works fine. Submit button do not work only if I need to check several fields.
UPDATE: sorry guys... everything works fine... copy-paste will kill me... type button should be "Submit" instead of "button"... next time I'll should be more careful coping code:)
Your IF statements look incorrect. Only the last IF statement will stop the submit from happening, as that is the only call that the "else" step is associated with. For javascript please try the following format:
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
additionally, if you want to check multiple values and if any of the values don't exist you should try some sort of flag. Example:
If (document.all.title.value==""){
message += "Title is missing";
}
If (document.all.price.value==""){
message += "Price is missing";
}
If (message == ""){
document.all.form1.submit();
}else{
alert(message)
}
Markup errors aside (see my comment), document.all is IE/MSHTML-proprietary and now deprecated (for some reason Mozilla adopted it a few years ago). Your code should look as follows when standards-compliant:
<form … onsubmit="return check_form(this)">
<script type="text/javascript">
function check_form (form)
{
var elements = form.elements;
if (elements["title"].value == "")
{
window.alert("Отсутствует название книги!");
return false;
}
if (elements["price"].value == "")
{
window.alert("Отсутствует цена книги!");
return false;
}
if (elements["descrip"].value == "")
{
window.alert("Отсутствует описание книги!");
return false;
}
}
</script>
…
<button type="submit" value="Submit" class="btn btn-primary">Редактировать</button>
</form>
Note that the function returns false if there is an error, preventing the form from being submitted because the return value is returned to the onsubmit event handler (which I presume was the intention; you called, but did not define the check() function there). You should not bother the user with several alert()s if there are several errors, but at most collect the error messages for one alert(). You can use an Array of string values for that.
However, given that new Firefox versions prevent the user from seeing the document while the alert() is displayed, you should avoid alert() and display the error messages in the document instead. A common approach is to highlight the erroneous fields using scripted CSS, and put the message that says what is wrong with the particular field either in a box for the entire form or next to the offending control. Also consider HTML5 form validation.
I've the following form twice on my homepage:
<form id="get-consultation-form" action="javascript:alert('success!');" >
<h3 class="sub-heading">Book a Consultation</h3>
<div id="message"></div>
<div id="fields">
<input type="text" maxlength="" name="Consultation[name]" placeholder="NAME" />
<input type="text" maxlength="" name="Consultation[number]" placeholder="NUMBER" />
<input type="text" maxlength="" name="Consultation[email]" placeholder="EMAIL" />
<button type="submit" class="btn">Submit</button>
</div>
</form>
The form uses jQuery/Ajax/PHP to forward the data via email:
$(document).ready(function() {
$("#get-consultation-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "http://novicecoder.co.uk/priestley/consultation-process.php",
data: str,
success: function(msg) {
$(document).ajaxComplete(function(event, request, settings) {
NProgress.set(0.0);
if (msg === 'OK') {
result = '<div class="thanks" id="thanks">Thank you, we will contact you <span>shortly.</span></div>';
$(this).find("#fields").hide();
NProgress.set(0.5);
$("#message").hide();
$("#message").html(result).slideDown(100);
$("#message").html(result);
}
else
{
result = msg;
$("#message").hide();
$("#message").html(result).slideDown(200);
$("#message").html(result);
}
NProgress.set(1.0);
});
}
});
return false;
});
});
The first form is working perfectly, however as you'll see in my working example, the 2nd is not:
My website
Any ideas why this is happening????
IDs are unique.
Try to change form elements to diferent ids.
Or instead use classes.
If you use classes you can use $('.messages-class').closest() inside the form submit() for only interact in the current form.
You can't have an element with the same ID on a page twice. Replace your #get-consultation-form ID with a class, that should solve your issue. This also applies to the elements within the form like #fields and #message.
I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.