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() {
.
.
.
});
Related
here is the function from inside a script
function dosubmit()
{
if (getObj("Frm_Username").value == "")
{
getObj("errmsg").innerHTML = "Username cannot be empty.";
getObj("myLayer").style.visibility = "visible" ;
return;
}
else
{
getObj("LoginId").disabled = true;
getObj("Frm_Logintoken").value = "3";
document.fLogin.submit();
}
}
i want to get the value of getObj("Frm_Logintoken")
as i can't pull the value from #Frm_Logintoken
using document.getElementById("#Frm_Logintoken")
this gives me null
because Frm_Logintoken only gets it's value when i click submit .
<input type="hidden" name="Frm_Logintoken" id="Frm_Logintoken" value="">
full page code
i found this online /getObj\("Frm_Logintoken"\).value = "(.*)";/g
but when i run it ... it gives me the same line again !
it's full code
https://hastebin.com/gurosatuna.xml
First:
Your checking if a value is empty with JS. However this is NOT needed as HTML does this for you. Add a attribute required and the form will not submit as long this value is empty
Documentation: https://www.w3schools.com/tags/att_input_required.asp
Second:
You could use the event handler 'on submit'. The code is not complete enough to know if u did this but I suppose you just added a Click handler on the button.
Documentation: https://www.w3schools.com/jsref/event_onsubmit.asp
When combining these two, you always have a username filled in and the code only executes when submitted. I hope this helps, if not please leave a comment and I will edit this answer.
EDIT: the answer on this SO will also help (not the checked on but the one below)
How can I listen to the form submit event in javascript?
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 created a server control for a login panel.
On this panel I have a textbox for the username and a textbox for the password.
Below that there is the button for login.
I want the button to be disabled if either or both textboxes are empty.
For that I created a function that checks the length of the contents of the textboxes.
function doCheck()
{
var lngth1 = document.getElementById('pnLogin_txtUserName').value.length;
var lngth2 = document.getElementById('pnLogin_txtPassword').value.length;
if (lngth1 > 0 && lngth2 > 0)
{
$('#pnLogin_btLogin').removeAttr('disabled');
} else {
$('#pnLogin_btLogin').attr('disabled','disabled');
}
}
I run this function at the start and on every keyup event.
That works great.
The problem is when the browser starts with the page. It fills in the username and password if they are stored.
When the function is then run, it still disables the button even though there is information in the textboxes.
I tried this:
setTimeout( function()
{
doCheck();
}, 2000);
But after 2 seconds I see the button disabling while seeing my credentials filled in.
If I inspect the element in Chrome, I don't see my credentials in the html code.
So where is it stored? How can I detect this?
You will not see the values in the html as they are not actually in the DOM.
You may access their values using $("#pnLogin_txtUserName").val() and
$("#pnLogin_txtPassword").val().
I would simplify your function and use jQuery specific syntax rather than native javascript.
function doCheck() {
var lngth1 = $("#pnLogin_txtUserName").val().length;
var lngth2 = $("#pnLogin_txtPassword").val().length;
if (lngth1 > 0 && lngth2 > 0) {
$('#pnLogin_btLogin').prop('disabled', false);
} else {
$('#pnLogin_btLogin').prop('disabled', true);
}
}
I also changed your code from .attr to .prop for disabling the input. Find more information with this stackoverflow question
The problem is when the browser starts with the page. It fills in the username and password if they are stored. When the function is then run, it still disables the button even though there is information in the textboxes.
Your code is being executed the moment it is loaded and parsed by the browser. The proper jQuery method is to use whats called .ready() which will execute after jQuery detects the page has finished loading.
$(document).ready( function() {
doCheck();
});
Or more simplified to:
$(function() {
doCheck();
});
detecting change
We can detect when the values get changed by bind an event listener:
$("pnLogin_txtUserName").change(function() {
console.log( 'pnLogin_txtUserName has changed', $(this).val() );
});
If we add a class to your inputs, say .loginElements, then we do things a bit easier and detect several different events:
$(".loginElements").on( 'change keypress', function() {
doCheck();
});
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.