Making form with vanilla javascript - javascript

I want to make form with vanilla javascript. when id="text" value is nothing I meant space I want alert to pop, I'm makin' it with if statement but doesn't seem to work here's code
var input = document.getElementById('text');
function check(){
if(input.value == " "){
alert('hello');
}
}
Username: <input name="fname" type="text" onsubmit="check()" id="text" placeholder="Enter your username"> <br>
<button type="submit">asd</button>

You need to get the field value every time the user clicks - if your initial code is not after the element, your code would fail, because document.getElementById('text'); will be undefined
An input field does not have an onsubmit event
I recommend to have a value attribute too and trim it before testing
You likely mean this
document.getElementById("form1").addEventListener("submit", function(e) {
var input = document.getElementById('text');
if (input.value.trim() === "") {
alert('Please fill in user name');
input.focus();
e.preventDefault(); // stop form submission
}
});
<form action="yourserverprocess" id="form1">
Username: <input name="fname" type="text"
id="text" placeholder="Enter your username" value="" /><br />
<button type="submit">Send</button>
</form>
Without a form
document.getElementById("subbut").addEventListener("click", function(e) {
var input = document.getElementById('text'), val = input.value.trim();
if (val === "") {
alert('Please fill in user name');
input.focus();
}
else {
console.log("You typed",val);
}
});
Username: <input name="fname" type="text"
id="text" placeholder="Enter your username" value="" /><br />
<button id="subbut" type="button">Send</button>

Here's the solution of your problem.
I've made some changes in your code.
1. you have to put onsubmit event in form tag. Because doesn't support onsubmit event.
2. Change the function name from check() to checkAlert(). May be check is a library keyword which causes your code to fail.
var input = document.getElementById('text');
function checkAlert() {
if(input.value == ""){
alert('hello');
}
}
<form onsubmit = "checkAlert(this)">
Username: <input name="fname" type="text" id="text" placeholder="Enter your username"> <br>
<button type="submit">asd</button>
</form>

Related

Trying to add event listener so that when any form field is empty, it displays "Please enter a value"

Although it works when I remove addEventListener and add onblur="validateNonEmpty(this.form);" in each input element. Also it would be great if I can get to know difference between passing 'this' and 'this.form'. Any article explaining different scenarios to use 'this' keyword would be great!
<body>
<form action="">
Enter the banner message: <input type="text" name="message" id="message" value=""><span
class="helpText"></span><br>
Enter ZIP code of the location: <input type="text" name="ZIP" id="ZIP" value=""><span
class="helpText"></span><br>
Enter the date for the message to be shown: <input type="text" name="date" id="date" value=""><span
class="helpText"></span><br>
Enter your name: <input type="text" name="Name" id="Name" value=""><span class="helpText"></span><br>
Enter your phone number: <input type="text" name="phone" id="phone" value=""><span class="helpText"></span><br>
Enter your email address: <input type="text" name="address" id="address" value=""><span class="helpText"></span>
<br>
<input type="button" value="Order Banner">
</form>
</body>
<script>
let z = document.querySelectorAll('input');
for (let i = 0; i < z.length; i++) {
z[i].addEventListener('onblur', validateNonEmpty(this.form));
}
function validateNonEmpty(inputField) {
if (inputField.value.length == 0) {
document.querySelector('.helpText').innerHTML = "please enter a value";
return false;
} else {
document.querySelector('.helpText').innerHTML = "";
return true;
}
}
</script>
Well, the next time try to make a question more clear.
The difference between "this" and "this.form" is that the first is the input and the second is the form that the input belongs. I supposed you are a little confused about this. When you attach a function to an event, the this variable that is passed to the function refer to the element that trigger the event, in this case always is an input element, but the input elements also have a form property, you aren't getting the global forms variable, is the form of the input.
In Javascript.info you can get a better overview about what is happening.

How to Redirect only if form is not empty , JavaScript Validation

Right now even if input fields are empty , if submit button is pressed it shows alert"message": and then redirects to window.location="URL"
What I m looking for is it only shows done alert and redirects if input fields are filled
<form>
<input type="text" placeholder="enter name here">
<input type="number" placeholder="enter number here">
<input type="submit" id="submitbutton" value="submit">
</form>
</center>
</body>
<script type="text/javascript">
const submitit = document.getElementById('submitbutton');
submitit.addEventListener("click",function(){
alert("Done, Meanwhile check our website");
window.location="https://www.google.com";
});
</script>
Try this
<form>
<input id="name" type="text" placeholder="enter name here">
<input id="number" type="number" placeholder="enter number here">
<input type="submit" id="submitbutton" value="submit">
</form>
and JavaScript:
const submitit = document.getElementById('submitbutton');
submitit.addEventListener("click", function(e) {
// prevent form from being submitted
e.preventDefault();
alert("Done, Meanwhile check our website");
const name = document.getElementById('name');
const number = document.getElementById('number');
if (name.value !== '' && number.value !== '') {
window.location = "https://www.google.com";
}
});
Demo - https://jsfiddle.net/vyspiansky/v7yjwL6x/

Adding *Required next to an empty input

So I was wondering how I could implement required fields into my code. I tried just using required="" in the <input> tag, however, this doesn't work across all browsers. I was wondering if someone could explain how to add "* Required" next to the input if the user tries to submit and the field is empty.
Here's my form code:
contact.html
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
formvalidate.js
function validateForm()
{
var a=document.forms["Form"]["email"].value;
var b=document.forms["Form"]["subject"].value;
var c=document.forms["Form"]["message"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="")
{
alert("Please Fill All Required Field");
return false;
}
}
var input = document.getElementById('a');
if(input.value.length == 0)
input.value = "Anonymous";
First of all this is wrong:
if (a==null || a=="",b==null || b=="",c==null || c=="")
Presumably you lifted that from here and as noted in the comments, it doesn't do what it claims and will only check the last field.
To add the message you can modify your validation function to check each field and insert some text. The snippet below should give you a basic idea - and since you're new to javascript I've commented each bit with an explanation. Hope this helps:
function validateForm() {
// start fresh, remove all existing warnings
var warnings = document.getElementsByClassName('warning');
while (warnings[0]) {
warnings[0].parentNode.removeChild(warnings[0]);
}
// form is considered valid until we find something wrong
var has_empty_field = false;
// an array of required fields we want to check
var fields = ['email', 'subject', 'message'];
var c = fields.length;
// iterate over each field
for (var i = 0; i < c; i++) {
// check if field value is an empty string
if (document.forms["Form"][fields[i]].value == '') {
// create a div with a 'warning' message and insert it after the field
var inputField = document.forms["Form"][fields[i]];
var newNode = document.createElement('div');
newNode.style = "color:red; margin-bottom: 2px";
newNode.className = "warning";
newNode.innerHTML = fields[i] + ' is required!';
inputField.parentNode.insertBefore(newNode, inputField.nextSibling);
// form is now invalid
has_empty_field = true;
}
}
// do the alert since form is invalid - you might be able to skip this now
if (has_empty_field) {
alert("Please Fill All Required Field");
return false;
}
}
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
And of course you always need server side validation as well! Client side is really only to help get a snappy UIX and can be easily fail or becircumvented by any user who has a mind to do so. Any data you send to the server needs to be checked over and if something's wrong an error should be returned and handled properly on the form page.
The input field becomes a required field when you specify inside the field that it is a required field. Just placing an asterisk * or placing the word required next to it will not make it required.
Here is how to make an input field required in HTML5
Username *: <input type="text" name="usrname" required>
It is the attribute "required" of the element itself that makes it required.
Secondly.. when using the HTML5 validation you will not need javascript validation because the form will not pass the html5 validation. Having both client-side and server-side is important.

Passing value from one field to another

I want to pass the value 9112232453 of one textfield to another.
I know I need Javascript for this but I don't know how to do it.
HTML
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
Then later, I want to use the value in my php.
You could use a JS. function to take param (this.value) like:
<script>
var some_func = function (val){
var input = document.getElementById("phone");
input.value = val;
}
</script>
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func(this.value);' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
The best way is to not obtrude the HTML code with Javascript event handlers.
So, you can add a DOMContentLoaded event listener to the document, and as soon as DOM is loaded:
You add a change event listener to the input[type=checkbox], and then:
1.1. If the checkbox is checked, then you change the input#phone's value to its value
1.2. If not, then you empty the input#phone's value.
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('cbphone').addEventListener('change', function(e) {
var phone = document.getElementById('phone');
if (this.checked) {
phone.value = this.value;
// you can even enable/disable the input#phone field, if you want to, e.g:
// phone.disabled = false;
}
else {
phone.value = '';
// phone.disabled = true;
}
});
});
<form method="post" action="">
<input type="checkbox" name="cbphone" id="cbphone" value="9112232453">
<input type="text" name="phone" id="phone">
<input type="submit" name="Go" value="Go">
</form>
before submit form use validation and check whether the field value is filled up or not. if yes get value of the field.
if(document.getElementBy("fieldIdfirst").value!="")
{
document.getElementBy("fieldIdSecond").value=document.getElementElementById("fieldIdfirst");
}
Thanks it..
Try this: http://jsfiddle.net/yhuxy4e1/
HTML:
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' id="chk_phone">
<input type="text" name="phone" value="" id="txt_phone">
<input type="submit" name="Go">
</form>
JavaScript:
some_func = function() {
var checkBox = document.getElementById('chk_phone');
var textBox = document.getElementById('txt_phone');
textBox.value = checkBox.value;
}

Updating Value of Input to user's Input

I'm trying to update a page by echoing the input of a user in real time through ajax. However, when a user types in something and clicks 'send' there is nothing echoed. But when I preset the input to a random word through html and click 'send' the word is shown. Why is this and how can I update the input value without manually doing so in html?
HTML
<input type="text" id="userName" name="typeit" value=""/>
<!-- Input containing preset value -->
<input type="text" id="userName" name="typeit" value="cindy"/>
<input type="button" id="text_value" value="send"/>
JQuery
// I used this to check if the actual input was being updated
$('#text_value').click(function() {
var text_value = $("#userName").val();
if(text_value=='') {
alert("Please enter a title first");
}else{
alert(text_value);
}
});
I think what you want is a keyboard event like keyup:
$('#userName').keyup(function() {
var text_value = $(this).val();
if(text_value=='') {
alert("Please enter a title first");
}else{
$("p").html(text_value);
}
});
Also id can only be used once on the page so you need to change one of them:
<input type="text" id="userName" name="typeit" value=""/>
<!-- Input containing preset value -->
<input type="text" id="somethingElse" name="typeit" value="cindy"/>
<input type="button" id="text_value" value="send"/>
<!--for my example-->
<p>Update</p>
FIDDLE
You have a mistake in your HTML as you define id="userName" twice. If you compare strings you always need the === identical operator. Try out this snippet:
// I used this to check if the actual input was being updated
$('#text_value').click(function() {
var text_value = $("#userName").val();
if (text_value === '')
alert("Please enter a title first");
else
alert(text_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Uname" name="typeit" value="" />
<!-- Input containing preset value -->
<input type="text" id="userName" name="typeit" value="cindy" />
<input type="button" id="text_value" value="send" />
<div id="test"></div>

Categories