I'm trying to use jquery to get data from a form and stop the form submiting using this code:
$form = $('form#signup')
$form.submit(function(event){
event.preventDefault();
var $input=$('#signup :input')
console.log($input.username)
alert($input.username)
})
but the form still posts the data and the alert box does not appear.Also firebug brings up the error $ is not defined and Node.js crashes
the form (writen in jade):
html
head
script(src='javascripts/signupValidation.js')
script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
script(src='javascripts/validator.js')
body
form(id='signup',method='post',action='/signup')
label Firstname
input(type='text', name='firstname')
label Lastname
input(type='text', name='lastname')
label Username
input(type='text', name='username')
label Password
input(type='password', name='password')
label Password again
input(type='password', name='password2')
label Email
input(type='email', name='email')
input(type='submit',value='Sign up', onclick="")
If your form-related JS is in the file signupValidation.js, you need to move the script call that includes that file to be after the jquery include.
I'd probably clean up the form code a tiny bit, too:
$('form#signup').on('submit', function(event){
event.preventDefault();
var $input = $(this).find('[name=username]');
console.log($input.val());
alert($input.val());
})
You might be interested in looking at .serialize(), too.
Problem with your code [not issue with form submission]
$input.username is not valid jQuery to reference another element.
var usernameInput = $input.filter('[name="username"]');
Looks like you are not adding the code on document.ready so you probably are attaching it to nothing. Change it to be:
jQuery( function() {
$form = $('form#signup');
$form.submit(function(event){
});
}
Also looks like you are including the validation code before the jQuery code. I bet looking at the JavaScript console in the browser has some nice error messages.
You need to prevent the form from submiting with return false :
$form.submit(function(event){
var $input=$('#signup :input');
console.log($input.username);
alert($input.username);
// data = array of all the information collected from the input tags
//data = $form.serizalize(); will also work
data = $(this).serialize();
return false;
});
data would be an array with the information you need, i recommend console.log(data) so you can see all of it's structure and then you can use it as you wish for example:
if(data.something == anything){
doThis();
}
And i highly recommend adding an ; at the end of your javascript sentences
Like other people I've had luck with code like this:
$(document).ready(function(){
// Prevent form submission
$( "form" ).submit(function( event ) {
event.preventDefault();
});
});
To prevent form submission. But also, these days it's pretty common that there are scripts on the page which go behind your back and add little candy-coated features like animations and "shake-off" effects to HTML forms. It's possible for those script to get in the way in situations like this, because they might have their own javascript-fu for submissions.
Related
I have an problem with my site when I want to change the css style from the JavaScript it works but only for few seconds.
function validateForm() {
var fname = document.getElementById('<%=UserFnameTextBox.ClientID%>');
if (fname.value == "") {
document.getElementById("WarnUserFnameTextBox").style.opacity = 1;
document.getElementById('<%=UserFnameTextBox.ClientID%>').style.borderColor = "red";
getElementById('<%=UserFnameTextBox.ClientID%>').focus;
}
}
I'm using also Asp.net, that's why I wrote the ID like this
I want that the JS will save the style for as long that the user enter the textbox.
Multiple things here: I suggest that your validateForm() function triggers in an onClick on your submit-button, right? Does your button look somewhat like this?
<input type="submit" value="submit" onClick="validateForm()">
If this is the case, the reason why your styles work only for few seconds is simply that the website reloads. The styles are in effect, but the form is also triggering and send to the site, which you added in your <form action>. After reloading, the website will fall back to its default style, as if the errors never occured... which is correct on that instance of the site.
If you want to have it permanent, you have to disable the submit-button as long as there are invalid fields. You can make use of the required attribute for form elements as well, since the form won't submit as long as there are invalid fields. These can be styled as well.
Have a look at these CSS rules for that:
/* style all elements with a required attribute */
:required {
background: red;
}
You can make use of jQuery as well and disable the form-submit with preventDefault. You can take care of every style and adjust accordingly, as long as there empty / non-valid characters in your input-fields. I suggest combining this with the onKeyUp-function. This way you check everytime the users releases a key and can react as soon as your input is valid.
As an example with jQuery:
var $fname = $('#<%=UserFnameTextBox.ClientID%>');
var $textBox = $('#WarnUserFnameTextBox');
$fname.on("input", function() {
var $this = $(this);
if($this.val() == "") {
$textBox.show();
$this.focus().css("border", "1px solid red");
}
});
(thanks for pointing out my errors and optimizing the code, #mplungjan!).
To "disable" the actual form-submission, refer to this answer:
https://stackoverflow.com/a/6462306/3372043
$("#yourFormID").submit(function(e){
return false;
});
This is untested, feel free to point out my mistake, since I can't check it right now. You can play around on how you want to approach your "errorhandling", maybe switch to onKeyDown() or change(), that kind of depends on your needs / usecase.
Since your question isn't tagged with jQuery, have a look at this answer given by mplungjan as well, since it uses native JS without any framework.
https://stackoverflow.com/a/53777747/3372043
This is likely what you want. It will stop the form from being submitted and is reusing the field and resetting if no error
It assumes <form id="myForm"
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var field = document.getElementById('<%=UserFnameTextBox.ClientID%>');
var error = field.value.trim() === "";
document.getElementById("WarnUserFnameTextBox").style.opacity = error ? "1" : "0"; // or style.display=error?"block":"none";
field.style.borderColor = error ? "red" : "black"; // reset if no error
if (error) {
field.focus();
e.preventDefault();
}
});
});
I am writing a little Meteor app. There is a textarea in a form, which looks like this:
<form name="comments-form">
<label for="textarea">Comment:</label><br>
<textarea cols="40" rows="10" name="comment_textarea" class="comment_textarea">Write your comment here.</textarea><br>
<button class="btn btn-success js-add-comment">add comment</button>
</form>
In my client.js I have the following code for accessing the value of the textarea:
EVENT_HANDLED = false;
Template.website_item_details.events({
"click .js-add-comment": function(event) {
var comment_text = event.target.comment_textarea.value;
if(Meteor.user()) {
Comments.insert({
created_by: Meteor.user()._id,
text: comment_text,
website_id: this._id
});
}
return EVENT_HANDLED;
}
});
However, when I click the button to add the comment, I get the following console output:
TypeError: event.target.comment_textarea is undefined
["click .js-add-comment"]()
client.js:103
Template.prototype.events/eventMap2[k]</</<()
blaze.js:3697
Template._withTemplateInstanceFunc()
blaze.js:3671
Template.prototype.events/eventMap2[k]</<()
blaze.js:3696
attached_eventMaps/</</</<()
blaze.js:2557
Blaze._withCurrentView()
blaze.js:2211
attached_eventMaps/</</<()
blaze.js:2556
HandlerRec/this.delegatedHandler</<()
blaze.js:833
jQuery.event.dispatch()
jquery.js:4690
jQuery.event.add/elemData.handle()
This seems to be basic form handling, but somehow I can't get that text in the textarea into a variable in my javascript code. I've already tried a multitude of variants of accessing it:
document.getElementsByClass()[0].value
$('.comment_textarea').get(0).val() // there should only be one such text area anyway
event.target.comment_textarea.value;
But none of those work for me, I always get that error. It's almost like the textarea was not part of my html or there is a bug in Meteor, which prevents me from accessing textareas.
I also checked whether there are other things named comment_textarea with a fulltext search on all of my projects clientside files, but there isn't any other.
Am I simply blind and overlooking something? How do I get that text?
What's more is, that although I return false, the browser still reloads the page. Could it be related to the error happening before?
You are using the click event of the button and on that event, the textarea is not available. You need to change the event into submit form. First, put the id into your form, change the button into type submit and change the code into
"submit #your-form-id": function(event) {
event.preventDefault();
var comment_text = event.target.comment_textarea.value;
.....
}
After trying even more desperate ways to access that textarea, I think I know now what's wrong:
// var comment_text = event.target.comment_textarea.value;
// var comment_text = document.getElementByName('comment_textarea').value;
// var comment_text = document.getElementByTagName('textarea')[0].value;
// var comment_text = $('textarea').get(0).val();
// var comment_text = $('textarea').get(0).text();
var comment_text = $('textarea').get(0).value; // finally working!
So it seems that when I use jQuery, I can't use the .val() function as stated in my other answers to many other questions, but for some reason I have to treat it like a normal DOM object and use the attribute value instead of the function .val().
Maybe it's specific to the jQuery version in my Meteor app?
So I will test the following:
var comment_text = $('textarea.comment_textarea').get(0).value;
...
Yes, that also works.
Also it fixes the reload issue. I guess since there was an error, it didn't even get to return false and this is why the website reloaded.
I have 4 forms on 1 page, one for each package. Can I use the form's onclick to establish a var and use it in the jquery function? The jquery function is included in a js file assigned to the the page. Just want to access the var in the jquery function for a specific form to be submitted.
<form action="javascript:" method="POST" id="buy-form_2"
onclick="javascript:$thisform='buy-form_2';" >
var thisformtext = "#"+$thisform;
$(document).ready(function()
{
$(thisformtext).submit(function(event)
{
i may or may not be close but this one escapes me...
Very curious
Edit: ended up using:
$('form').submit(function(event){
window.buyform = '#'+"buy-form_"+$(this).attr('id').slice(-1);//alert(buyform);
.......
}
I know window.var is overloaded but beats 4 X 12 jquery functions
Thanks for the help!
W
if you only want to differentiate form, you can have id check.
$(document).ready(function(){
$('form').submit(function(event){
if($(this).attr('id') == 'buy-form_2'){
............
}
});
});
I'm trying to use Jquery in order to validate a form's input. On top of that, I want to auto-fill some fields if they are left blank.
Here is how I proceed :
$(form).submit(function () {
var result = true;
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
if ($("#newStartTime").val().length == 0) $("#newStartTime").val("00:00");
if (!timeRegex.test($("#newStartTime").val())) {
$("#newStartTime").wrap("<div class='error' />");
result = false;
}
return result;
});
What's happening here is that the input is set to 00:00, but the submit is rejected (and the field wrapped as an error). If I re-click on submit, it works fine.
The way I see things, Jquery doesn't treat the modifications made after the 'submit' was called.
If that's the case, is there a way to achieve what I want without using ".submit()" twice ?
If I'm mistaken, what's wrong ?
You can add an event listener on the submit button click
by example :
$('#submit_button').click(function() {
var newValue = $('#field1_real').val();
$('#field1').val(newValue);
$('#form1').submit();
});
Regarding the blank fields, it would be best to have the server handle the default values rather than Javascript. It could provide the defaults when the Form is sent to the browser, or apply defaults if their missing when the browser submits the Form.
It keeps the hack out of your JS, and will still work if JS is disabled.
$(form).submit(function() {
.
.
.
});
Here, form means ID of the form?
If it is Id, try like this
$('#formId").submit(function() {
.
.
.
});
I'm trying to do a pretty simple thing, I believe. I need to popup a success confirmation dialog after a user clicks to add someone to his friends list. Simply there's an add link on the page with the url (mysite.com/add/friendname). I needed to make issue this request asynchronously so I used jQuery.ajax built-in function to send the request. Take a look at the following code:
$(document).ready(function() {
$('.track_links').click(function() {
if (confirm("are you sure you want to track <firstname lastname>?")) {
$.ajax({
type: "GET",
url: this.href,
success: function() {
alert("Congratulation! you're now tracking <firstname lastname>");
},
error: function() {
alert("Oops! An error occured, plz try again later!");
}
});
return false;
}
else {
return false;
}
});
});
Now, here's what I need to do in short:
1- I need to use an already designed Html form as the success or failure confirmation message, instead of just alerting!
2- I also need to replace a placeholder (###username###) on that html page with the actual user name (firstname space lastname) which is the value of another field on the document. How to manipulate this html before poping it up on the client?
p.s: My Html/Javascript skills is totally awesome ;) (well, not really)!
For the first part
You can use the
show
function to show a div in the ajax success function.
$("#divResult").show();
if divResult is the id of the div to be shown
For the second part
you can get the value of first name and last name using
$("#txtFirstname" ).val();
and
$("#txtLastname" ).val();
if your first name text box id is txtFirstname and last name text box id is txtLastName
This is how I setup an Acknowledgement dialog, which could quickly be modified to be a confirmation for an action like yours.
http://professionalaspnet.com/archive/2009/06/02/Displaying-a-Confirmation-Dialog-with-the-JQuery-UI-Dialog.aspx
For the Form, I would suggest the html() Method, which injects raw HTML you have to provide. Since you already have it, you can give it to the Method via parameters.
For the Placeholder Part, I would suggest the val() Methods, coupled with Javascript's built-in regex functions.
If your placeholder is "###firstname###", then you should try something like
var firstname = jQuery('input#firstname').val();
var lastname = jQuery('input#lastname').val();
var text = jQuery('span#ThePlaceMyPlaceholderIsAt').text();
text = text.replace(/\#\#\#firstname\#\#\#/,firstname);
text = text.replace(/\#\#\#lastname\#\#\#/,lastname);
jQuery('span#ThePlaceMyPlaceholderIsAt').text(text);