Given this code, it never works and always returns true whatsoever ?
<form id="my-form" data-validate="parsley">
<p>
<label for="username">Username * :</label>
<input type="text" id="username" name="username" data-required="true" >
</p>
<p>
<label for="email">Email Address * :</label>
<input type="text" id="email" name="email" data-required="true" >
</p>
<br/>
<!-- Validate all the form fields by clicking this button -->
<a class="btn btn-danger" id="validate" >Validate All</a>
</form>
<script>
var $form = $('#my-form');
$('#validate').click (function () {
if ( $form.parsley('validate') )
console.log ( 'valid' ); <-- always goes here
else
console.log ('invalid');
});
</script>
So my question is if there is a way to trigger parsley validation without adding a submit button ?
$form.parsley('validate') is 1.x API. It was deprecated in 2.x versions you might use.
Try $form.parsley().validate() instead.
Best
I've been searching high and low to try and make the form validation work with a non-form tag.
I guess my biggest gripe with the framework is that it doesn't work out-of-the-box with non-form elements.
I would be ok using a form element if it didn't scroll to the top of the page every time it tries to validate. Because this behavior is inherent in how form works, there is only this hack to fix it.
Just as a side note, using data-parsley-validate attribute on the div tag also works. You can also initialise the form as normal (meaning you can subscribe to the validation).
example html:
<div id="signupForm" data-parsley-validate>
... put form inputs here ...
<button id="signupBtn">Sign me up</button>
</div>
Just make sure to put js in:
var $selector = $('#signupForm'),
form = $selector.parsley();
form.subscribe('parsley:form:success', function (e) {
...
});
$selector.find('button').click(function () {
form.validate();
});
if you put type="button" on the button, it won't refresh and scroll to top of page when clicked.
Related
I want to create an authentification page and the design is almost finish :)
I just want to add a last thing to my page.
I want that if the form is not fully completed (a box is missing for example), the submit button is grey and not clickable. And if the whole form is filled in, the button become blue and clickable.
The problem is that I don't know JavaScript (I'm beginner)...
Here is my form :
<form method="post" action="traitement.php">
<div class="text">
<div class="group">
<label for="username">Téléphone, email ou nom d'utilisateur</label>
<input type="text" name="username" id="username" autofocus required class="champs" />
</div>
<div class="group">
<label for="password">Mot de passe</label>
<input type="password" name="password" id="password" required class="champs" />
</div>
<input type="submit" value="Se connecter" id="button" disabled="disabled" />
</div>
</form>
Do you think it's possible with only CSS ?
Can you help me please ?
Thank you in advance :)
You ask a generic question, so I can only give you a generic answer:
In theory, there might be cases where you can work with CSS only. But in practice, you will most probably need JavaScript. Using a framework that supports form input validation would be more comfortable.
If you want to have a more specific answer, you need to provide more details, e.g. what exactly you want to validate. But maybe my answer is already helpful.
There is a simple solution to this and it looks like this
<form method="post" action="traitement.php" id="loginForm">
First add the id to your form and then create a JS script that will look like this
document.getElementById("loginForm").addEventListener("keyup", function() {
var userInput = document.getElementById('username').value;
var passInput = document.getElementById('password').value;
if (userInput !== '' && passInput !== '') {
document.getElementById('button').removeAttribute("disabled");
} else {
document.getElementById('button').setAttribute("disabled", null);
}
});
On every keystroke it will check if both inputs have value and enable/disable button accordingly
I'd like to know how to initiate the certain javascript functions to make a label red or have a pop up saying an empty field etc with the twitter bootstrap.
I have a form like so:
<form role="myForm" id="sign-up-form" method="post" action="/sign-up">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1">
</div>
<input type="submit" value="Next: Connect Shopify" class="btn btn-success">
</form>
I have a route like so:
app.post("/sign-up", function (req, res) {
console.log(req.body);
res.render('sign-up');
});
I'd like to know how to handle the form validation. Like if a space is empty, with Bootstrap javascript, I can make it red or have a pop up. How can I do this?
You could use the onChange event on the form to call a validation function. Then change the css use the .style() method.
So,here's what I am getting from your question. You want JS function to
validate input
change ui of label
or add a pop-up to alert that user has left that field blank
This all can be done simply by JavaScript or JQuery.
If we follow template (HTML) you provided in your question then, below script will do what you want. I have also added necessary comments to help you out.
<input id="submit" type="submit" value="Next: Connect Shopify" class="btn btn-success" onClick="submit()">
This is a very basic function to give you an idea how you can change style using javascript and see some field's value.
function submit() {
if (document.getElementById('exampleInputEmail1') === '' || typeof document.getElementById('exampleInputEmail1') === 'undefined') {
document.getElementById('exampleInputEmail1').style.color = 'red';
return;
} else if (document.getElementById('exampleInputPassword1') === '' || typeof document.getElementById('exampleInputPassword1') === 'undefined') {
document.getElementById('exampleInputEmail1').style.color = 'red';
return;
}
return;
}
However, I would suggest you should use Jquery to do these kind of things. And also you can use required attribute in input fields to make sure user must add something in the field.
I've been trying for some time now (some time = whole day) to figure out why I have this strange problem with my form. I have a client who wants a stand-alone HTML page running locally which would display one form with couple of textbox and one button. After info is entered and user click that button, a second form should show up with new textboxes. Form can't have a redirection to another website or file. It all has to be in that (HTML) file.
I figured out this would be easiest to do with jQuery but loading whole library just to hide one form is plain stupid. So I take a look at other option and decided to use pure Javascript.
The problem is when I click "NEXT" first time the 1st form disappear but then apear a second later like some sort of request is sent. Bellow is the code I currently have. I tried making an JSFiddle but browser blocks every time I access it.
Javascript:
function hideAll() {
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'none';
showFirstForm();
}
function showFirstForm() {
if (document.getElementById('second').style.display == 'block') {
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'none';
}
}
function showSecondForm() {
if (document.getElementById('first').style.display == 'block')
{
document.getElementById('second').style.display = 'block';
document.getElementById('first').style.display = 'none';
}
}
HTML:
<body class="if5" onload="hideAll()"> // I'm loading hideAll() on refresh to hide second form
....
<!-- FORM 2 -->
<form id="first" action="#" class='tx_anmelden' method="post" autocomplete="off" >
<filedset>
<label for="name"> Your name </label>
<input name="name" value="MyName" /></input>
<button onClick="showFirstForm()">Next</button>
</filedset>
</form>
<!-- FORM 1 -->
<form id="second" class='tx_anmelden'>
<fieldset>
<label for="name"> Your name </label>
<input name="name" value="MyNaffffffme" /></input>
<button onClick="showSecondForm()">Next</button>
</fieldset>
</form>
....
References:
getElementByID
Besides the fact that you have your form id's switched, <button> has a default type of submit. So when your button is clicked it is posting the form to #. So correct your form ids, and then change your button code type to button:
<button type="button" onClick="showSecondForm()">Next</button>
Here are some docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
Here is a working jsfiddle using the corrected code: http://jsfiddle.net/789SP/
First off, any button in a form that doesn't have a type attribute or has a type attribute of submit will by default submit the form on click.
Second, it looks like you are trying to implement some sort of wizard. If this is true you don't want each part to be it's own form because at the end you're going to want to send all of this data to the server which won't work if it's in two forms.
The entire thing needs to be in one form with sections inside that you show/hide. To navigate between the sections you'll want to use
<button type="button" onClick="showSecondForm()">Next</button>
To do wizards is always a pain in the butt. Once you start handling validation you need to figure out which step has an error in it and show that section, or if the user uses the back button they might expect the form to go back to step one. You might want to search for a third party solution that provides some of the boiler plate functionality. These might help
This should get you off to a good start though.
Edit
Don't attempt this from scratch. Use this
<!-- FORM 2 -->
<form id="first" action="#" class='tx_anmelden' method="post" autocomplete="off" >
<fieldset> **fieldset was misspelled as "filedset"**
<label for="name"> Your name </label>
<input name="name" value="MyName"></input> **your input had /> at it's end, which is unfortunately wrong**
<button onClick="showFirstForm()">Next</button>
</fieldset> **fieldset was misspelled as "filedset"**
</form>
<!-- FORM 1 -->
<form id="second" class='tx_anmelden'>
<fieldset>
<label for="name"> Your name </label>
<input name="name" value="MyNaffffffme"></input> **your input again had /> at it's end, which is unfortunately wrong**
<button onClick="showSecondForm()">Next</button>
</fieldset>
</form>
I'm trying to find a cross browser compatible way of picking out the id attribute of a button that is clicked during a form submit that has two different submit buttons. I was able to accomplish this for FireFox with the following, but it won't work in IE 8 or Chrome because they don't support explicitOriginalTarget.
$("#postForm, #dialogPostForm, #pastPostForm").live('submit', function(event) {
event.preventDefault();
if (event.originalEvent.explicitOriginalTarget.id === 'pastPosts'){
...SNIP...
Can someone suggest a cross browser compatible way to do this?
UPDATE I've tried using the answer from How can I get the button that caused the submit from the form submit event?, but I'd like to use the .live jquery method and use the event object to select the originating input submit id.
UPDATE Here is my form that I am trying to get the originating submit button id from:
<form id="postForm" action="{% url account_tracker mashup.pk %}?fuzzy=true" method="post">
<div class="mygoal">Update Your Progress: {{ form.post }}
<input type="submit" value="+ 1" class="formbtn" style="font-size:18px;"/>
<input type="submit" value="This week" style="font-size:18px;" id="pastPosts" class="formbtn"/>
<span id="result" class="results"></span>
</div>
</form>
UPDATE I came up with my own solution. Add an onclick attribute that adds a "name" attribute to the form. Then in the form processing check if the form name is "past" and do something with it then remove the attribute after the form is finished processing. This works on all browsers as far as I can tell.
<input type="submit" value="This week" style="font-size:18px;" id="pastPosts" class="formbtn" onclick="$('#postForm').attr('name', 'past');" />
There is no alternative.
That is a Firefox-only property.
This is a really old question and needs to be answered.
I've Googled about this and found a solution on http://www.webmuse.co.uk/blog/using-forms-with-multiple-submit-buttons-and-jquery-events/
Basically, try to get the focused element.
An example:
(function($){
$(document).ready(function(){
$('#user_form').submit(function(event){
event.preventDefault(); //stops submission
$('#name_submit')
.text(
//searches all the submit buttons
$('input[type="submit"], button[type="submit"]',this)
.filter(':focus') //finds the focused one
.attr('name') //takes the name
);
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<form action="#" id="user_form">
<input type="email" placeholder="Email"/><br>
<input type="password" placeholder="Password"/><br>
<input type="submit" name="login" value="Login"/>
<input type="submit" name="register" value="Register"/>
</form>
<br>
Clicked submit name: <span id="name_submit">(none)</span>
I've tested this and it works in IE7 and Firefox (at least the current version).
Given:
<div id="parent">
<div id="child">
clicky
</div>
</div>
We can apply the following logic: (UPDATED)
$('#parent').live('click', function(e){
var target = e.originalEvent || e.originalTarget;
console.log($(target.srcElement || target.originalTarget).attr('id'));
});
This gives me 'child' in Chrome, IE9, and FF8 if I click on child.
I'm working on a simple javascript login for a site, and have come up with this:
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify.
1. Your Immediate Concern:
(Why won't the input button work when ENTER is pressed?)
Use the submit button type.
<input type="submit".../>
..instead of
<input type="button".../>
Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
2. Security concerns:
#Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.
Is there some way I can do a user validation client-side?
Encrypting Ajax calls for authentication in jQuery
3. Other Issues:
Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).
The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
Instead of <input type="button">, use <input type="submit">. You can put your validation code in your form onsubmit handler:
<form id="loginwindow" onsubmit="validate(...)">
it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.
<input type="password" name="text1" onkeypress="detectKey(event)">
Maybe you can try this:
<form id="loginwindow" onsubmit='validate(text2.value,"username",text1.value,"password")'>
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="submit" value="Check In"/>
</p>
</form>
As others have pointed out, there are other problems with your solution. But this should answer your question.
Surely this is too unsecure as everyone can crack it in a second ...
-- only pseudo-secure way to do js-logins are the like:
<form action="http://www.mySite.com/" method="post" onsubmit="this.action+=this.theName.value+this.thePassword.value;">
Name: <input type="text" name="theName"><br>
Password: <input type="password" name="thePassword"><br>
<input type="submit" value="Login now">
</form>
My Thought = Massive security hole. Anyone can view the username and password.
More relevant to your question: - You have two events happening.
User clicks button.
User presses enter.
The enter key submits the form, but does not click the button.
By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.
Your code will then run for both events.