This is my html register page for entering the details:
<form id = "tform" onsubmit="return false;">
<h1>Register</h1>
<p><label>Name</label>
<br><input type="text" id="fname" name="fname">
</p>
<p><label>Username</label>
<br><input type="text" id="uname" name="uname">
</p>
<p><label>Create Password</label>
<br><input type="password" id="psw" name="psw">
</p>
<p><label>Confirm Password</label>
<br><input type="password" id = "pswc" name=psw>
</p><input type ="submit" value="Submit" onclick="validform()">
</form>
The validation code works but I would also like to implement json function so I can store the user data when I enter all the details correctly, it works separately but I don't know how to combine the two. Here is my code for json:
function StoreUser(){
var userObj = {};
userObj.name = document.getElementById("fname").value;
userObj.username = document.getElementById("uname").value;
userObj.password = document.getElementById("psw").value;
//Store user
localStorage[userObj.name] = JSON.stringify(userObj);
//Inform user of result
document.getElementById("tform").innerHTML = "<b> Register Done";
}
Related
I'm a javascript noobie. I'm creating a form for visitors to sign up to a webinar. I need to create a "unique code" or unique identifier for each visitor that submits the form.
For this I've created a hidden field called "Unique Code". This unique code is generated from a variable which concatenates a string, the email address value typed in the form and a webinar id that I assign from another variable. When I submit the form I just get the string and the webinar id concatenated by not the email address. The desired resulting value is something like this: GTW-visitor#emailaddress.com-12345. Here's my code:
<form action="/destination/" method="post" name="GTW_Test_Form">
<input type="hidden" name="gtwWebinarId" id="gtwWebinarId" value="">
<input type="hidden" name="uniqueCode" id="uniqueCode" value="">
<label for="email"><b>Email</b></label><br>
<input type="text" placeholder="Enter Email" name="emailAddress" id="emailAddress" required><br>
<label for="name"><b>First Name</b></label><br>
<input type="text" placeholder="Your First Name" name="firstName" id="firstName" required><br>
<label for="name"><b>Last Name</b></label><br>
<input type="text" placeholder="Your Last Name" name="lastName" id="lastName" required><br><br>
<input type="submit" value="Register to webinar">
</form>
And then, the javascript:
<SCRIPT LANGUAGE="JavaScript">
var emailAddressInput = document.getElementById("emailAddress").value;
var webinarId = "12345678";
var uniqueCode = "GTW-" + emailAddressInput + "-" + webinarId;
document.querySelector("#gtwWebinarId").value = webinarId;
document.querySelector("#uniqueCode").value = uniqueCode;
</script>
Thanks in advance,
Daniel
Your script runs even before the form fields have any value, you may have to write your script code inside a function which will be invoked by "onsubmit" event of the form.
<form onsubmit="foo(event)">
<script LANGUAGE="JavaScript">
const foo = (event)=>{
event.preventDefault();
var emailAddressInput = document.getElementById("emailAddress").value;
var webinarId = "12345678";
var uniqueCode = "GTW-" + emailAddressInput + "-" + webinarId;
document.querySelector("#gtwWebinarId").value = webinarId;
document.querySelector("#uniqueCode").value = uniqueCode;
}
</script>
Try to use var emailAddressInput = document.querySelector("#emailAddress").value;
That actually worked! Thank you, Sai!
i want to make a form with inputs and "submit" button. Idea is to disable button as long as inputs are empty or value of input not correctly (email validation).
I have my js code, but the problem is that, button starts at the beggining as disabled, but when i write something in first input it start to be not disabled, even if rest of inputs have not correct value.
My function:
document.getElementById("my-button").disabled = true
function inputValidator() {
var $element = $(this);
// for all input fields
if ($element.val()) {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
} else {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
}
// for email field
if ($element.attr('id') === 'email' && $element.val()) {
if (!reg.test($element.val())) {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
} else {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
}
}
Does anyone knows how to solve it?
Iterate over each element inside the form and check if one elements value length is zero. Note: Also the submit button needs a value in this implementation. A more native way would be to simply add the required tag to each input which also gives a good user experience.
JS approach
function validateForm() {
let inputs = document.forms["example"].elements;
let status = true;
[...inputs].forEach((input) => {
if(input.value.length == 0) status = false;
});
document.getElementById('submit').disabled = !status;
}
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" onKeyup="validateForm()">
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" onKeyup="validateForm()">
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" onKeyup="validateForm()">
</p>
<p>
<button disabled=true id="submit" value="submit">Submit</button>
</p>
</form>
Pure HTML Approach
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" required>
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" required>
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" required>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
HTML Part
<form name="loginForm" action="someUrl.do' />" method="POST" onsubmit="return submitForm()">
<fieldset>
<input type="text" name="organization" placeholder="Organization" maxlength="40">
<input type="text" name="username" placeholder="User Id" maxlength="24" value="">
<input type="submit" value="Submit">
</fieldset>
</form>
Script
function submitForm() {
return isValid(); // submit the form value when it's valid
}
They say, I can check the form element value through request.getParameter(FORM_ELEMENT_NAME) in servlet side but what I'd like to know is if there's any way to see the form value in JSP side, for example, inside of the submitForm function. Like we can in javascript by formElement.value.
Any help will be appreciated!
You can try this, i have just given as an example (used alert), u can do as per your requirement.
<form name="loginForm" action="someUrl.do' method="POST" onsubmit="return submitForm(this)">
<fieldset>
<input type="text" name="organization" placeholder="Organization" maxlength="40">
<input type="text" name="username" placeholder="User Id" maxlength="24" value="">
<input type="submit" value="Submit">
</fieldset>
</form>
JavaScript method:-
function submitForm(form){
var flds = form.elements;
for(i=0; i<flds.length;i++){
fld = flds[i];
alert(fld); // Field Object
alert(fld.value); // value of each field
}
return true;
}
In Jsp file, you can also get the value as following.
<%= request.getParamter("form_element_name") %>
To get the all values of the form...
request.getParameterMap();
For example,
<%# page import = "java.util.Map" %>
<%
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
String[] values = parameters.get(parameter);
//your code here
}
%>
Please take a look at this code, I want to know how to validate all these input elements in this single form using JavaScript.
I know they look the same but i have the names in a separate div. Your corrections and contributions to my form will be very much appreciated.
<form name="myForm">
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="password" name="fname"><br><br>
<input type="submit" value="Submit">
</form>
Yes, You can. Try this to Validate data in Java Script
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
Then You have to create a javaScript Function to Validate the data as above validateDate(), for this, now your code is
<script>
function validateData() {
var fname = document.getElementById("fname").value;
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
//if name is empty
if(fname == "" || username == "" || email == "" || password == "") {
//SOme Error Code here
alert("Please Fill All the Form Data.");
}
if(username.length < 4 || username.length > 20) {
//SOme Error Code here
alert("username must be less than 20 but more than 4 Characters.");
}
// You can add more filters like password length, and so on by using more if conditions
}
</script>
<body>
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
That's all. :)
Even though this requires jQuery, it can solve your problem:
To use jQuery Validate you just need to include in your code a version of the jQuery library equal or more recent than 1.7 and a file with the plugin.
See an example:
jQuery('form').validate();
After calling the jQuery.fn.validate method, you can validate your fields using data attributes, that are valid to the HTML5, according to the W3C.
See a example to required field:
<form>
<input type="text" data-required />
</form>
https://plugins.jquery.com/validate/
I am looking for a simple way to pre-fill a field in my contact form when ever a user clicks on a link that is given in some other page.
This is my contact form in html :
<form method="post" action="submit.php" >
<p>Your name:
<br /><input name="name" /></p>
<p>Your email:
<br /><input name="email" /></p>
<p>Your message:
<br /><textarea name="message" id="message" rows="10" cols="50"></textarea></p>
<p><input type="submit" value="Send" /></p>
</form>
I want to fill the "message" field with "some text" when a user clicks on a url like www.xyz.com/contact.html?setmessagefield=some_text
A more modern way would be to use the URL() constructor and the searchParams property. Let the browser engine do the work!
(new URL(window.location.href)).searchParams.forEach((x, y) =>
document.getElementById(y).value = x)
Try it online! or on Stack Overflow:
const hash = '?name=some_text&email=more%20text';
const example = "http://example.com/" + hash;
(new URL(example)).searchParams.forEach((x, y) =>
document.getElementById(y).value = x);
<p>Your name:
<br /><input name="name" id="name" /></p>
<p>Your email:
<br /><input name="email" id="email" /></p>
JavaScript has no built-in functions to parse url parameters like that (Since those GET parameters are usually used to send data to the server).
I'd suggest using a hash instead (A hash is purely client-side):
www.xyz.com/contact.html#name=some_text&email=more%20text
Now, add some id's to your fields:
<p>Your name:
<br /><input name="name" id="name" /></p>
<p>Your email:
<br /><input name="email" id="email" /></p>
Then set the values like this, on load:
var hashParams = window.location.hash.substr(1).split('&'); // substr(1) to remove the `#`
for(var i = 0; i < hashParams.length; i++){
var p = hashParams[i].split('=');
document.getElementById(p[0]).value = decodeURIComponent(p[1]);;
}
Working example
The big advantage of this is that it's flexible. If you want to set the values of 2 fields, you supply those 2 fields' id's in the hash:
www.xyz.com/contact.html#name=some_text&email=more%20text
4 fields? 4 id's:
www.xyz.com/contact.html#name=some_text&email=more%20text&username=john&age=23
No need to edit the code, then.
Don't bother with JavaScript if you're using PHP.
Just add a little something to the HTML:
<form method="post" action="submit.php" >
<p>Your name:<br />
<input name="name" value="<?php echo htmlspecialchars($_GET['name']) ?>" /></p>
<p>Your email:<br />
<input name="email" value="<?php echo htmlspecialchars($_GET['email']) ?>"/></p>
<p>Your message:<br />
<textarea name="message" id="message" rows="10" cols="50">
<?php echo htmlspecialchars($_GET['message']) ?>
</textarea></p>
<p><input type="submit" value="Send" /></p>
</form>
You can retrieve your current url with window.location.href and then get the default message via a regular expression :
var msg = window.location.href.match(/\?setmessagefield=(.*)/);
document.getElementById("message").value = msg[1];