I have a situation where i want to validate the text entered into a input text field. This is the HTML code:
<div id="err_title" style="display:none;">Please enter a valid Number.</div>
<input type="radio" id="txt_a-radio" value="valueA" checked="checked">
<input type="text" id="txt_a">
<input type="radio" id="txt_b-radio" value="valueB">
<input type="text" id="txt_b" disabled>
By default #txt_b field will be disabled, when user clicks on #txt_b-radio button #txt_b will be enabled and #txt_a will be disabled.
The condition for validation is:
#txt_a can contain only 12 digit number
#txt_b can contain only 20 digit number
Validation should happen once user enters value in enabled field then clicks anywhere outside. If value entered by user is not valid error message #err_title should display.
Suppose if user enters value for #txt_a and then clicks on #txt_b-radio button then validation shouldn't happen since user has switched the input field.In this case #txt_a should be disabled and txt_b enabled.
I have tried with the following code:
$('#txt_a').change(function() {
custNumber = $('#txt_a').val(); expression = /^[0-9]{12}$/;
if(custNumber === '') {
$("#err_title").css('display', 'none');
} else if ((!custNumber.match(regexp))) {
$("#err_title").css('display', 'block');
} else {
$("#err_title").css('display', 'none');
}
});
$input1 = $('input[name="input1"]');
$input2 = $('input[name="input2"]');
$checkbox = $('input[name="checkbox"]');
$input1.on('change', function(e) {
var isValid = this.value.length >= 12;
this.classList.toggle('notValid', !isValid);
})
$checkbox.on('change', function(e) {
$input2.prop('disabled', !this.checked);
})
input.notValid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input1" />
<input type="text" name="input2" disabled />
<input type="checkbox" name="checkbox" />
NOTE:
In example above, I'm mixing vanillia JS, with jQuery. I would recommend avoiding it - I did that to show You how easy (well not always...) it is to do such a simple thing without jQuery.
Basically, if You want to do simple stuff like that, I would recommend to give up on jQuery.
ANSWER:
You are looking for jQuery change event. It triggers once input loose focus.
$(your_input).on('change', function(e) {...} )
You can validate input length like (function inside listener) :
var isValid = this.value.length === 12
Same goes with disabled/enabled input.
You have to attach event listener to checkbox
$(your_checkbox).on('change', function(e) {...} )
then You can get state of checkbox :
var isChecked = this.checked
and disable/enable Your input
$(your_input).attr('disabled', !isChecked)
Related
I'm trying to create a script that keeps our main button disabled until specific field requriments are met.
jQuery(document).ready(function() {//check if all are filled else disable submit
var inputFields = jQuery('#list-item-cc input, #field_28_50 input,#field_28_18 input');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if (jQuery(this).val().length == 0) {
empty = true;
}
});
if (empty) {
jQuery('#gform_submit_button_28').attr('disabled', 'disabled');
} else {
jQuery('#gform_submit_button_28').removeAttr('disabled');
}
I'm having trouble thinking of a way to ensure my inputFields variable can be passed to my inputFields.each(function() in a way that would allow the loop.
We're not worried about all input fields. Just the specific inputs in our inputFields variable.
Is this an effective way to ensure a button is disabled if certain fields are not filled out and can I create the selector in the way that i did and use that in an each statement?
Looks like you are using gravity forms? In that case I would add a css class to each field that you want to validate. That way you don't have to go searching for ID's and change the code for multiple forms.
https://docs.gravityforms.com/css-ready-classes/
Here is a fiddle in which I pretend that I added "ensure-filled" to each item in the gravity forms builder
https://jsfiddle.net/dokLz4hm/3/
Also note that I added a .trim() to the value so that blank spaces aren't counted as input and made the submit button generic so it would work with any field in a form that contains the ensure-filled class
Html
<div>
<div id="arbitraty_id_1">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_2">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_3">
<input type="text" class="ensure-filled" />
</div>
<input type="submit" value="submit" disabled>
</div>
JS
$(document).ready(function() {
var inputFields = $('.ensure-filled');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if ($(this).val().trim().length == 0) {
empty = true;
}
});
$('input[type="submit"]').attr('disabled', empty);
})
})
I dont know how to do a self validation within the page.
I have a php file contains a checkbox and a lot of textboxes. What i would like to do is that, what the user will check on the checkbox will require the textboxes to be filled up. I tried to validate using my statement in php but it always redirect to another page before it validates everything, what i want is that when the user click the submit button, it will trigger the whole page and validate those that should be filled up.
user will check any of the checkbox
then it has a corresponding condition that will make the textboxes required to be filled in!
Hope you guys can help me. I dont know how to do it. javascript or anything? I need solution and show me please.
Codes are like this:
Test 1 <input name="chkbox[]" type="checkbox" value="1"><br>
Test 2 <input name="chkbox[]" type="checkbox" value="2"><br>
Test 3 <input name="chkbox[]" type="checkbox" value="3"><br>
Test 4 <input name="chkbox[]" type="checkbox" value="4"><br>
Test 5 <input name="chkbox[]" type="checkbox" value="5"><br>
<br><br>
Name <input name="txt1" type="text"><br>
Address <input name="txt2" type="text"><br>
Number <input name="txt3" type="text"><br>
Age <input name="txt4" type="text"><br>
Two options for this (all in javascript).
The first, as requested is validating when the user tries to submit.
document.addEventListener("DOMContentLoaded", function (event) {
var isValid = false;
document.querySelector("#formid").addEventListener("submit", function(e){
var _selector = document.querySelectorAll('input[type=checkbox]:checked');
var checked = _selector.length;
for(var i = 0; i<checked; i++){
if (_selector[i].checked) {
if(!document.querySelector('input[name=txt'+ _selector[i].value +']').value)
break;
}
}
if(checked == i)
isValid = true;
if(!isValid){
alert('at least one field is empty');
e.preventDefault(); //stop form from submitting
}
});
});
the second uses an eventlistener to add and remove the required field.
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i<_selector.length; i++){
_selector[i].addEventListener('change', function (event) {
if (event.target.checked) {
document.querySelector('input[name=txt'+ event.target.value +']').required = true;
} else {
document.querySelector('input[name=txt'+ event.target.value +']').required = false;
}
});
}
});
Then you can style the required fields to show which needs to be filled:
:required{border: red solid 1px;}
I am working on a php form where the form is validating with jquery. Now in this form there is radio button list. If the user clicks yes then textbox related to that radio button list will not be validated. If the user clicks no then textbox related to that that radio button list should be validated..
But now the problem is that the developer before me validates the form like this:
jQuery(".required").each(function(){
var vlr = jQuery(this).val();
if(vlr == ''){
alert("Value not to be blank");
jQuery(this).focus();
e.preventDefault();
e.stopPropagation();
return false;
}
});
Html part of radio button list
<tr>
<td class="css-gen7 paragraph">Is premium paid?
<input name="is_premium_016" value="yes" class="required" type="radio">Yes
<input name="is_premium_016" value="no" class="required" type="radio">No
</td>
<td class="css-gen7">if not,why not? <input name="if_not_017" type="text" class="required" style="width:30%"></td>
</tr>
This code is validating the complete form how can I catch the radio button list value and how can I stop validation of the textbox if user ticks yes?
I hope you understand what I want.
Thanks
Try this :
$('#search_form').submit(function() {
if($('#fepUserIDValue').attr("checked") == "checked" && $('#inquiry_date').val() == '') {
alert('Required field missing');
return false;
}
});
Reference links :
jQuery Validation ONLY when certain radio buttons selected
How do I Required text box if radio button selected on form submission using jquery?
HTML
<input type="radio" class="checker yes" name="check" > yes: <br>
<input type="radio" class="checker no" name="check" > no: <br>
<div>
<input type="text" class="isValid" name="name">
</div>
JQUERY
<script>
//select the radio buttons to be clicked
var radioBtns = jQuery('.checker');
//text box to be affected but the radio buttons
var textbox = jQuery('.isValid');
//when any of the buttons is clicked a function to validate the textbox is run
radioBtns.on('click',function(){
// get the button clicked
if (jQuery(this).hasClass('yes')){
// put code to affect textbox when not valid
alert('textbox not valid');
}else if(jQuery(this).hasClass('no')){
//put code to affect the textbox when it is valid
alert('text box is valid ');
}
});
</script>
So you want to Perform your Validation only if the User clicks on No? Is that correct? Well here is a Code that might work for you: assuming the Assumption above is right.
JAVASCRIPT
<script type="text/javascript">
; // CLOSE OFF ANY UNCLOSED JS TAGS... IF ANY ;-)
jQuery.noConflict(); // ADD THE noConflict() METHOD, IN CASE YOU ARE USING OTHER LIBRARIES THAT MAKE USE OF THE $ SYMBOL
(function ($) {
$(document).ready(function(e) {
// CREATE VARIABLES TO HOLD THE FORM, RADIO-BUTTON & TEXT-FIELD JQUERY OBJECTS
var isPremiumRadio = $("input[name=is_premium_016]");
var ifNotWnyNot = $("input[name=if_not_017]");
var controlForm = $("form[name=name_of_your_form]"); //<== PLEASE; PUT THE REAL NAME OF YOUR FORM IN THE STEAD OF "name_of_your_form"
controlForm.on("submit", function(evt){
var theForm = $(this);
var invalids = [];
evt.preventDefault();
evt.stopPropagation();
$(".required").each(function(){
var vlr = jQuery(this).val();
if( $(this).is(isPremiumRadio) ){
if(isPremiumRadio.val() == "no"){
//PERFORM YOUR VALIDATION HERE...
if(ifNotWnyNot.val() == ""){
invalids.push("Blank Field Error");
alert("Could you, please, let us know why not?");
}
}
}else if( $(this).is(ifNotWnyNot) && ifNotWnyNot == ""){
if(isPremiumRadio.val() == "no"){
invalids.push("Blank Field Error");
alert("Could you, please, let us know why not?");
}
}else{
// VALIDATE OTHER FIELDS OTHERWISE...
if(vlr == ''){
invalids.push("Blank Field Error");
}
}
});
if(invalids.length == 0){
theForm.submit();
}else{
alert("Value not to be blank.");
}
});
});
})(jQuery);
</script>
HTML ++FORM++
<tr>
<td class="css-gen7 paragraph">Is premium paid?
<input name="is_premium_016" value="yes" class="required" type="radio">Yes
<input name="is_premium_016" value="no" class="required" type="radio">No
</td>
<td class="css-gen7">if not,why not? <input name="if_not_017" type="text" class="required" style="width:30%"></td>
</tr>
I have two input fields one is for a phone number another is for an email. I would like to disable one field based on the user selection. Should a user click and enter input in either field, it would disable the other and vice versa.
I have written code but it seems to only disable the email field upon entering in numbers in the phone field. Removing the numbers in the phone field removes the disabled from the email input field.
IN MY HTML
<input type="number" name="number" placeholder="hone" class="cellphone" data-cp-visibility="new-user" id="phone">
<input type="email" name="email" placeholder="enter email" class="email" data-cp-visibility="new-user" id="email">
IN JAVASCRIPT
$('#phone').live('blur',function(){
if(document.getElementById('phone').value > 1) {
$('#email').attr('disabled', true);
} else {
$('#email').attr('disabled', false);
}
});
$('#email').live('blur',function(){
if(document.getElementById('email').value > 1) {
$('#phone').attr('disabled', true);
} else {
$('#phone').attr('disabled', false);
}
});
Ultimately I what I am trying to accomplish is that a user can click in either field and then enter input, upon doing so, the other field is disabled. Should they choose to remove the text they entered, it would remove the disabled feature and then they could choose the opposite input field.
I am not sure why it only works for one field and not the other or why if you enter in 333-333-3333 in the phone field it breaks the disabled, but 33333333 works fine.
Any ideas or insight as to what I may be missing?
to fix the dash issue you are having with the phone input, you can try changing it to:
<input type="text" required="" pattern="\d{3}[\-]\d{3}[\-]\d{4}" name="phone" id="phone" data-cp-visibility="new-user" placeholder="123-345-5678">
and here is another version of the js:
var $phone = $('#phone'),
$email = $('#email');
$phone.on('keyup change', function() {
$email.prop('disabled', $(this).val() ? true : false );
});
$email.on('keyup change', function() {
$phone.prop('disabled', $(this).val() ? true : false );
});
You may use jQuery on instead of live. live is deprecated as of jQuery 1.7.
You can also look for the keyup/keydown event on the input element.
$(function(){
$('#phone').on('keyup',function(){
if($(this).val()!=="")
{
$('#email').prop('disabled', true);
}
else {
$('#email').attr('disabled', false);
}
});
$('#email').on('keyup',function(){
if($(this).val()!=="")
{
$('#phone').prop('disabled', true);
}
else {
$('#phone').prop('disabled', false);
}
});
});
Here is a working sample.
I would recommend using .on('input', ...) to listen for changes, this makes it so even if you use the increment/decrement buttons (or other forms of input) you'll trigger the event-handler. Then use .attr('disabled', boolean) to control enable/disabled state, see example below:
$(function() {
$('#phone').on('input', function() {
$('#email').attr('disabled', $(this).val() !== "");
});
$('#email').on('input', function() {
$('#phone').attr('disabled', $(this).val() !== "");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" placeholder="phone" id="phone">
<input type="email" placeholder="enter email" id="email">
Can I somehow insert the required attribute into an input field only if a certain radio is checked?
I have an input field named "ladder-meters" that is not required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.
My input looks like this:
<input type="text" name="ladder-meters" id="ladder-meters">
and should like this at the onchange event on the radio
<input type="text" name="ladder-meters" id="ladder-meters" required>
document.getElementById("ladder").addEventListener('change', function(){
document.getElementById("ladder-meters").required = this.checked ;
})
Whenever the checkbox is clicked, the required attribute will be changed to match the checked attribute of the checkbox. To reverse this relationship, replace this.checked with !this.checked
This may need some adjustment to suit your specific project.
This will work with this checkbox:
<input type='checkbox' id='ladder' name='ladder' />
Tried F. Orvalho, didn't work for me, I had to use
$('#ladder').change(function () {
if(this.checked) {
$('#ladder-meters').prop('required', true);
} else {
$('#ladder-meters').prop('required', false);
}
});
It could be usefull. Thx to F. Orvalho for the structure
Easy to achieve with jQuery:
$('#ladder').change(function () {
if($(this).is(':checked') {
$('#ladder-meters').attr('required');
} else {
$('#ladder-meters').removeAttr('required');
}
});