How to give alert when user clicked on disabled input field? - javascript

I have two input fields i.e. VimeoLink and YTLink, I am trying to disable YTLink until and unless the VimeoLink input field is empty, and if the user clicked on the disabled YTLink input field an alert needs to be shown, but an alert is not working!
I have tried several solutions for alerts like -
$("YTLink").click(function (evt) {
console.log('disabled input clicked!');
});​
//for disabling input on first
$(document).ready(function() {
document.getElementById('YTLink').disabled = true;
});
checking
if vimeolink input is empty or not
$('input[name=vimeoLink]').change(function() {
if (document.getElementById('vimeoLink').value !== '') {
document.getElementById('YTLink').disabled = false;
} else {
document.getElementById('YTLink').disabled = true;
}
});
//alert on click YTLink input
var container = document.querySelector('#YTLink');
container.addEventListener('click', function() {
console.log('disabled input clicked!');
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group last mb-3">
<label for="name">VimeoLink</label>
<input type="text" class="form-control" placeholder="" name="vimeoLink" id="vimeoLink">
</div>
<div class="form-group last mb-3">
<label for="name">YTLink</label>
<input type="text" class="form-control formcheck" placeholder="" name="YTLink" id="YTLink">
</div>

Ans is NO. Disabled inputs don't fire click event. Solution is wrap your input with div, and fire click on that div using class or ID.
Example:
//for disabling input on first
$(document).ready(function() {
document.getElementById('YTLink').disabled = true;
});
//checking
//if vimeolink input is empty or not
$('input[name=vimeoLink]').change(function() {
if (document.getElementById('vimeoLink').value !== '') {
document.getElementById('YTLink').disabled = false;
} else {
document.getElementById('YTLink').disabled = true;
}
});
//alert on click YTLink input
var container = document.getElementById('tempdisable');
container.addEventListener('click', function(event) {
var inp = document.getElementById('YTLink');
if (inp.disabled) {
console.log('disabled input clicked!');
}
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group last mb-3">
<label for="name">VimeoLink</label>
<input type="text" class="form-control" placeholder="" name="vimeoLink" id="vimeoLink">
</div>
<div class="form-group last mb-3">
<label for="name">YTLink</label>
<div id="tempdisable">
<input type="text" class="form-control formcheck" placeholder="" name="YTLink" id="YTLink">
</div>
</div>

Since disabled control elements can't have events bound to them, you'd need to bind an event to an ancestor element and make a check to see whether the target was the input.
You can then go on to check if it's disabled, and if so, show your alert:
$(document).on('click',function(e){
if(e.target.id == "Travellerpaymentinfo_cc_number" && e.target.disabled){
alert("The textbox is clicked.");
}
});

Related

Remove Div from jquery when checkbox is clicked

I have to implement the logic when add button is clicked,it will add the input field and when remove button is clicked it removes the fields, For this requirement code is working fien,but when i add checkbox ,if checkbox is clicked the requirement is that input field should be disabled and all new input fields will be removed,in my case only one input filed removes,i have to remove all fields.
var maxField = 5; //Input fields increment limitation
var add_button = $('#add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div id="fieldhtml"><input type="text" name="socials[]" value="" />
<img src="{{ 'remove-icon.png' | asset_url }}"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
<div class="col-lg-6 col-sm-12">
<div class="input-icons pt-2">
<label for="socials">Socials <span class='req'>*</span></label>
<div class="input-icon">
<i class="plus"></i>
<div class="icon"></div>
<div class="field_wrapper">
<input type="text" class="validate input-field validate-input-structure" data-input-type="text" name="socials[]" value="" id="socials" required />
</div>
<label for="chksocials">
<input type="checkbox" id="chksocials" name="chksocials" />
My business doesn’t have social media
</label>
</div>
</div>
</div>
$(function(){
//Once add button is clicked
$(add_button).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
$("#chksocials").click(function () {
if ($(this).is(":checked")) {
$("#add_button").attr("disabled", "disabled");
$("#socials").attr("disabled", "disabled");
$("#fieldhtml").remove();
} else {
$("#socials").removeAttr("disabled");
$("#fieldHTML").removeAttr("disabled");
$("#add_button").removeAttr("disabled");
//$("#fieldhtml").parent('div').show();
$("#socials").focus();
}
});
You need to define the fieldHTML based on the Jquery Documentation.
// HTML
<div class="col-lg-6 col-sm-12">
<div class="input-icons pt-2">
<label for="socials">Socials <span class='req'>*</span></label>
<div class="input-icon">
<a href="" class="add-button" title="Add field" id="add_button">
ADD
</a>
<div class="icon"></div>
<div class="field_wrapper">
<input type="text" class="validate input-field validate-input-structure socials" data-input-type="text" name="socials[]" value="" required />
</div>
<label for="chksocials">
<input type="checkbox" id="chksocials" name="chksocials" />
My business doesn’t have social media
</label>
</div>
</div>
</div>
// JS
const add_button = $('#add_button');
const wrapper = $('.field_wrapper');
$(function(){
const maxField = 5;
let x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < maxField){
x++;
// This is to create element in JQUERY
const fieldHTML = $('<div class="fieldhtml"><input type="text" name="socials[]" value="" />REMOVE</div>');
$(wrapper).append(fieldHTML);
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$("#chksocials").click(function () {
if ($(this).is(":checked")) {
wrapper.hide();
} else {
wrapper.show();
$(".socials").focus();
}
});
});
Note : do not use the same HTML ID multiple times, see here.

Email Validation with Materialize and jQuery

I am trying to make a form with Materialize that validates one email. I start off with a submit button toggled to disabled. Ideally, when the email is filled in and validated, the submit button will stop being disabled and the user can click it to the next page. Here is my HTML:
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="text" name= "email" class="validate" required="" aria-required="true">
<label for="email">Email Address</label>
</div>
<br></br>
<a class="waves-light btn red lighten-2 disabled" id="submit">Submit
<i class="material-icons right">send</i>
</a>
<br></br>
<br></br>
<br></br>
</form>
Here is the JavaScript/jQuery:
$(document).ready(function(){
$('.parallax').parallax();
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
$('body').on('click', 'input', function() {
checkValidity($(this));
});
$('body').on('focusout', 'input', function() {
checkValidity($(this));
});
function checkValidity (current) {
let isValid = true;
if (!current.val()) {
isValid = false;
} else {
isValid = iteratatingForm(current);
}
const submit = $('#submit');
if (isValid) {
submit.removeClass('disabled');
} else {
if (!submit.hasClass('disabled')) {
submit.addClass('disabled');
}
}
}
function iteratatingForm (current) {
if (!document.forms['survey']['email'].value) return false;
return true;
}});
Please let me know what I'm doing wrong! Thanks!
You can use email type for your input and a button submit who will trigger validation input.
I added a function to check if email is valid with a regex. (Found here : How to validate email address in JavaScript? )
You have to add jQuery Validation Plugin
$(document).ready(function(){
$('#survey input').on('keyup', function(){
var validator = $("#survey").validate();
if (validator.form() && validateEmail($('#email').val())) {
$('#submitButton').prop('disabled', false);
$('#submitButton').removeClass('disabled');
}
else{
$('#submitButton').prop('disabled', true);
$('#submitButton').addClass('disabled');
}
} );
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email.toLowerCase());
}
/*
Confirmation Window
*/
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="email" name= "email" class="validate" required="true" aria-required="true">
<label for="email">Email Address</label>
</div>
<button type="submit" form="survey" value="Submit" class="waves-light btn red lighten-2 disabled" disabled='disabled' id="submitButton">Submit</button>
</form>
StackOverflow snippet bug due to jQuery validation plugin, but it works in CodePen
Another way to solve this is to add a regex field to your <input ... elements e.g.
<div class="input-field col s6">
<input id="email" type="text" class="validate" value="hello#email.com" regex="(?!.*\.\.)(^[^\.][^#\s]+#[^#\s]+\.[^#\s\.]+$)" required="" aria-required="true" value="hello#email.com" >
<label for="email">Email</label>
<span class="helper-text" data-error="Invalid email address."></span>
</div>
The nice thing about this is you can have individual regex validation for other fields. For example, you could have other inputs such as name / age e.g.
name (only contain groups of UPPER-CASE characters separated by a single space e.g. JAMES JONES - regex = ^[A-Z]*(\s[A-Z]+)*$).
age (only contain numbers - regex = ^\d+$).
NOTE: - I recommend the https://regex101.com/ website to test our your regex expressions against example text.
To validate using e.g. JQuery - you would add listeners to each of your input elements: -
$(document).ready(function(){
$("input").on('input propertychange blur', function(event) {
var elm = event.currentTarget;
var val = elm.value;
var isValid = true; // assume valid
// check if required field
if (elm.hasAttribute("required")) {
isValid = val.trim() !== '';
}
// now check if regex
if (isValid && elm.hasAttribute("regex")) {
var regex = new RegExp(elm.getAttribute("regex"), 'g');
isValid = regex.test(val);
}
elm.classList.remove(isValid ? "invalid" : "valid");
elm.classList.add(isValid ? "valid" : "invalid");
updateButtonState();
});
});
function updateButtonState () {
var numOfInvalid = $('input.invalid').length;
if (numOfInvalid > 0) {
$('.submit-button').prop('disabled', true);
$('.submit-button').addClass('disabled');
}
else{
$('.submit-button').prop('disabled', false);
$('.submit-button').removeClass('disabled');
}
}
When the page loads the JQuery function listens to changes to the input (and also blur events). It first of all checks if the input is a required field and validates that first. Next of all, it checks if a regex attribute exists, and if so, performs regular expression based validation.
If the validation fails, then the function adds/removes classes related to Materialize CSS and then finally updates the button state. This is optional but very nice if you are filling in a form (button is only enabled if everything is valid).
See the following CodePen to see everything in action: -
https://codepen.io/bobmarks/pen/oNGGvWq

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

Client-side validation fire according to empty textboxes on button click

I have 4 text boxes. I want to validate according to bewlow criteria:-
1). IF first textbox value not blank and anotherthree are blank than addclass error on that blank textbox.
2). If second textbox value not blank and 1st, 3rd and 4th textbox valueare blank than addclass error on that blank textbox.
3). If first two textbox value are not blank and another textox value are blank than addClass error on that blank textbox.
4). If First and third textbox value are not blank and 2nd and 4th textbox value are blank than addclass error on that blank textbox.
5).If 3 textboxs value are not blank and one textbox value blank than addclass error on that blank textbox.
This is My jquery validation code:-
$(".submit_data").click(function(){
input1 = $("#data1").val();
input2 = $("#data2").val();
input3= $("#data3").val();
input4= $("#data4").val();
if(input1 == "" && input2 == "" && input3 == "" && input3 == "")
{
$(".data-form").addClass('required');
$(".data-form").addClass('error');
$(".new-data-form").addClass('required');
$(".new-data-form").addClass('error');
}
if( input1 != "" && input2 == "" && input3 == "" && input3 == "" )
{
$("#data2").addClass("error");
$("#data3").addClass("error");
$("#data4").addClass("error");
return false;
}
});
HTML:-
<div id="painting_form" class="painting-form-wrap">
<div class="form-group">
<label class="col-sm-2 control-label">Input 1</label>
<div class="col-sm-10">
<input type="text" name="data1" value="" id="data1" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 2</label>
<div class="col-sm-10">
<input type="text" name="data2" value="data2" id="input-ceilheight" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 3</label>
<div class="col-sm-10">
<input type="text" name="data3" value="" id="data3" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 4</label>
<div class="col-sm-10">
<input type="text" name="data4" value="" id="data4" class="form-control painting-form1">
</div>
</div>
</div>
You can loop through all input boxes and check if any of the input field is filled with value the add error class to all other empty input boxes.
Try this:
$(document).ready(function() {
$(".submit_data").click(function(){
flag = 0; // check if eny input box is filled with value or not
$("input[type=text]").each(function() {
if($(this).val() != '') {
flag = 1; // set flag one if any of the inputbox has value entered
}
});
if(flag == 0) { // if flag is 0 means all input are empty then remove error class from all inputs
$("input[type=text]").each(function() {
$(this).removeClass('required');
$(this).removeClass('error');
});
}
if(flag == 1) { // if any of the input box is filled with value
$("input[type=text]").each(function() {
if($(this).val() == '') {
$(this).addClass('required'); // add error class to empty inputboxes
$(this).addClass('error');
} else {
$(this).removeClass('error'); // remove error class if inputbox has value
}
});
}
return false;
});
});
Use jquery validation plugin for this.
It's quickly and easy to implement.
Will be something like this
$(form).validate()
If you want to add some rules, like minlength/maxlength and so on .
// Try this
$(form).validate(rules:{
inputname: {
minlength: 8
}
})

Error in enabling submit button when all field are entered

I have a login form.
Field: Username textbox, password text box, 2 check boxes, submit button--- everything inside a form.
submit button initially disabled. It is enabled only when username, password or AT LEAST any one checkbox is checked. button gets enabled when username & password fields are entered. no change happens even if checkbox is checked or unchecked.
<form class="form-horizontal" role="form" action="page2.html">
<div class="form-group">
<label for="txtusername" class="col-sm-4 control-label ">Username</label>
<div class="col-sm-8">
<input type="text" class="form-control textboxprop" id="txtusername" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="txtpassword" class="col-sm-4 control-label ">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control textboxprop" id="txtpassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<div class="checkbox">
<input id="chk" type="checkbox" >chk1
<input id="chk" type="checkbox" >chk2
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="signin" class="btn btn-default" disabled>Sign in</button>
</div>
</div>
</form>
This is the form. Below given is the javascript function I use.
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
You need to listen checkboxes change event too. Try this code:
var $input = $('input'),
$check = $input.filter(':checkbox'),
$register = $('#signin');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$check.filter(':checked').length);
});
Demo: http://jsfiddle.net/jy3UR/1/
Your HTML is invalid. A <label> is closed which wasn't started and you have a duplicate ID 'chk'...
You need to put it in the onload event of the document and indeed as #dfsq already stated, you need to add a check for the checkboxes too, like so:
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$chk = $('input[type=checkbox]');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$chk.filter(':checked').length);
});
})
otherwise it will get executed when the DOM has not fully loaded yet and your fields will not be available...
DEMO
First of all you have used same id for both the check box.
rename it like below
<input id="chk1" type="checkbox" >chk1</label>
<input id="chk2" type="checkbox" >chk2</label>
and modify your code like below :
<script>
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
var checked = $("input[type='checkbox']:checked");
if(checked.length >0) // check if atleast one checkbox checked
trigger = true;
if(!trigger){
if(!$(this).val()) {
trigger = true;
}
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
</script>
You should try this simple solution :
jQuery(function($) {
$('form input').on('change',function() {
isDisabled = !(($('#txtusername').val().length > 0 && $('#txtpassword').val().length > 0) || $('input[type="checkbox"]:checked').length > 0);
$('#signin').attr('disabled', isDisabled);
});
});
It does its job.

Categories