Form validation button without submitting the form - javascript

I have a form, and I want to check validation ( if the inputs are correct) without submitting that form. How is that possible?
The validations in this example is as follows:
If the user enters and for first name and jkp for last name and clicks on the validate button, the document.write function will print success without submitting the form.
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp")
{document.write("Correct answer");}
else{document.write("Incorrect answer");}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="#">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
</select>
<input type="submit" value="Submit">
<input style="background:red" type="submit" value="Validate">
</form>

make validate but not a submit type
Changes i have made:
in js
$( "#vali" ).click(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
$('#fname, #lname').css({
'color' : 'red'
});
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
in html
<input id="vali" style="background:red" type="button" value="Validate">
DEMO:
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
$( "#vali" ).click(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
$('#fname, #lname').css({
'color' : 'red'
});
if(name === "and" && lname ==="jkp")
{alert("Your answers are correct!");}
else{alert("Your answer is not correct");}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
#vali{
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="#">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<input type="submit" value="Submit">
<input id="vali" style="background:red" type="button" value="Validate">
</form>

You can also try AJAX requests supposing you will do the validation on the server side, also hiding the business logic from the client.
Another solution is to create a javascript method for validation that is called after focus lost/key up which takes the elements by their id and passes them to this function.

You can simply add event.preventDefault() to the submit event if the validation fails:
$( "#myform" ).submit(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp") {
alert("Success");
}
else {
event.preventDefault();
alert("failed");
}
});
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="#">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
</select>
<input type="submit" value="Submit">
<input style="background:red" type="submit" value="Validate">
</form>

Not checked but you can use onchange(),
The change event occurs when the value of an element has been changed (only works on input, textarea and select elements).
The change() method triggers the change event or attaches a function to run when a change event occurs.
$( "#myform" ).change(function( event ) {
var name = $("#fname").val();
var lname = $("#lname").val();
if(name === "and" && lname ==="jkp"){
alert("Your answers are correct!");
}
else{
alert("Your answer is not correct");
}
}

Related

Javascript - I can not see the result of the sum of values

I have a design problem in the script that gives me the values ​​of the right column (ignoring the values ​​on the left), and the result of the sume I can not see in the green box when I click on "View Result"
// Old script
/*window.sumInputs = function() {
var inputs = document.getElementsByTagName('input'),
result = document.getElementById('total'),
sumar = 0;
for(var i=0; i<inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sumar += parseInt(ip.value) || 0;
}
}
result.value = sumar;
}*/
// ========================
// New script
$(document).ready(function() {
var valores = $('#derecha').children();
var suma = 0;
$.each(valores, function() {
valor = $(this).val() || 0;
suma += parseInt(valor);
});
//console.log(suma);
valores = document.getElementById('total');
});
body p {
margin: 0 20px
}
/*#izquierda {display:none}*/
#izquierda,
#derecha {
display: inline-block;
vertical-align: top;
width: 140px;
margin: 20px 20px 20px 20px;
padding: 10px;
border: 1px solid #000
}
#izquierda span,
#derecha span,
body span {
font-weight: bold
}
#izquierda p,
#derecha p {
margin: 5px auto 15px;
text-align: center
}
input {
width: 80px;
display: block;
margin: 5px auto;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 120px;
padding-left: 40px
}
#cont-resultado input {
display: inline-block;
margin: 0 auto 10px;
background: red;
color: #fff;
border: none;
padding: 10px 0
}
#cont-resultado a {
display: inline-block;
text-decoration: none;
color: #fff;
background: green;
padding: 10px 12px
}
#total {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="izquierda">
<p><span>DIV LEFT</span><br>display="none"</p>
<input name="qty1" value="240">
<input name="qty2" value="862">
<input name="qty3" value="911">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="derecha">
<p><span>DIV RIGHT</span><br>display="block"</p>
<input name="qty1" value="2">
<input name="qty2" value="2">
<input name="qty3" value="2">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="cont-resultado">
<input name="total" id="total">
See total
</div>
<br>
<p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
What am I doing wrong...?
Thanks in advance!
$(document).ready(function(){
var valores = $('#derecha').children();
var suma = 0;
$.each(valores,function(){
valor = $(this).val() || 0;
suma += parseInt( valor );
});
//console.log(suma);
valores = document.getElementById('total');
});
You're not doing anything with suma, further, use a selector for the children .children('input').
$(document).ready(function() {
function sumInputs(e) {
e.preventDefault();
var valores = $('#derecha').children('input');
var suma = 0;
$.each(valores, function() {
valor = $(this).val();
suma += Number(valor);
});
valores = document.getElementById('total');
$(valores).val(suma);
}
$('#sumup').on('click', sumInputs);
});
body p { margin: 0 20px}/*#izquierda {display:none}*/#izquierda,#derecha { display: inline-block; vertical-align: top; width: 140px; margin: 20px 20px 20px 20px; padding: 10px; border: 1px solid #000}#izquierda span,#derecha span,body span { font-weight: bold}#izquierda p,#derecha p { margin: 5px auto 15px; text-align: center}input { width: 80px; display: block; margin: 5px auto; padding: 2px 0; background: #f2f2f2; border: none; border: 1px solid #000; text-align: center}#cont-resultado { text-align: center; width: 120px; padding-left: 40px}#cont-resultado input { display: inline-block; margin: 0 auto 10px; background: red; color: #fff; border: none; padding: 10px 0}#cont-resultado a { display: inline-block; text-decoration: none; color: #fff; background: green; padding: 10px 12px}#total { display: block}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="izquierda"> <p><span>DIV LEFT</span><br>display="none"</p> <input name="qty1" value="240"> <input name="qty2" value="862"> <input name="qty3" value="911"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="derecha"> <p><span>DIV RIGHT</span><br>display="block"</p> <input name="qty1" value="2"> <input name="qty2" value="2"> <input name="qty3" value="2"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="cont-resultado"> <input name="total" id="total"> <a id='sumup' href="#">See total</a></div><br><p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
You need to set the value of valores (the new one) to suma:
valores.val(suma);

Transfer input from prompt() into a text field

I have a HTML page in which when the start button is being pressed, a prompt box will appear to prompt the user to enter his/her name. When user enters his/her name and confirms the input, it would appear on the black box (as shown in the code) with white text color. I am not sure of how to "transfer" the value from prompt() to text field. I know the value of the input fields are empty by default.
function myFunction() {
var person = prompt("Please enter your name");
if (person != null) {
person = document.getElementById(input).value;
}
}
#input{
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #191818;
color: white;
}
#input1 {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #7C7878;
color: white;
}
.btnEdit{
width: 30px;
margin: 5px;
display: block;
font-weight:bold;
text-align:center;
font-size:10px;
line-height:15px;
}
<h2>Part 3</h2>
<button onclick="return myFunction()" id="strt" value="Start">Start</button>
<button onclick="return reset()" id="clr" value="Clear">Clear</button> <br />
<br>
<input type="text" id="input" style="text-align:center;" name="input"/>
<button id="swap" value="Swap" class="btnEdit">--></button>
<button id="swap1" value="Swap1" class="btnEdit"><--</button>
<input type="text" id="input1" value="" style="text-align:center;" name="input1"/>
Expected output would be for the user to enter his/her name in the prompt and upon confirmation, his/her name will appear in the text field in black with white text colors.
You just need to swap it.
person = document.getElementById(input).value;
The above is wrong. It should be:
document.getElementById("input").value = person;
And you need to update the "input" too. It's not a constant.
function myFunction() {
var person = prompt("Please enter your name");
if (person != null) {
document.getElementById("input").value = person;
}
}
#input {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #191818;
color: white;
}
#input1 {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #7C7878;
color: white;
}
.btnEdit {
width: 30px;
margin: 5px;
display: block;
font-weight: bold;
text-align: center;
font-size: 10px;
line-height: 15px;
}
<h2>Part 3</h2>
<button onclick="return myFunction()" id="strt" value="Start">Start</button>
<button onclick="return reset()" id="clr" value="Clear">Clear</button> <br />
<br>
<input type="text" id="input" style="text-align:center;" name="input" />
<button id="swap" value="Swap" class="btnEdit">--></button>
<button id="swap1" value="Swap1" class="btnEdit"><--</button>
<input type="text" id="input1" value="" style="text-align:center;" name="input1" />
function myFunction() {
var person = prompt("Please enter your name");
if (person != null) {
document.getElementById('input').value = person;
}
}
#input{
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #191818;
color: white;
}
#input1 {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #7C7878;
color: white;
}
.btnEdit{
width: 30px;
margin: 5px;
display: block;
font-weight:bold;
text-align:center;
font-size:10px;
line-height:15px;
}
<h2>Part 3</h2>
<button onclick="return myFunction()" id="strt" value="Start">Start</button>
<button onclick="return reset()" id="clr" value="Clear">Clear</button> <br />
<br>
<input type="text" id="input" style="text-align:center;" name="input"/>
<button id="swap" value="Swap" class="btnEdit">--></button>
<button id="swap1" value="Swap1" class="btnEdit"><--</button>
<input type="text" id="input1" value="" style="text-align:center;" name="input1"/>

validate form with javascript with a validation expression

So I have a form and I am trying to validate it to make sure no other characters are submitted I know theirs a validation expression but I do not know how to apply it.I just want it where if the user puts any invalid character that may interfere then it just return false. I tried but it does not seem to work, also please help me make my code more efficient if there is any way thank you
function validateForm() {
var name = document.forms["theForm"]["fname"].value;
var lastName = document.forms["theForm"]["lname"].value;
var email = document.forms["theForm"]["femail"].value;
var subject = document.forms["theForm"]["subject"].value;
if (name == "") {
window.alert("Missing First Name.");
name.focus();
return false;
}
if (lastName == "") {
alert("Missing Last Name");
return false;
}
if (email == "") {
alert("Missing Email");
return false;
}
if (subject == "") {
alert("Incomplete Action");
return false;
}
}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: #993b3b;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #B0B0B0;
}
.formCont {
text-align: left;
margin: 152.5px 0;
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
<div class="formCont">
<form name="theForm" onsubmit="return validateForm()" method="post">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<label for="femail">Email</label>
<input type="text" id="femail" name="Email" placeholder="Your email.."
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
Ok, so since this is a college project. I'm assuming you have to write vanilla JS (if not jQuery is a super better alternative).
A couple of things to start off:
name === ""
Is better than name == "" Because of JavaScript's type coercion.
Also, HTML now has an email input type. So
<input type="email" id="femail" name="Email" placeholder="Your email..">
Why do you have window.alert in one place and alert in other places. Oh goodness. This is becoming a code review :).
Anyway, like I said before, if jQuery is a choice, please, please do.
#peterb mentioned correctly here is an example of using jquery
function validateForm() {
var name = $("#fname").val();
var lastName = $("#lname").val();
var email = $("#femail").val();
var subject =$("#subject").val();
if (name == "" || name ==null || name==undefined) {
alert("Missing First Name.");
markerror("#fname")
return false;
}
if (lastName == "" || lastName ==null || lastName==undefined) {
alert("Missing Last Name");
markerror("#lname")
return false;
}
if (email == "" || email ==null || email==undefined) {
alert("Missing Email");
markerror("#femail")
return false;
}
if (subject == "" || subject ==null || subject==undefined) {
alert("Incomplete Action");
markerror("#subject")
return false;
}
}
function markerror(index){
$(index).css("border", "1px solid red");
$(index).focus();
setTimeout(function () {
$(index).css("border", "1px solid #ccc");
}, 4000);
}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: #993b3b;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #B0B0B0;
}
.formCont {
text-align: left;
margin: 152.5px 0;
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="theForm" onsubmit="return validateForm()" method="post">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<label for="femail">Email</label>
<input type="text" id="femail" name="Email" placeholder="Your email.."
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" value="Submit">
</form>

How to validate a multiple step form and message display for each and every fields

How to validate a multiple step form and message display for each and every fields example:please enter your email and I also want all the error message to
be display at the same time :suppose I click on next button I should display all How to validate a multiple step form and message display for each and every feilds How to validate a multiple step form and message display for each and every fields
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
You can use Jquery.validate.min.js file which contains validate method.
Refer the following code below:
function valid(){
$("#rform").validate({
rules:{
uname:"required", // uname, email are input names
umail:{
required:true,
email:true
},
upass:{
required:true,
minlength:8
}
},
messages:{
uname:"Please enter full name",
umail:{
required:"Please enter email id",
email:"Please enter valid email id"
},
upass:
{
required:"please provide password",
minlength:"min length of password is 8"
}
},
submitHandler :function(form){
// alert("it works!");
console.log("it works!");
// form.submit();
funreg(); //function to be called after submit button is pressed and al inputl fields are valids
}
});
}

Disable input button when field.value is empty

I've seen this answered in jquery, but I'd like to know how I can do it in javascript. So far I came up with the following, but I understand it is not capturing the nameF.value properly.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
if (nameF.value == "") {
formButton.classList.add("notclickable");
}
}
go();
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
opacity: 1;
}
#form-button.notclickable {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button">
https://stackoverflow.com/questions/ask#
How can I do it without jQuery, just using vanilla?
Thank you!
All you need is an event handler assigned to nameF, and to .toggle() the class instead of add().
The .toggle() receives an optional second argument where you tell it if it should add or remove the class, so you'll pass the string comparison there.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
formButton.classList.toggle("notclickable", nameF.value == "");
}
go();
nameF.addEventListener("input", go);
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
opacity: 1;
}
#form-button.notclickable {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#
Also, be aware that you don't need a class to disable the button. You can use the disabled property with the :disabled selector. This disables its functionality too instead of just fading it.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
formButton.disabled = nameF.value == "";
}
go();
nameF.addEventListener("input", go);
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
}
#form-button:disabled {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#
Try something like that!
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function onChangeContent(e) {
formButton.disabled = e.target.value !== '' ? false : true;
}
nameF.addEventListener('keyup', onChangeContent);
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button" disabled>

Categories