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.
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 am trying to remove a required attribute from an input on the fly. The general idea is I have a field that is set to required, this field has custom validation with the pattern attribute. When the user clicks a button I am attempting to remove the required field.
I have put together a fiddle here:
https://jsfiddle.net/paulmatos/t1p1wub3/
HTML:
<form>
<input type="text" oninvalid='this.setCustomValidity("Enter a number in the Specified Range");' oninput="try{setCustomValidity('')}catch(e){}" pattern="[0-9]" required="required" name="password" id="password" />
<input type="text" required="required" name="temp" />
<input type="submit" class="btn btn-primary form-control" value="Submit" />
<div class="btn btn-default removeReq">Remove Required</div>
</form>
Jquery:
$('.removeReq').click(function() {
$('#password').removeAttr('required');
});
The issue I am experiencing has to do with the order of submission.
If you click remove required, and then submit the form you will see that it works as intended.
However, if you do those steps in reverse order, click submit first, then remove and try and submit again, you will notice I am still getting the validation error on the first input.
Is there anyway to get around this with this intended functionality, I am trying to get this to work just with the html5 validation.
I did have a look at the fiddle and the only way I could get the behaviour you wanted was by literally detaching, cloning and reinserting the field. Works tho.
$('.removeReq').click(function() {
var password = $('#password').removeAttr('required oninvalid oninput pattern').detach().clone();
$('form').prepend(password);
});
https://jsfiddle.net/t1p1wub3/2/
Think you are getting this due to the code in the oninvalid handler. Try this.
$('.removeReq').click(function() {
$('#password').removeAttr('required oninvalid');
});
You can try this instead of removeAtt():
$('.removeReq').click(function() {
$('#password').prop('required', false);
});
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.
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 have a form with two inputs:
<input type="text" name="keyword" value="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" onfocus="wipe(this)"/>
and my JavaScript which gets rid of the pre-set value in form field as soon as you click it with your mouse is:
function wipe(obj)
{
obj.value="";
}
My question is, say the user doesn't type anything in the city field, how do I make it so that when the form is submitted the value for that field is empty and not the word City?
placeholder is a good attribute which can solve your problem its a past time history when we are used to using value for showing for which this textbox we have
<input type="text" name="keyword" placeholder="Search" />
if you still want to use java script modify your code something like this
<input type="text" name="keyword" value="Search" onfocus="wipe(this,'Search')" onblur="wipe2(this,'Search')"/>
<input type="text" name="city" value="City" onfocus="wipe(this,'City')" onblur="wipe2(this,'City')"/>
script function for second approch
function wipe(obj, str)
{
if(obj.value!=str){
obj.value="";}
}
function wipe2(obj, str)
{if(obj.value==""){
obj.value=str;}
}
You are using the wrong technique here. you should be using placeholder which is supported by most major browsers with the regular exception of IE. So if this is not a concern for you, you should definitely be using that. Especially, if you have a label element for that field. Otherwise you'd need to be checking for that input value on submission and see if it equals the string city
Just Declare a variable hasChanged and set it true when wipe function is called.Then call a function say 'SubmitFunction()'on the onclick function of Submit button.
<input type="text" name="keyword" value="Search" id="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" id="City" onfocus="wipe(this)"/>
<input type="submit" name="submit" value="submit" onclick="SubmitFunction();"/>
var hasChanged=false;
function wipe(obj)
{
hasChanged=true;
obj.value="";
}
function SubmitFunction()
{
if(hasChanged==false)
{
$("#City").val('');
}
}
at the time of submit why not check for value='city'
if(obj.value!='city')
{
//your code here
}
or if you have no problem in using jquery use watermark plugin this will handle browser compatibility problem also
Jquery Watermark
try this:
if($('input[name="city"]').val() && $('input[name="city"]').val() != 'city') { yourform.submit(); }
See How to prepopulate input text fields with prompting text which disappears on typing (jQuery) for some solutions to this. If you're okay with using HTML5, the best solution is probably to use "placeholder" instead of "value".
You should add one more attribute(eg. default <input type="text" name="keyword" default="Search" value="Search" onfocus="wipe(this)"/>) with value same as value attribute.
in on submit compare each form fields
function onSubmit(){
for (var fields in form)
if(form[fields].value== form[fields].getAttribute("default")){
form[fields].value = "";
}
}
}