How to compare two inputs and show a div - javascript

I need to make a simple js. Nothing fancy - just show or hide an element only if the inputs have the same value. All before send the form.
<form>
<input type="number" name="some1" id="some1">
<input type="number" name="some2" id="some2">
<div id="showhide">The inputs are the same</div>
<input type="submit">
</form>
The result can be something like this.
if(#some1(value)==#some2(value)) {
#showhide.show()
} else {
#showhide.hide()
}

Your jquery should be like this:
if($('#some1').val() == $('#some2').val()) {
$('#showhide').show();
} else {
$('#showhide').hide();
}

Something like this?
$("#some1, #some2").on("keyup change", function(){
let firstEl = $("#some1"),
secondEl = $("#some2"),
conditionalEl = $("#showhide");
if (firstEl.val() == secondEl.val() ) {
conditionalEl.show();
} else {
conditionalEl.hide();
}
});
#showhide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" name="some1" id="some1">
<input type="number" name="some2" id="some2">
<div id="showhide">The inputs are the same</div>
<input type="submit">
</form>

Related

How to disable submit button for multiple inputs (jQuery Homework) [duplicate]

This question already has answers here:
Disabling submit button until all fields have values
(11 answers)
Closed 1 year ago.
I'm trying to setup a jQuery function to keep a submit button disabled until all the fields are filled. I got to a point when I can get it to work with 1 field filled. I've tried to change my call statement various ways I can think of, but I've locked myself to only one field... so I'm obviously missing something... I'm still very new to javascript so I'd appreciate some simple basic help. Thanks
My jQuery:
$(document).ready(function () {
$("#valueInput").on("input", function () { // << only for one field
if ($(this).val() != "") {
$("#addCarToGarage").prop("disabled", false);
} else {
$("#addCarToGarage").prop("disabled", true);
}
});
});
My HTML:
<input type="number" placeholder="Year" id="yearInput" required/>
<input type="text" placeholder="Make" id="makeInput" required/>
<input type="text" placeholder="Model" id="modelInput" required/>
<input type="number" placeholder="Est Value" id="valueInput" required/>
<input type="submit" id="addCarToGarage" value="Add to Garage" disabled="disabled">
You can try following code.
Instead of using id of last input, following approach can be better
$(document).ready(function () {
$('form > input').keyup(function() {
var empty_inputs = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty_inputs = true;
}
});
if (empty_inputs) {
$('#addCarToGarage').attr('disabled', 'disabled');
} else {
$('#addCarToGarage').removeAttr('disabled');
}
});
});
Try something like that
$(document).ready(function () {
let areAllValid = false;
const fields$ = jQuery('input[type="text"], input[type="number"]');
function checkValues() {
areAllValid = true;
for(const field of fields$) {
if(!$(field).val()) {
areAllValid = false
}
}
}
$("input").on("input", function () {
checkValues()
$("#addCarToGarage").prop("disabled", !areAllValid);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" placeholder="Year" id="yearInput" required/>
<input type="text" placeholder="Make" id="makeInput" required/>
<input type="text" placeholder="Model" id="modelInput" required/>
<input type="number" placeholder="Est Value" id="valueInput" required/>
<input type="submit" id="addCarToGarage" value="Add to Garage" disabled="disabled">

Disable submit button until all form inputs have data

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">

Issue on Checking Multi Inputs Calculation Using each()

Can you please take a look at this Demo and let me know why I am not able to do the calculation check using the each iterator?
As you can see I tried to use :
if (!parseInt($(this).val()) === ((parseInt($(this).closest('div').find('.upper').text())) - parseInt($(this).closest('div').find('.lower').text()))) {}
Which it didnt work then I used this :
if (!parseInt($(this).val()) === ((parseInt($(this).prev('.upper').text())) - parseInt($(this).prev('.lower').text()))) {
but still not validating the input?
I'm not sure if that what you want to achieve, take a look at following example :
$('#test').on('click', function (e) {
$("input").each(function () {
if ($(this).val().length === 0)
{
$(this).addClass('input-error');
} else {
var upper = parseInt($(this).prev().prev().text());
var lower = parseInt($(this).prev().text());
var current_value = parseInt($(this).val());
if (current_value != (upper-lower)){
$(this).addClass('input-error');
}else{
$(this).removeClass('input-error');
}
}
});
});
.input-error {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">5</div>
<div class="lower">2</div>
<input type="text" id="txt1">
<hr />
<div class="upper">7</div>
<div class="lower">3</div>
<input type="text" id="txt2">
<hr />
<div class="upper">200</div>
<div class="lower">66</div>
<input type="text" id="txt3">
<hr />
<br />
<button type='button' id="test">Test</button>

Check a DIV for input item values are not empty in jQuery

I've stacked some input text fields, drop downs, radio gruop inside a DIV. Now how do I check if all text fields, radio groups and dropdowns inside this DIV have some value?
I've created a simple mockup in JSFiddle
jQ:
$("#continue_btn").click(function(){
if($('#myForm input:text[value=""]').length > 0){
alert("yes");
} else {
alert("no")
}
}
All you have to do is to wrap your markup in a form element and to each input add attr required
this is pure css.
DEMO ON JSFIDDLE
function highlight(event)
{
event.preventDefault();
alert('Done!!!');
return false;
}
var highlightForm = document.querySelector("form#myForm");
highlightForm.addEventListener('submit',highlight , false);
/**
$("#continue_btn").click(function(){
if($('#myForm input:text[value=""]').length > 0){
alert("yes");
} else {
alert("no")
}
}
*/
<form id="myForm">
<div class="myF">
<div class="input-group">
<span class="input-group-addon"><input type="radio" name="radioGroup" id="radio1" value="option1" required></span>
<input class="form-control" value="Fruits" autofocus required />
</div>
<div class="input-group">
<span class="input-group-addon"><input type="radio" name="radioGroup" id="radio2" value="option2" required></span>
<input class="form-control" value="Vegitables" required/>
</div>
</div>
<div class="input-group">
<span class="input-group-addon quotationFields">City</span><input type="text" class="form-control numericOnly" id="weight_oq" name="weight_oq" required/>
</div>
<div class="input-group onlineQuoteForm">
<span class="input-group-addon">Type </span>
<select class="form-control" id="ptype_oq" required>
<option value="">Please selelct</option>
<option value="Satisfatory">Documents</option>
<option value="val1">OPtion 1</option>
<option value="val2">OPtion 2</option>
</select>
</div>
<input type="submit" value="Continue" id="continue_btn" class="btn btn-primary"/>
</form>
Now you can style it using this
input:required:focus {
}
input:required:hover {
}
/**--------VALID----------*/
input[type="text"]:valid,
input[type="name"]:valid,
input[type="password"]:valid,
input[type="email"]:valid {
}
input[type="text"]:valid:focus,
input[type="name"]:valid:focus,
input[type="password"]:valid:focus,
input[type="email"]:valid:focus {
}
input[type="text"]:valid:hover,
input[type="name"]:valid:hover,
input[type="password"]:valid:hover,
input[type="email"]:valid:hover {
}
/**---------INVALID---------*/
input[type="text"]:invalid,
input[type="name"]:invalid,
input[type="password"]:invalid,
input[type="email"]:invalid {
}
input[type="text"]:invalid:focus,
input[type="name"]:invalid:focus,
input[type="password"]:invalid:focus,
input[type="email"]:invalid:focus {
}
input[type="text"]:invalid:hover,
input[type="name"]:invalid:hover,
input[type="password"]:invalid:hover,
input[type="email"]:invalid:hover {
}
/**---------REQUIRED---------*/
input[type="text"]:required,
input[type="name"]:required,
input[type="password"]:required,
input[type="email"]:required {
}
/**---------OPTIONAL---------*/
input[type="text"]:optional,
input[type="name"]:optional,
input[type="password"]:optional,
input[type="email"]:optional {
}
input[type="text"]:optional:focus,
input[type="name"]:optional:focus,
input[type="password"]:optional:focus,
input[type="email"]:optional:focus {
}
input[type="text"]:optional:hover,
input[type="name"]:optional:hover,
input[type="password"]:optional:hover,
input[type="email"]:optional:hover {
}
The main difficulty here is radio buttons which you need to check separately. Try something like this:
var $form = $('#myForm');
$("#continue_btn").click(function () {
var $radio = $form.find(':radio:checked');
var hasEmpty = $.grep($form.serializeArray(), function(el) {
return !$.trim(el.value);
}).length || $radio.length == 0;
if (hasEmpty) {
alert("yes");
} else {
alert("no")
}
});
Demo: http://jsfiddle.net/tq3jL2d6/9/
Note, that for this demo I improved HTML a little:
wrapped everything with form tag, since you deal with form
added name attributes to all form elements
added placeholder attributes.
You can use this code, here is the link
http://jqueryvalidation.org/files/demo/
And here is the code
view-source:http://jqueryvalidation.org/files/demo/
You can use filter function which can filter every value in form like this
$("#continue_btn").click(function(){
var anyFieldIsEmpty = $("#myForm input,select").filter(function() {
return $.trim(this.value).length === 0;
}).length > 0;
if(anyFieldIsEmpty){
alert("yes");
} else {
alert("no")
}
});
you can select multiple form elements like i have done input,select,textarea etc..
FIDDLE DEMO

How do I enable a button when fields are filled in?

I'm trying to hide part of the form with the button disabled and have the user click on the button to show rest of form when previous fields are filled in. Can anyone help? Here's my code as an example:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1"/><br/>
<label>Field 2:</label>
<input type="text" class="field2"/><br/>
<label>Field 3:</label>
<input type="text" class="field3"/><br/>
</div>
<div align="center">
<button id="show_form" onClick = "this.style.display= 'none'" disabled="disabled">
Enter Billing Info</button>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
JQUERY
<script>
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
$("#show_form").prop("disabled", true);
$("#group2").hide();
$("#show_form").show();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
</script>
Try this jQuery:
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
/* This will hide the bottom form and disable the button again if
* any of the field above will be emptied.
* NOTE: This will just hide the form; it will not clear the fields.
*/
$("#show_form").prop("disabled", true);
$("#group2").hide();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
This will enable the button when all the fields in the initial form are filled. Then the user will be able to click on the button to see the rest of the form.
You just need to loop through each input and check if a value is set when the button is clicked like this:
$('#show_form').click(function () {
var fields = $('.js-field');
var pass = true;
for (var i = 0; i < fields.length; i++) {
if (!$(fields[i]).val()) {
pass = false;
}
}
if (pass === true) {
$('#group2').show();
}
});
I also needed to add some classes to your html:
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1 js-field"/><br/>
<label>Field 2:</label>
<input type="text" class="field2 js-field"/><br/>
<label>Field 3:</label>
<input type="text" class="field3 js-field"/><br/>
</div>
<button type="button" id="show_form" value="Show_Form">Enter Billing
Info</button>
<div id="group2" style="display: none;">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
To see it in action visit this fiddle.
You can add some logic to the click event and check all the input fields to have a value like this
$("#show_form").click(function(){
var allFilled = true;
$('#group1').find('input').each(function(){
//if someone is empty allFilled will keep false
if(this.value === ''){
allFilled = false;
//this breaks the each
return false;
}
});
if(allFilled){
$("#group2").show();
}
});
Keep in mind the previous code only work with input fields.

Categories