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.
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();
}
});
});
There are several questions/answers on this here, here and here and elsewhere, but they all seem JQuery specific and do not appear to apply to this (for example, I am NOT creating a new Form object, this is an existing form in the document. Also I am NOT using Jquery at all).
I have a form which has to be modified before submission for reasons of IE7 compatibility. I have to strip out all the BUTTON tags from my form and then add a hidden field, but this is all in an existing form on the existing HTML page. This code works properly in IE and Chrome but doesn't work in Firefox (versions 23 & 24 both tested).
buttonClickFunction(formName, buttonObject) {
var formObject = document.forms[formName];
var i = 0;
// Strip out BUTTON objects
for (i=0;i<formObject.length;i++) {
if (formObject[i].tagName === 'BUTTON') {
formObject[i].parentNode.removeChild(formObject[i]);
i--;
}
}
// Create new field
var newField = document.createElement('input');
newField.type = 'hidden';
newField.id=buttonObject.id;
newField.name = buttonObject.name;
if (buttonObject.attributes['value'] != null) {
newField.value = buttonObject.attributes['value'].value;
} else {
newField.value = buttonObject.value;
}
// Submit form
formObject.appendChild(newField);
document.forms[formName].appendChild(newField);
document.forms[formName].submit();
}
In addition to the document.forms[formName].submit() I have also tried formObject.submit() - both work in Chrome but both fail in Firefox. I'm at a loss as to why this doesn't work - I've traced through the JS and watched that document.forms[formName].submit() execute - no exception appears but nothing goes to the server.
Can anyone identify why Firefox won't submit this form, and how I can fix it?
Firefox expects that, when you submit a form, you have at least a submit button available, meaning there should be something like:
<button type="submit">Click me</button>
or:
<input type="submit" value="Click me" />
When you use the first one in your code, it will not work (because you strip out all buttons before submitting the form). When you use the second option, it will work, also in Firefox. As you can see in this fiddle: http://jsfiddle.net/q9Dzc/1/
I had similar behaviour, when form.submit() didn't work on Firefox, but worked on other browsers. Just make sure that all the buttons within form contain type="button".
For anyone having an issue with making the Firefox submit with the page location changing / reloading afterwards, you need to put your redirect code in the $.post callback:
$(".form").submit(function(e){
e.preventDefault();
$.post("submit.php", {data: textData}, function(){
history.go(-1);
});
return false;
});
If your form has a mixture set of "input [type=button]" and "button", the JavaScript of submit() will not work for "input [type=button]" sometimes.
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 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.
I am trying to pop up a confirmation modal when the user presses the delete button on the edit form. The modal pops up fine, but when jQuery should be submitting the form, it's not doing anything. I have delete as a type="button", because when it is of type submit the modal function does not hold up the process and it just deletes the user right away.
The HTML ...
-- EDIT --
(I added the <form> tags)
<form action="/admin/edit-user" enctype="application/x-www-form-urlencoded" method="post" name="edit_user_form" id="edit_user_form">
...
<p><input type="submit" value="Save" name="submit" id="submit"/></p>
<p><input type="submit" value="Cancel" name="cancel" id="cancel"/></p>
<p><input type="button" value="Delete User" name="delete_btn" id="delete_btn" onclick="confirmDeleteUser();"/></p>
...
</form>
...
<div id="dialog-modal" title="Confirm Delete User">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> Are you sure you wish to delete this user?</p>
<p>To continue editing, click cancel.</p>
</div>
The Javascript:
function confirmDeleteUser()
{
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.attr('name', 'delete');
tmpElm.attr('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
$('#dialog-modal').dialog('open');
}
When I inspect the source, I'm seeing that the code is properly appending the new hidden element, but the submit just doesn't seem to want to fire. What step am I missing?
Try it a different way.
HTML
Your html has the following: onclick="confirmDeleteUser();"
Why? jQuery is supposed to make this easier for you, not harder.
Your HTML should be pure and not calling functions (with the exception of ultra-extreme circumstances you are very unlikely to encounter). Why not use the jQuery library to bind the event to the element, rather than mix javascript function calls into your HTML? You should be doing something like this in the <script> tags, after a document ready statement.
$("#delete_btn").click(function(e){
/*Code that runs on click of the "delete_btn" ID tag*/
});
If you're unfamiliar with jQuery selectors and events then start reading here.
You can find all the events here.
You can find all the selectors here
The other reason you should do this is in the event the document isn't correctly/fully loaded in order to prevent it from breaking on your users.
CSS
You've also done this: style="float:left; margin:0 7px 0 0;" in an HTML tag? That's evil, dude. Just evil. How am I going to maintain this code in five months?
Instead, use CSS.
In your tags, or CSS file, you need an entry such as:
.dialogAdjust {
float: left;
margin: 0 7px 0 0;
}
Then in your HTML you would say:
<span class="ui-icon ui-icon-alert dialogAdjust"></span>
And now you can tweak the thing to your heart's content. It's better if you can make the class on the dialog div, rather than individual HTML elements, and in this case you absolutely can.
JavaScript
Hokay, so, here's your function:
function confirmDeleteUser()
{
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
$('#dialog-modal').dialog('open');
}
What's going on here? First step, you should try and use a tool to measure code quality. Two popular ones are JSHint and JSLint. You don't need to follow things they say like it's the only way to write your code, but it's immensely helpful in finding bugs due to small mistakes. I like JSHint, so we're going to run it through that.
And here's the output:
Errors:
Line 17 tmpElm = $('<input type="hidden" />');
'tmpElm' is not defined.
Line 18 tmpElm.attr('name', 'delete');
'tmpElm' is not defined.
Line 19 tmpElm.attr('id', 'delete');
'tmpElm' is not defined.
Line 20 tmpElm.val(true);
'tmpElm' is not defined.
Line 21 tmpElm.appendTo(form);
'tmpElm' is not defined.
Oops. Looks like you've got an undefined variable in there, meaning it's now global. Global variables are bad, they break scope and can make your code function in strange ways.
We need to fix that. You should always declare local variables in local scope. That means putting a var tempElm; at the top of the "Delete User" function.
Do away with that function wrapper, you won't need it. Your code should create the dialog object and code when the document is done loading, and open the dialog when it's clicked. What is happening in your original code both creating the dialog and opening it every time you click that button. What's the problem with that? You keep creating the object, even though it's created. You're creating the same object again and again and again. In this implementation, you won't notice it, but your design will carry over to places it will unless you take notice of this now.
So, what does that look like? In your <head> tag you should see something like this:
<script>
/*
This makes all the code inside
run when the window is done loading,
not before, which may cause issues.
*/
$(window).load(function(){
/*
This sets up the dialog
as you've described before
*/
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
//We've added the var infront of tepElem
var tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
/*
This is the part where I talked
about selectors and events in the HTML
*/
$("#delete_btn").click(function(e){
$('#dialog-modal').dialog('open');
});
});
</script>
When asking for help, use a tool like jsFiddle to post JavaScript in to make it easier for other people to help you.
Here's a jsFiddle of the revisions we've made so far. Spend a bit of time learning how to use it if you're doing a lot of work in JavaScript and want to test something really quickly.
Here's why I wanted you to learn jsFiddle:
You didn't give us enough code to work with successfully, thus leading to me writing this huge post about code quality and how to ask questions, doubly so when you post a bounty.
If you want help, don't make people work really hard for it. You won't get good help unless someone is totally insane.
jsFiddle requires you post actual working code (or non-working code) that lets us see if there's a problem with form.submit(), such as any strange attributes or properties on the form element, or any number of other issues that could be kicking around that you excluded.
So let's look at what's breaking your "Delete User" function.
function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
Why have you declared self? You never use it once. Lets get rid of that.
You could use something called chaining, it's really up to you. Some people hate it.
You append a whole new input to the form for something that looks like a choice, I'm not sure this is wise. I'd suggest changing the value of a normal input, or using another pattern, this could lead to a lot of issues, but for the sake of the question I'll imagine it's done for all the right reasons. Be careful however, if someone double clicks submit, that input's in there two times.
form is a word reserved by used in the DOM, you should avoid using that one to avoid confusion between your variable and the DOM API.
Which form submission button are we clicking here? You have a lot, and jQuery isn't going to guess and hope for the best.
How forms should look:
The w3 explains what forms are and the purpose of things.
Key points:
Names are paired with values
The submit button clicked is sent, the submit buttons not clicked are not.
The DOM is can be navigated based on NAME and ID attributes
Something weird is going on in your form.
Here's a form that javascript understands how to submit:
http://jsfiddle.net/YS8uW/2/
Here's javascript attempting to submit your form (stripped down to bare-bones):
http://jsfiddle.net/LfDXh/
What's different here?
You have IDs all over the place.
You use keywords for names
Lets look at something you've done, given an ID of submit to something:
http://jsfiddle.net/fdLfC/
And what happens when we don't use that as an ID?
http://jsfiddle.net/fdLfC/1/
Ahh. So that's weird.
It's like giving it an id of submit won't let you call submit. A proper explanation is, you've re-written it because the dom did it when you assigned that ID and Name, it's trying to call the element.
You can see this if you open up a debugger or something, it gives you an alert to the effect of:
TypeError: Property 'submit' of object # is not a function
Keep away from using keywords to mean something else and you won't fall into these weird traps.
A big thank you to #MattMcDonald for linking me to this resource, which explains how to deal with, and why, NAME and ID attributes over-write the built-in HTML DOM methods.
Do the other stuff I said too. Disclaimer: Everyone's going to wage war on me saying it's not absolute that you should be doing all those things, I agree, but I think this post is long enough, and we'll all agree that doing these things is a step forward in code quality, not backwards. It's up to you at the end, but try avoiding mixing things together into a huge messy pot. Think about the execution of your code and how it's happening also.
If you are sure it appends the hidden input, then the problem must be in using duplicate ID.
The button and the hidden input have the same ID. Make them different and try again.
Dont ask me the reason why it worked, all i can tell you is after doing this and that and tearing each part of your code, finally i made it work. click below link to see the demo
http://jsfiddle.net/praveen_prasad/KaK5A/4/
The changes i made are: removed id and name attributes from submit buttons from form
Example:
<input type="submit" value="Save" name="submit" id="submit"/>
changed above to below
<input type="submit" value="Save" />
Note For JsFiddle Demo: when you will click delete user on modal, form will submit. jsfiddle will say "Error 404", as it wont find the link you are posting your form. Open firebug and see that its actually posting to correct url.
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.attr('name', 'delete');
tmpElm.attr('id', 'delete');
tmpElm.val(true); // HERE ----------------
tmpElm.appendTo(form);
form.submit();
return true;
}
At the designated location, shouldn't it be :
tmpElm.value(true);
or
tmpElm.attr('value', 'true');
I find it less confusing to handle my form submits upon confirms via jQuery ajax with serialized form values. It has the added benefit of avoiding unwanted form submits from buttons inside the <form> tags. So, it would look something like this:
<form id="edit_user_form">
...
<button id="submit_btn">Submit</button><br />
<button id="cancel_btn">Cancel</button><br />
<button id="delete_btn">Delete</button>
...
</form>
And then the javascript:
$('#delete_btn').click(function() {
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
$.ajax({
url: "/admin/edit-user",
type: "POST",
data: $('#edit_user_form).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred: " + errorThrown);
},
success: function(){
//Notify of success, redirect, etc.
}
});
}
}
});
});
So, it still submits via a POST. It now can happen asynchronously (or not) You can "do things" on success without changing the page, or alternatively redirect as you might need. I use a "dispatcher" page to submit to my object oriented framework, which then returns the output back to the PHP dispatcher to be json_encoded and echoed as a string for the AJAX call to use on success. Using this pattern, I only have to have one page that spits out plain text and the rest can reside in my OO Classes, which can't be called directly by ajax without doing some serious clooging (by using xajax)