Hide/Show form in HTML produce unusual result - javascript

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>

Related

Submit button clickable when form is filled in

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

Submit form with Javascript then handle with PHP

Not sure how I did this last time or else I wouldnt asking here but here is what I'm trying to do.
I have the usual basic form with a javascript function that will submit the form. Question is that after the form is submitted, I have an if statement in PHP that echos a that the form has been submitted. Any help would be greatly appreciated.
//PHP
if($_POST['submitDelete']){
echo "welcome, You form has been submitted";
}
//HTML
<form id="form_id" action="" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" TYPE="submit">
</form>
<button type="button" onclick="myFunction()">Submit</button>
//JAVASCRIPT
<script>
function myFunction() {
document.getElementById("form_id").submit();
}
</script>
I can't seem to trigger the if statement in PHP. I also tried using the form name in the if statement and that didnt work either.
A form element must be told where to submit its data to when the submit event takes place. This is accomplished by setting the action attribute value for the form. Leaving that attribute empty does not implicitly set the form to post back to the current page. So, if you want to have a single page form/form processor, you need the action to be set to the current page file name:
<form action="currentPageFileName.php" method="post">
Next, there's no reason a single page can't have multiple forms on it. In that case you would need multiple submit buttons, each tied to a specific form. For this reason, you can't just drop a submit button anywhere on the page that you like unless you add the form attribute to the button to tie it back to the form it is supposed to trigger the submit for. Also, if you simply place the submit button within the form element it "belongs" to, you don't have to worry about this.
Also, you have some invalid HTML with:
<input type="hidden" name="submitDelete" TYPE="submit">
An element may not have the same attribute repeated within it (the case that you type the attribute in makes no difference since HTML is not case-sensitive). So, that code would wind up simply creating a submit button.
Lastly, if all you want to do with your submit button is cause its related form to be submitted, there is no need for JavaScript at all. That is what submit buttons do by default.
So, in the end, you can get rid of the JavaScript in your code completely and change your HTML to this:
<form id="form_id" action="currentFileName.php" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" value="true">
</form>
<button type="submit" form="form_id">Submit</button>

How can I submit multiple dynamically generated forms with a single submit button using Javascript? [partial progress]

I am having a bit of trouble with some code. I am attempting to submit multiple forms. The first form is immediately visible, and the second can be added to the page when the user clicks an "Add Another Form" button (think of this like a referral system a user can add multiple referrals to).
So far I am able to submit one form and make more than one form appear on the page, however submitting any more than the first visible form is a challenge. Here is my code so far:
The form (all forms are clones):
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input id="name" type="text">
<input id="phone_number" type="text">
<input id="addanother" type="button" class="formBtn lrgBtn addanother" value="Add Another Form" >
<input type="hidden" name="retURL" value="https://www.example.com/thank-you/">
<input type="button" value="Submit Now" class="loopStarter multiRefHide formBtn" onclick="submitFormLoop()">
</form>
JavaScript for Form Submissions (SubmitFormLoop function):
var formCounter = 0;
var ellipsesCount = 0;
function submitFormLoop(){
if(typeof document.forms[formCounter]!= 'undefined'){
if($('.error:visible').length>0){
return false;
}
document.forms[formCounter].mySubmit.click()
if($('.error:visible').length>0) return false;
$('#submitting').show();
$('#supportCase').hide();
document.getElementById('submittingText').innerHTML = "Submitting your form(s)."
setInterval(function(){
ellipsesCount++;
var dots = new Array(ellipsesCount % 8).join('.');
document.getElementById('submittingText').innerHTML = "Submitting your form(s)" + dots;
}, 300);
setTimeout(function(){submitFormLoop()},1500)
formCounter++
}else{
window.location = "https://example.com/thank-you";
$('input[type="submit"],.addanother').hide()
formCounter = 0;
}
}
Again I can get the first one to submit, but I can't seem to get the function to loop. Any advice on this matter is very welcome, whether it is a small tweak or a recommendation to scrap my code completely.
Thank you all very much.
You cannot submit multiple form elements from the same page.
But you can get the behavior you desire two ways:
Submit the forms using AJAX (using XMLHttpRequest or a helper library like jQuery).
Reformat your inputs to use a single form element.
To do the latter, PHP programmers1 typically use the syntax:
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input name="contacts[0][name]" type="text">
<input name="contacts[0][phone_number]" type="text">
<input name="contacts[1][name]" type="text">
<input name="contacts[1][phone_number]" type="text">
<input name="contacts[2][name]" type="text">
<input name="contacts[2][phone_number]" type="text">
</form>
Notice the [<integer>] in the syntax. In PHP, the $_POST variable will contain data like these as an indexed array.
Your button can then add additional input elements in the same format:
<input name="contacts[3][name]" type="text">
<input name="contacts[3][phone_number]" type="text">
On form submission, you can then retrieve these fields like so:
foreach($_POST['contacts'] as $person){
echo $person['name'];
echo $person['phone_number'];
}
1 I assume you're using PHP since your form's endpoint is submission.php.

Trigger parsley validation without submit form?

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.

How to manually trigger AngularJS validation from a button outside of the form tags?

Given this code:
<div ng-controller="MyCtrl">
<form ng-submit="onSubmitted()">
Header inputs:
<input type="name" ng-model="sample" required/>
<input type="name" ng-model="sampleX" required/>
<input type="submit" value="This submit triggers validation. But I wanted to put this button at the end of the page"/>
</form>
<hr/>
Some other form here. Think line items
<hr />
<a class="btn" ng-click="/* what could should be put here, so this can trigger the firt form's validation, then submit? */">Wanted this submit button to trigger the validation+submit on the form in which this button doesn't belong</a>
</div>
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.onSubmitted = function() {
alert('submitted!');
};
}
I want the last button to trigger the validation(then submit when things are valid) on first form. As of now, only the button inside the form can trigger that form's validation and submission. Is there any possible way for a button outside the form to do that?
Live test: http://jsfiddle.net/dzjV4/1/
You can create directive which you can then attach to <a class="btn".... Check this jsfiddle
http://jsfiddle.net/dzjV4/2/
Note that I added to <input type='submit' id='clickMe'... and linked it with link at the bottom <a class='btn' linked="clickMe"...
for (control of $scope.[form name].$$controls) {
control.$setDirty();
control.$validate();
}
You can try the above codes. Make it running before submit.
Ideally there'd be a programmatic way to cause validation to re-run across a form. I have not investigated that completely but had a situation that required multiple controls to be re-validated based on different data in the scope -- without the user interacting with the individual controls. This arose because the form had two action buttons which each required different validation rules be in play when they were clicked.
The UI requirement changed before I fully implemented forcing re-validation but before it did I got most of what I needed by copying and then re-setting the form's data. This forced re-validation across the form within the current scope. Basically, it's along the lines of the following (not tested, but taken from the code that was working). In this case the form's data was bound to the properties in one object.
var formData = $parse(<form's model>);
var dataCopy = angular.copy( formData($scope) );
formData.assign( $scope, dataCopy );
This may or may not be acceptable, but if you can get away with the SUBMIT button being disabled until the form is completed, you can do this:
<form name="formName">
<input ng-required="true" />
</form>
<button ng-click="someFunction()" ng-disabled="formName.$invalid" />
It's also worth noting that this works in IE9 (if you're worried about that).
Give your form a name:
<div ng-controller="MyCtrl">
<form name="myForm">
<input name="myInput" />
</form>
</div>
So you can access your form validation status on your scope.
app.controller('MyCtrl', function($scope) {
$scope.myForm.$valid // form valid or not
$scope.myForm.myInput // input valid or not
// do something with myForm, e.g. display a message manually
})
angular doc
There is no way to trigger browser form behavior outside of a form. You have to do this manually.
Since my form fields only show validation messages if a field is invalid, and has been touched by the user:
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}

Categories

Resources