jQuery form error checking - javascript

I'm doing a simple jQuery form checker for a website. I have two forms on the website: a login form and a signup form. My code is as followed:
$('.btn').click(function(e) {
e.preventDefault();
// DOES SOME ERROR CHECKING HERE
if { hasError $('div.error').fadeIn() }
else { $(this).parents('form').submit() }
});
So my question is, both the login button and the signup button has a class called btn, how can I have the them check and submit their own form instead of checking all the forms on the page since $(this).parents('form') will get both the signup and login form?
Thank you!

no $(this) will get that form whose respective btn u have clicked. "this" keyword pass object of an ellement so don't worry this code will run fine.

There is something really wrong with your html markup if $(this).parents('form') returns more than one element. Also, consider to shorten your code to just
$('.btn').click(function(e) {
// DO SOME ERROR CHECKING HERE
if (hasError) {
e.preventDefault();
$('div.error').fadeIn();
}
});

give them id, and take it like this.
$('#btn1).click(....
$('#btn2).click(....

Change your HTML form structure so that when when you click either button, you are able to select the corresponding form.
<form action="get">
<input type="text" value="1" />
<input type="button" class="btn" />
</form>
<form action="get">
<input type="text" value="1" />
<input type="button" class="btn" />
</form>
And jQuery:
$(function(){
$(".btn").click(function(){
$(this).closest("form").submit();
});
});
EDIT
A better selector for your error handling
$(this).closest('form').find('.required').each(function(){
});
http://jsfiddle.net/c9GXZ/6/

If you want to go ahead with your code then you can go just take look on .parent() and .parents() method of jQuery.
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.
Try, to use $(this).closest('form').submit() instead of $(this).parents('form').submit(). I am not user but I think you have included form inside a form(check or share your HTML as well.)

$('.btn').click(function(e) {
e.preventDefault();
// DOES SOME ERROR CHECKING HERE
if (hasError) { $('div.error').fadeIn(); } //some syntax change
else { $(this).closest('form').submit() } ///will get the nearest form element and stop there and will submit it as per your code...
});
UPDATE
replace this
$('.btn').click(function(e) {
with this
$('.btn').on('click',function(e){
This got it working in your jsfiddle url...

Related

Make the click-button code not disappear instantly? [duplicate]

I have a button (<input type="submit">). When it is clicked the page reloads. Since I have some jQuery hide() functions that are called on page load, this causes these elements to be hidden again. How do I make the button do nothing, so I can still add some action that occurs when the button is clicked but not reload the page.
There is no need to use JS or jQuery.
to stop the page to reload, just specify the button type as 'button'.
If you don't specify the button type, the browser will automatically set it to 'reset' or 'submit' which causes the page to reload.
<button type='button'>submit</button>
Use either the <button> element or use an <input type="button"/>.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
You could add a click handler on the button with jQuery and do return false.
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
In HTML:
<input type="submit" onclick="return false">
With jQuery, some similar variant, already mentioned.
You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:
$(document).ready(function($) {
$(document).on('submit', '#submit-form', function(event) {
event.preventDefault();
alert('page did not reload');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id='submit-form'>
<button type='submit'>submit</button>
</form>
You could also use JavaScript for that:
let input = document.querySelector("input");
input.addEventListener("submit", (event) => {
event.preventDefault();
})
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
I can't comment yet, so I'm posting this as an answer.
Best way to avoid reload is how #user2868288 said: using the onsubmit on the form tag.
From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page.
For example:
<form id="frmData" onsubmit="return false">
<input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
<input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
<input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function() {
var tel = $("#txtTel").val();
var email = $("#txtEmail").val();
$.post("scripts/contact.php", {
tel1: tel,
email1: email
})
.done(function(data) {
$('#lblEstatus').append(data); // Appends status
if (data == "Received") {
$("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
}
})
.fail(function(xhr, textStatus, errorThrown) {
$('#lblEstatus').append("Error. Try later.");
});
});
});
</script>
Use event.preventDefault() in the first line of your event function.
Buttons must be of the type button and contain type="submit" in the button html.

Retrieving data from a form loaded with jQuery and passing it to a parent page

I have a 'parent' page that is using the following bit of code to pull in a form from a different page on the same domain. There are reasons why I can't just place the form directly on the 'parent'.
<script type="text/javascript">
jQuery("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
function() {}
).hide().fadeIn(1000);
</script>
The form that is pulled in looks like this:
<form action="https://example.com/form/" method="post" id="profile-edit-form" class="standard-form base" target="hiddenFrame">
<label for="field_1">Name</label>
<input id="field_1" name="field_1" type="text" value="Joey-Jojo Jr. Shabadoo">
<input type="submit" name="profile-group-edit-submit" id="profile-group-edit-submit" value="Save Changes " />
<input type="hidden" name="field_ids" id="field_ids" value="1" />
<input type="hidden" id="_wpnonce" name="_wpnonce" value="a62f8d5fec" />
<input type="hidden" name="_wp_http_referer" value="/form/" />
</form>
When 'submit' is clicked, https://example.com/form/ is opened in a hidden iframe and the user name gets properly saved. This all works well.
I would like the user name on the currently loaded 'parent' page to update via jquery, so that the user has some immediate visual feedback that the name change has taken place.
My approach has been to try and take the value out of the 'field_1' input when 'submit' has been clicked, and pass that variable onto a div in the parent page with an id of 'display_name'.
$(document).ready(function(){
function nameUpdate(){
$("#profile-group-edit-submit").click(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
}
nameUpdate();
});
I've also tried adding window.parent.
before the the #display_name selector section and it didn't change anything.
I've used this approach on another button/div combo on the same page and it works, the difference is that that particular button is in an iframe, not loaded by jquery. So I'm guessing my problem is related to that fact.
I've googled around, but have run out of ideas of how to phrase my question, what to look for, etc...
Any help would be greatly appreciated. Thanks!
Edit: For clarity, the div w/ id #display_name won't update.
Use jquery to handle the form submission.
$(document).ready(function(){
$('#profile-edit-form').submit(function(){
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
});
EDIT:
Due to your loading the form dynamically you need to bind the submit function after the load. So...
$(document).ready(function () {
var formLoaded = function () {
$('#profile-edit-form').submit(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
};
$("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
formLoaded
).hide().fadeIn(1000);
});
If I am understanding it correctly, your problem is "display_name" field is not getting updated with the latest value.
If this is the problem then can you try below thing?
Instead of
$("#display_name").text(updateName);
try using-
$("#display_name").val(updateName);
As per the documentation on jQuery site Val() works well with form Elements whereas text won't.
More on Val() method- https://api.jquery.com/val/#val2

Unable to submit form using Javascript

I am trying to submit my form named 'vform' by using javascript and ajax.Here
Button named 'show' is being used to show the 'div' containing form named vform and that form calls codevalidate function and there it submits the form using some ajax code..Where i am getting error is vform.submit().Here's the html and js code(I know error is in if condition but do not know where)
html:
<button id="show" onClick="javascript:codefield(); return false";>Apply for Discount</button>
<div id="apply" style="display:none">Voucher code<br>
<form id="vform" name="vform" action="" method="post" onsubmit="javascript:codevalidate(); return false;" >
<input type="text" name="code" id="code"><br>
<span id="error" style="color:red"></span><br>
<input type="submit" name="btn" value="apply" id="btn" ></form>
</div>
javascript:
function codevalidate()
{
if(document.getElementById('code').value!=="")
{
$.post("couponajax.php",{code:$("#code").val()},
function(data)
{
if(data=='1')
{
//alert("success");
vform.submit();
return true;
}
else
{
document.getElementById('error').innerHTML="You have entered a wrong code!";
return false;
}
});
}
else
{
document.getElementById('error').innerHTML="Code can't be empty!";
return false;
}
return false;
}
codefield function is just displaying the div on onclick event and ajax call is just checking whether the code exists in database or not..if exists returns 1 else 0.
The problem is alert message is being displayed but form is not being submitted. How can I fix this problem?
I think you are missing jquery selector.
Try to replace
vform.submit();
with
$("#vform").submit();
or you can call submit button click event like
$("#btn").click();
You are not selecting the form.
Try changing;
vform.submit();
To:
$("#vform").submit();
Please try this one, works for me.
document.getElementById("vform").submit();
Try this
document.forms["vform"].submit();
Hope this helps.
You don't have to submit form with code.
Just call validation function and control submit flow with preventDefault function.
var codevalidate = function(e) {
if (!validationCode) { // if validation code didn't pass
e.preventDefault(); // prevent form from submitting
}
}
// register callback that will be called when user submits form
document.getElementById("vform").addEventListener('onsubmit', codevalidate);
That way form will be submitted by user only if validation pass.
Also check if your data is actually returning '1' by calling console.log(data);
Form will be submitted to the current address if action is empty, is that ok?
The thing is that:
action attribute of your form element is empty. So it is being submitted but to the same page from which it is calling the .submit() method.
so you should specify action attribute first of all like:
<form id="vform" name="vform" action="vfrom_submit.php" method="post"
onsubmit="javascript:codevalidate(); return false;" >
.....
</form>
Also try changing
vform.submit();
to:
$("#vform").submit();
//OR
// document.getElementById("vform").submit();
// Although vform.submit() can also work.
Hope it helps, cheers :)!
You should use:
document.getElementById("vform").submit();
Update:
Try removing "return false;" from onsubmit attribute and remove "vform.submit();" from the if condition as well.

jQuery how to get input from a form?

<script>
$(function() {
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
})
</script>
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name"><input type="submit" id="button">
</form>
</div>
Does not print name in console, what am I doing wrong here?
The problem right now is that the code you've written is executed immediately when the page loads.
From the way your code looks, it looks like you actually want the form's button to do the console log.
I've altered your code a bit, but here's how you'd:
Select the Form and the Input
Declare the variable out of the scope
Bind onto the form's submit event
Prevent it from actually submitting
And logging to console per your example
Altered code below:
<script>
$(function() {
// Save a reference to the input
var input = $("input[name=first_name]"),
// Get the form itself
form = $("form[name=info]"),
// Storage for your first_name outside of the scope
first_name = false;
// Bind to the submit event on the form
form.bind('submit', function() {
// Set the first_name to the input's value
first_name = input.val();
// Log it out (per your example)
console.log(first_name);
// Return false to prevent the form from posting
return false;
});
});
</script>
<div id="content">
<form name="info">
First Name:
<input type="text" id="first_name" name="first_name">
<input type="submit" id="button">
</form>
</div>
I'm not saying this is the best way to handle whatever you're attempting to do with the form, realistically you shouldn't need an ID on the button, and probably would want to replace the NAME on the form with an ID for the selector. Also using an ID selector to get the input would be recommended as well, as ID selectors are faster than [name=something] selectors. (Thanks gnarf for the comment!)
The variable scoping is also probably somewhat strange in your example, but the above code should be good for learning :)
The method as you've written it only runs once, after the page loads. At that point the input element doesn't contain a value (i.e. $("#first_name").text() == ''). You can bind the logging statement to the keyup event of the element, to see the text that's being entered into it.
$(function() {
// this code only runs once
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
$('#first_name').keyup(function() {
// this code fires everytime a key is released on the element
console.log($(this).val());
});
})
Demo on plnkr
Here is the JSFiddle for your code.
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name" value="something">
<input type="submit" id="button">
</form>
</div>
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val());
});
'Something' is the default value.' Try other words in the text box and you will see the new value in console.
As per your code, you are getting correct results.
Your defined function is never called because you have not attached any events to it.
I have modified your code and you can check it working here
$(document).ready(function(){
$("#first_name").focusout(function(){
var first_name = $(this).val();
alert(first_name);
});
});
$('#content form').on('submit', function () {
console.log(
$(this).find('input[name="first_name"]').val()
);
return false;
});
edit: you must run your jQuery selection after you have inputted something into the input field. Right now when you run it, it is empty
edit: try using this 'on' from the jQuery docs
http://api.jquery.com/on/
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val(););
}

jQuery prevent input default action

I have an ajax form I would like to prevent from preforming an action when submitted and have tried numerous methods and nothing works. My first method was:
return false;
and then I tried
event.preventDefault();
event being the callback name or whatever you call it.
function(event) {
event.preventDefault();
};
Heres the HTML I am using right now:
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
Heres the test javascript I set up:
$('.main_search').submit(function(event) {
event.preventDefault(console.log(event)); //Log the event if captured
});
Neither method works but the weird part is that they work on different things like buttons but they don't work on this one form. Am I missing something here? Thanks!
To deal with your specific problem (ie, inserting dynamically generated form), use $.on(). You're better off not using document.body as the parent observer (as $.live() essentially does) with $.on(), so the following would be appropriate (considering your actual markup):
<div id="searches">
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
</div>
var $main_search = $('.main_search'),
$searches = $('#searches');
$searches.on('submit', '.main_search', function(event) {
event.preventDefault();
console.log(event); //Log the event if captured
});
setInterval(function(){
$searches.append($main_search.clone());
}, 5000);
http://jsfiddle.net/5TVGn/2/
I set up a JSfiddle:
http://jsfiddle.net/XM679/
Could it be you forgot to wrap it into $(document).ready(function() {} ?
If this didn't solve the problem: Since the fiddle is working - we would need your context to help more.

Categories

Resources