Enable button when two inputs are the same - javascript

I have two passwords input, i want my validate button to be clickable when the two inputs are the same.
reset.pug
block content
div#content.center-align
p
span#main.bold=trad.mainTitle
br
input#pass(type='password',placeholder='' + trad.textplaceholder)
input#pass(type='password',placeholder='' + trad.validpass)
button#validate(value=token) #{trad.button}
this is my ajax function
$('#validate').bind( 'click', function(e) {
let token = e.target.value
// let pass1 = $('#pass1').val()
let pass = $('#pass').val()
if (pass !== '') {
$.post('/reset-password', {'pass': pass, 'token': token}, function (res) {
console.log(res)
if (res.err) {
$('#hiddenErr').removeClass('hide')
} else {
$('#hiddenSuccess').removeClass('hide')
setTimeout(function () {
window.location = '/'
}, 10000)
}
})
} else {
console.log('wrong password')
}
})

It's not strictly speaking an error, but you're using the same id on two html elements on the same page which can lead to strange behavior. It's better to use a class when you have two elements that are similar, or use two separate id's.
With classes do this:
block content
div#content.center-align
span#main.bold=trad.mainTitle
br
input.pass(type='password',placeholder='' + trad.textplaceholder)
input.pass(type='password',placeholder='' + trad.validpass)
button#validate(value=token) #{trad.button}
script.
function isMatchingPassword(){
var passwords = [];
$('.pass').each(function(index, element){
passwords.push( $(element).val() );
});
if( passwords[0] === passwords[1] ){
return true;
} else {
return false;
}
}
With id's do this:
block content
div#content.center-align
span#main.bold=trad.mainTitle
br
input#pass1(type='password',placeholder='' + trad.textplaceholder)
input#pass2(type='password',placeholder='' + trad.validpass)
button#validate(value=token) #{trad.button}
script.
function isMatchingPassword(){
if( $('#pass1').val() === $('#pass2').val() ){
return true;
} else {
return false;
}
}
The id solution is easier of course, but it doesn't scale very well past two or three elements.

You can subsribe to the 'input' event for the two input boxes, like this:
$('#pass, #pass1').on('input', function()
{
$('#validate').prop('disabled') = $('#pass').val() != $('#pass1').val();
});
Now , when user types in either of the boxes, the '#validate' button will be disabled, if the two values differ.

Related

How come multiple classes not targeting in textarea?

I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.
$(document).ready(function() {
$('#field-warning-message').hide();
$('#dob-warning-message').hide();
var empty_field_error = false;
var dob_error = false;
// $('input[type=text], textarea')
$('.log, .log2').focusout(function () {
validate_empty_field();
});
function validate_empty_field() {
var field = $('.log, .log2, textarea').val();
// var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (field.length == '') {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else if (field.length < 1) {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else {
$('#field-warning-message').hide();
}
}
$('.verify-form').submit(function () {
empty_field_error = false;
dob_error = false;
validate_empty_field();
if ((empty_field_error == false) && (dob_error == false)) {
return true;
} else {
return false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="log"></textarea>
<textarea class="log2"></textarea>
<div id="field-warning-message"></div>
You should pass the event to the handler so you have access to the target
Change your event listener line to this:
$('.log1, .log2').focusout(validate_empty_field);
and then accept an argument in validate_empty_field
function validate_empty_field(ev){
var field = $(ev.target).val();
if(!field.length){
//textarea is empty!
}else{
//textarea is not empty!
}
}
in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:
$('.log1, .log2').on('focusout', function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
});
And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.
EDIT: Final option should cover all requirements.
$('.log').on('focusout', function(){
$('.log').each(function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
}
});

Performing functions if method is available in an array for jQuery

I'm trying to find a better way to write a piece of jQuery but I couldn't figure it out on my own.
$('.ajaxButton').click(function(event) {
event.preventDefault();
var button = $(this).data('button');
var action = $(this).data('buttonaction');
var target = $(this).data('buttontarget');
// The following code needs a rewrite
if (action === 'fadeIn') {
$(target).fadeIn();
} else if (action === 'slideDown') {
$(target).slideDown();
} else if (action === 'fadeToggle') {
$(target).fadeToggle();
} else if (action === 'slideToggle') {
$(target).slideToggle();
} else {
console.log('Action not found for ' + button + ' button.');
}
});
In order to avoid having to write the same code over and over again, I wrote the above JS for buttons I create in my web application. The above code works with the following anchor:
<a href="#"
class="button ajaxButton"
data-button="showForm"
data-buttonaction="slideToggle"
data-buttontarget=".showForm" >...</a>
What I have been trying to figure out is if there is a better way to write the following piece of code:
if (action === 'fadeIn') {
$(target).fadeIn();
} else if (action === 'slideDown') {
$(target).slideDown();
} else if (action === 'fadeToggle') {
$(target).fadeToggle();
} else if (action === 'slideToggle') {
$(target).slideToggle();
} else {
console.log('Action not found for ' + button + ' button.');
}
I would like to avoid the use of if: else statements. My first instinct was to have some sort of array that contains all possible actions. From there, I conduct a simple if action is in array do....
var actionArray = new Array('fadeIn', 'slideDown'...);
if ($.inArray(action, actionArray)) {
$(target).action();
}
But I have no idea how to create the function. Can I call functions based on array values? Or can I convert strings to functions? I think the closest I could find was to use the eval() function.
Is there a better way to do this? Or will I have to use if else statements?
You can target a property within an object using bracket notation (obj['prop']) instead of dot notation (obj.prop). So you can do something like this:
const validActions = ['fadeIn', 'slideDown'];
function doSomethingWithTarget(target, something) {
if (validActions.includes(something)) {
target[something]();
}
}
doSomethingWithTarget($('#element'), 'slideDown'); // $('#element').slideDown();
More info:
Working with objects #MDN, Property accessors #MDN
Here's my attempt :
$('.ajaxButton').click(event => {
event.preventDefault();
let $this = $(this),
button = $this.data('button'),
action = $this.data('buttonaction'),
$target = $($this.data('buttontarget'));
try {
$target[action]();
} catch (error) {
console.log('Action not found for ' + button + ' button.');
}
});
target.fadeIn can also be written target["fadeIn"]. If it is a function, you can then call it the same way : target.fadeIn() or target["fadeIn"](). Then the argument can be dynamic (variable) : target[action]()
What you can do is check of the function excist for the target, and if so execute it.
$('.ajaxButton').click(function(event) {
event.preventDefault();
var button = $(this).data('button');
var action = $(this).data('buttonaction');
var target = $(this).data('buttontarget');
//check if the function excist for target object
if (typeof $(target)[action] === 'function') {
//if so execute it.
$(target)[action]();
} else {
console.log('function: ' + action + ' not found for target: ' + target);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
testbutton
<div class="showForm">test toggle div</div>

IF condition need to check evrytime

I am using the below code to render the same as many as times,
I have two sections, one section with show-all class and another with no class.
When 'show-all' class is not available, it need to run countIncrease function, if class available no need to run the function,
In every time section need to check whether the class is available or not.
class Grid {
init() {
$('.grid').each(function() {
const $this = $(this);
// getting values & url from from html
const dropDownUrlpath = $this.find('.grid__dropdown-select').attr('data-ajaxurl');
const hasClass = $this.find('.grid').hasClass('grid_showall');
// countIncrease shows the inital 6 compoents/div and rest of will be hidden
// onclick it will display 3 components/div
function countIncrease() {
let limit = parseInt($this.find('.grid__component').attr('data-initcount'), 10);
const incrementalCall = parseInt($this.find('.grid__component').attr('data-incrementalcount'), 10);
$this.find(`.grid__content > .grid__component:gt(' ${limit - 1} ') `).hide();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
else {
$this.find('.grid__cta').show();
}
$this.find('.grid__cta').on('click', function(event) {
event.preventDefault();
limit += incrementalCall;
$this.find(`.grid__content > .grid__component:lt(' ${limit} ')`).show();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
});
}
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
// on dropdown change taking the selected dropdown value and adding #end of the url and replacing the previous html
$this.find('.grid__dropdown-select').on('change', function() {
const optionValue = this.value;
$.ajax({
url: dropDownUrlpath + optionValue,
success(result) {
$this.find('.grid__content').html(result);
countIncrease();
}
});
});
});
}
}
I written if condition, but it running once and giving false condition in both the scenarios,
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
How to handle it...?
shouldnt you add a parameter to the .hasClass so it knows what to check?
if ( $this.hasClass ('some class') === true ) {
alert('something');
}
or set if(hasClass.length > 0){}
keep the checking class in a variable by finding with parent div,
const hasClass = $this.find('.grid').hasClass('grid_showall');
gets the attribute value for only the first element in the matched set with .attr() method
const classInthis = hasClass.attr('class');
check the condition, with
if (classInthis !== 'grid_showall') {
countIncrease();
}

How to validate specific input fields in a specific div

I am able to validate all fields within a div but I only want to validate specific fields. Here is a jsfiddle to show what I mean Once validation is passed the div is hidden. I have to enter data in all of the fields so if you check 'Yes' from the checkbox you will see a input field appear I don't want to include that and also if you select 'NoGame' from the dropdownlist once you enter data in all the fields apart from the two fields in the lower div (green border) and click the Test1 button you will see what I mean. Any suggestions?
This is the code which validates all fields and then Hides the div, which can also be seen in the fiddle
function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
$.each($div.find("input[type='text']"), function (i, input) {
if ($(input).val().length == 0 || $.trim($(input).val()) == '') {
result = false;
return;
}
});
return result;
}
$(document).ready(function(){
$("#hide").click(function(){
if (IsValid('contentone')) {
$('#contentone').hide();
};
});
});
Input fields of type text that you don't want to validate exclude them from the validation process
function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
var excludeElement = ["reason"]; //<-- EXCLUDED ELEMENTS IDS
$.each($div.find("input[type='text']"), function (i, input) {
if ($.inArray($(input).attr('id'), excludeElement) < 0 && ($(input).val().length == 0 || $.trim($(input).val()) == '')) {
result = false;
return;
}
});
return result;
}

Return through all functions

Is it possible to return through multiple functions?
I have a jQuery on click function with a $.each loop in it. In the $.each loop I test for various conditions, and if not met display an alert message and then return. Here is a cut down version of my code:
$(document).on('click', '.add-to-basket, #add-to-basket', function(e) {
var data = {
id: $(this).data('id'),
quantity: 1
};
if($('#quant').length > 0) {
data.quantity = $('#quant').val();
}
var i = 0;
var j = 0;
if($('.product-option').length > 0) {
$('.product-option').each(function(index, element) {
if($(this).is('select')) {
//check to see if this is a required select, and return if a selection has not been made.
if($(this).data("force") == 1 && $(this).val() == 0) {
AlertDialogue($(this).data("title") + " requires a selection before you can add this product to your basket.", "Required Option");
return;
}
data.opts[i++] = $(this).val();
} else if($(this).is('input[type="checkbox"]:checked')) {
data.opts[i++] = $(this).val();
//check to see if this is a required group of checkboxes, and if so at least one has been checked. If not return.
} else if($(this).is('input[type="checkbox"]')) {
if($(this).data("force") == 1 && $('input[name="' + $(this).prop("name") + '"]:checked').length == 0) {
AlertDialogue($(this).data("title") + " requires at least one option to be checked before you can add this product to your basket.", "Required Option");
return;
}
} else if($(this).is('input[type="radio"]:checked')) {
data.opts[i++] = $(this).val();
} else if($(this).is('textarea')) {
//Check to see if this is a required textarea, and if so make sure there is some text in it.
if($(this).data("force") == 1 && $.trim($(this).val()).length == 0) {
AlertDialogue($(this).data("title") + " requires text before you can add this product to your basket.", "Required Option");
return;
}
if($(this).val().length > 0) {
data.text[j].id = $(this).data("id");
data.text[j++].val = $(this).val();
}
}
});
}
//submit product to the cart
});
However the return will only break that loop of the $.each loop, and start the next loop. I would like to not only break the $.each loop, but return from the on click function entirely.
Is this possible?
If so, how can I achieve this?
To exit from $.each you should return false
To exit from event handler function you should use return
As per your requirement you can do little like below,
var break = false;
$('.product-option').each(function(index, element) {
// rest of code
if(condition) {
break = true;
return false; // this will break out of each loop
}
});
if(break) {
return; // return from event handler if break == true;
}
// rest of code
Check out the docs for jQuery.each():
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same
as a continue statement in a for loop; it will skip immediately to
the next iteration.
Essentially, use return false; instead of just return;.

Categories

Resources