Check for value of input on click of button - javascript

I am attempting to check if an input contains anything in it upon the press of a button. It only seems to be checking the value upon the first load of the website. It is not detecting any values typed into the input even if the button is pressed again and again. I have tested this by setting the input value to something at default, which gave me a success. I am stumped as to why this is happening.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>test</title>
</head>
<body>
<label>Goals:</label>
<input type="text" class="input-box" id="goals" />
<input
type="button"
name="submit"
value="Submit"
class="button"
id="submit"
/>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"
></script>
<script src="./app.js"></script>
</html>
JavaScript:
// Gather Inputs
let goals = document.getElementById("goals").value;
console.log("goals");
$("#submit").click(function() {
// Check Goals Input
if (goals === "") {
console.log("fail");
} else {
window.print();
}
});

You need to gather the inputs within the click() function.
$("#submit").click(function() {
// Gather Inputs
let goals = document.getElementById("goals").value;
console.log("goals");
// Check Goals Input
if (goals === "") {
console.log("fail");
} else {
window.print();
}
});

Related

Background color is changing and undoing again in jquery

When I am trying to change background colour of body (background color changer project)using jquery, it changes and again comes to default background-color.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Background-Color Changer</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form action="">
<h3>Change the Background-Color (Hex code only)</h3>
<input type="text" name="" id="name" maxlength="7" placeholder="#" />
<button id="btn1" type="submit">Change</button>
</form>
</div>
</body>
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/main.js"></script>
</html>
JS:
$(document).ready(function () {
$("#btn1").click(function () {
$('body').css("background-color", $("#name").val());
});
});
Your button is inside a form, so when you click it, the form is submitted, and the page is reloaded. To prevent the form from being submitted, you can do this:
$("#btn1").click(function (evt) { // <- the event
$('body').css("background-color", $("#name").val());
evt.preventDefault(); // prevent the default behavior for that event
});
More info on Event.preventDefault()

Cancelling onSubmit with JS Field Validation

I am trying to validate length of password and display a warning message but message is temporary.
I have tried using the onsubmit attribute with the submit button but it still doesn't work.
function validate()
{
var pw = document.getElementById("password").value
if(pw.length<8)
{
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" id="password"/>
<br/>
<span id="span" style="color:red;"></span>
<button onclick="validate()">Submit</button>
</form>
</body>
</html>
There were a few things fixed below:
Pass the event to your validate(), like this: onclick="validate(event)".
Cancel the regular event that happens with onsubmit by means of Event.preventDefault() and return false, but the former is much more important.
Notice what you see below when password is too short and when password is long enough:
function validate(ev)
{
var pw = document.getElementById("password").value
if(pw.length<8)
{
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>";
ev.preventDefault();
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" id="password"/>
<br/>
<span id="span" style="color:red;"></span>
<button onclick="validate(event)">Submit</button>
</form>
</body>
</html>
document.querySelector('form').addEventListener('submit', validate);
function validate(event) {
event.preventDefault();
const form = new FormData(event.target);
const password = form.get('password').trim();
if (password.length < 8) {
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
return;
}
event.target.submit();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<input name="password" type="text" id="password"/>
<br/>
<span id="span" style="color:red;"></span>
<button type="submit">Submit</button>
</form>
</body>
</html>
Your script should look something like this:
document.querySelector('form').addEventListener('submit', validate);
function validate(event) {
event.preventDefault();
const form = new FormData(event.target);
const password = form.get('password').trim();
if (password.length < 8) {
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
return;
}
event.target.submit();
}
I put the .trim() because it is usually a good idea to trim the inputs.
Consider this if you are using the inline attributes:
"You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient. " This is from the mdn documentation -> https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
var ssn = document.getElementById("ssn");
var current = document.getElementById("current");
ssn.oninput = function(event) {
current.textContent = ssn.value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<label for="ssn">password:</label>
<input type="password" id="ssn" inputmode="numeric" minlength="9" maxlength="12"
pattern="(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}"
required autocomplete="off">
<br>
<label for="ssn">Value:</label>
<span id="current"></span>
<span id="span" style="color:red;"></span>
<button onclick="validate()">Submit</button>
</form>
</body>
</html>
You could use the submit event on the form and return a status (boolean) on whether or not to let the request go through. (This is what is usually used for form validation.)
<form action="" onsubmit="return validate()">
function validate()
{
var pw = document.getElementById("password").value
if(pw.length<8)
{
document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>";
return false;
}
return true;
}
If the function returns true, it means the form is valid and the submission will go through.
If it returns false, it will show the error message and will not submit the form.

Prevent buttons from submitting forms

I am a beginner in JavaScript and HTML. I am trying to prevent buttons from submitting forms. It is not working with my below code. It is working when I remove the type:button and return false in the code but if I remove it is always submitting the form.
<!DOCTYPE html>
<html>
<head>
<title>Font Awesome Icons</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<button type="button" onclick="myFunction1();return false;" style="font-size:24px">Button <i class="fa fa-info-circle"></i></button>
<script type="text/javascript">
function myFunction1(){
}
</body>
</html>
JQUERY
You should be able to do:
$('#formid').submit(false);
or
$('#formid').submit(function(e){ e.preventDefault(); });
To use the jquery library visit the official website
http://jquery.com/download/
PURE JS
document.getElementById('formid').addEventListener('submit', function(e) {
e.preventDefault();
});
here is your example
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script>
function countRabbits() {
for(var i=1; i<=3; i++) {
alert("Rabbit number " + i);
}
return false;
}
</script>
</head>
<body>
<input type="button" onclick="countRabbits()" value="Count rabbits"/>
</body>
</html>
First of all, take care about closed pair tags. In your snippet you have unclosed script tag. Don't use button where it isn't necessary, but use the input type button instead.

jQuery button enable/disable based on input value?

this is test I created, how can I apply the button disable or enable to both inputs? As you can see the below code only works '.link_address'. I set keyup since once dom is loaded, we still need to check for weather inputs are empty or not. what am I doing wrong here? I tried foreach that checks all inputs under 'input_fields_wrap' , maybe I set it up wrong, but wasn't working either
$(document).ready(function() {
$('.confirm-btn').attr('disabled', true);
var valid_check = $('.link_address') || $('.link_name');
valid_check.keyup(function() {
if ($(this).val().length != 0) {
$('.confirm-btn').attr('disabled', false);
} else {
$('.confirm-btn').attr('disabled', true);
}
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="input_fields_wrap">
<input type="text" class="link_address">
<input type="text" class="link_name">
</div>
<button class="confirm-btn">Add More Fields</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="./js/test.js"></script>
</body>
</html>
Your current statement is var valid_check = $('.link_address') || $('.link_name');.
Remember, || is a Javascript construct, not some kind jQuery magic. It has no special combination abilities when used with jQuery, it only means what it has always meant: a logical OR comparison.
So what you're saying is "If $('.link_address') is a truthy value, set valid_check to that. If not, then set valid_check to $('.link_name')". However, jQuery objects are always truthy, so it will never touch $('.link_name') with that expression.
jQuery has it's own way of combining multiple selectors in to one object, which I have demonstrated below. (Also, you want to use prop instead of attr, trust me).
$(document).ready(function() {
$('.confirm-btn').attr('disabled', true);
var valid_check = $('.link_address,.link_name');
valid_check.keyup(function () {
if ($('.link_address').val().length != 0 && $('.link_name').val().length != 0) {
$('.confirm-btn').prop('disabled', false);
}
else {
$('.confirm-btn').prop('disabled', true);
}
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="input_fields_wrap">
<input type="text" class="link_address">
<input type="text" class="link_name">
</div>
<button class="confirm-btn">Add More Fields</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="./js/test.js"></script>
</body>
</html>
Here's what you can do:
Note: .input_fields_wrap :input is probably not the best selector here, you should make sure it only captures the inputs that are relevant.
// Upon page load
$(() => {
// When user releases a key on any relevant input field
$('.input_fields_wrap :input').on('keyup', () => {
// Disable confirm button if at least one of them has an empty value
$('.confirm-btn')
.prop('disabled', $('.input_fields_wrap :input')
.toArray()
.some(input => $(input).val().length === 0)
);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="input_fields_wrap">
<input type="text" class="link_address">
<input type="text" class="link_name">
</div>
<button class="confirm-btn" disabled>Add More Fields</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="./js/test.js"></script>
</body>
</html>
Currently you have var valid_check = $('.link_address') || $('.link_name');
which means your variable (valid_check) will contain a handle to one, or the other. Since the first one is always found, the OR part of it is not executed (by-passed).
The event listener is, thus, only applied to the first element (input) and never the second.
You may want to change your selector so that it applies to all the fields you want to take into account for validation. I used $("input") but you can be more specific if you want.
Something like:
$(document).ready(function() {
// start with the button disabled
$('.confirm-btn').attr('disabled', true);
$(".input_fields_wrap > input").on('keyup', function() {
// all the inputs into an array
var inputList = $(".input_fields_wrap > input");
// check to see if one has a value length of 0 (i.e. no input)
var isDisabled = inputList.toArray().some(f => $(f).val().length === 0);
// enable/disable button now
$('.confirm-btn').attr('disabled', isDisabled);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<input type="text" class="link_address">
<input type="text" class="link_name">
</div>
<button class="confirm-btn">Add More Fields</button>

Disable keyboard input excluding backspace

Using the javascript i am trying to disable users input after rich 80 charecters and if they press "Backspace" and remove some charecters then they can enter text again until rich again to 80. I have written code bellow but dont know why its not working. Any idea?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
</head>
<body>
<input type="text" class="form-control" id="editText" aria-describedby="basic-addon2" value="Something">
<span class="input-group-addon" id="basic-addon2">/80</span>
<script type='text/javascript'>
$('#editText').keyup(updateCount);
$('#editText').keydown(updateCount);
function updateCount() {
var limitText = "/80";
var lengthNumber = $(this).val().length;
if (lengthNumber>80) {
$("#editText").keydown(false);
}else{
$("#editText").keydown(true);
}
$('#basic-addon2').text(lengthNumber+limitText);
}
</script>
</body>
</html>
<input type="text" name="usrname" maxlength="80">
You can use maxlength tag.
You can directly use input property maxlength="80":
<input maxlength="80">
https://jsfiddle.net/ramseyfeng/wph565xu/
If you cant use maxlength property, and you MUST use javascript / JQuery, you could use bellow code
var limitText = 10;
$('#editText').keydown(function(e){
if ($(this).val().length > limitText)
{
if (e.keyCode != 8)
{
e.preventDefault();
return false;
}
}
});
Demo : https://jsfiddle.net/5dctLbxq/

Categories

Resources