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>
Related
I have a simple HTML form with two inputs. One is a radio input and the other is a numeric input.
Using a Javascript function, if the radio option is selected as Insurance - YES(1), then the script must force a numeric value input on the Insurance Value ins_value input. If the radio input is selected as NO, then no input to be entered in the text input.
I have tried to find a similar example but have only found simple examples where an alert is triggered.
I am learning Javascript and have been through tutorials - but also no similar examples.
<script>
function INSURANCE() {
var insurance = document.forms["RegForm"]["optradio"];
var ins_value = document.forms["RegForm"]["ins_value"];
if (insurance.value == 0) {
"";
return false;
} else {
if (ins_value.value == "") {
window.alert("Please insert Insurance value.");
ins_value.focus();
return false;
}
return true;
}
</script>
I expect once the form is submitted, it should either force an insurance value input or not, based on the radio input selection.
First of all, you need a checkbox for you're use case. Radio buttons force a selection of one in many. You only have a "is numeric" flag meaning you're value is either true or false.
Well I guess you can achieve you're goal by changing you're input type according to user selection:
<input id="optcheckbox" type="checkbox" onclick="HandleCheckboxClick();" />
<input id="ins_value" type="text" onclick="HandleCheckboxClick();" />
<script>
function HandleCheckboxClick() {
var type = 'text';
var checkbox = document.getElementById('optcheckbox');
if(checkbox.checked) {
type = 'number';
}
document.getElementById('ins_value').type = type;
}
</script>
I hope that helps.
Best regards
Only seeing the Javascript it's difficult to figure out what's going on, including the HTML would help a lot. Also, this question is a big vague which is makes it hard to answer.
First, when are you trying to trigger the forcing the numeric value? When the user clicks on the radio button? If so, then call that function on the change event. If you're going to change it on the submit, then put the code in the submit function.
I recommend building an array of numeric values and matching that up with the 0, 1, 2, ... values of the radio buttons. When you set the text input, plug that value into your numeric array.
Here's a JS fiddle of using an array in conjunction with the radio button values.
https://jsfiddle.net/Chris_Hayes/coxta1bw/1/
var form = document.querySelector("form");
var numbers = [30, 20, 80];
form.addEventListener("submit", function(event) {
form["textinput"].value = numbers[form["contact"].value]
event.preventDefault();
}, false);
If the user skips the radio buttons, just make that check in the on submit function before filling in the numerical input.
var radio = document.getElementById('optradio');
var input = document.getElementById('ins_value');
radio.addEventListener("click", function(){
if(radio.value == 0){
radio.value = 1;
this.checked = true;
input.removeAttribute('disabled')
input.value = radio.value;
}
else{
radio.value = 0;
input.setAttribute('disabled','disabled');
input.value = '';
this.checked = false;
}
});
<input type="radio" name="optradio" id="optradio" value="0">
<input type="number" name="ins_value" id="ins_value" value="" disabled>
add disabled attribute to your numeric input like so
html:
<input type="radio" name="optradio" id="optradio" value="0">
<input type="number" name="ins_value" id="ins_value" value="" disabled>
javacript:
<script type="text/javascript">
var radio = document.getElementById('optradio');
var input = document.getElementById('ins_value');
radio.addEventListener("click", function(){
if(radio.value == 0){
radio.value = 1;
this.checked = true;
input.removeAttribute('disabled')
input.value = radio.value;
}
else{
radio.value = 0;
input.setAttribute('disabled','disabled');
input.value = '';
this.checked = false;
}
});
</script>
add the script below your html code
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 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)
I am trying to validate a set of radiobuttons that output a message upon submit informing the user that they must make a selection before they continue. The code below never recognises that the buttons are checked and always outputs the alert message. How would I adapt this code to make it work?
Radiobuttons:
<input type="radio" name="examtype" value="GCSE"onclick="return confirmation();"/>GCSE
<input type="radio" name="examtype" value="AS" onclick="return confirmation();"/> AS
<input type="radio" name="examtype" value="A2" onclick="return confirmation();"/> A2 </td> </tr>
Function for confirmation onclick:
function confirmation() {
for (var i=0; i < document.ExamEntry.examtype.length; i++)
{
if (document.ExamEntry.examtype[i].checked)
{
var answer = confirm(document.ExamEntry.examtype[i].value)
if (answer){
document.ExamEntry.examtype[i].checked = true;
}
else{
document.ExamEntry.examtype[i].checked = false;
}
}
}
}
Code currently being used for rejecting unselected radiobuttons:
if (document.ExamEntry.examtype.checked){
alert('checked') //for testing if statement runs when appropriate//
}
else {
msg+="You must enter the exam type \n";
result = false;
}
Try setting a variable as false outside both functions, and then if the confirmation function runs, assign that variable to true.
Then in your next function where you check if the user have clicked a radio button or not, use an if statement that runs only if the variable has been set to false which could include your alert message.
Hope this helps :)
Here's an example code on how to validate radioboxes: http://jsfiddle.net/jyUAM/3/
<script type="text/javascript">
function validateRadioboxesByName(form, name)
{
var el = form[name];
for (i = 0; i < el.length; ++i) {
if (el[i].checked)
return true;
}
return false;
}
function checkRegistration() {
var isValid = validateRadioboxesByName(document.forms.test, "examtype");
if (!isValid)
alert("Please check one of the radiobox.");
return isValid;
}
</script>
<form name="test" onsubmit="return checkRegistration()">
<input type="radio" name="examtype" value="GCSE"/>GCSE
<input type="radio" name="examtype" value="AS"/> AS
<input type="radio" name="examtype" value="A2"/> A2
<button type="submit">Send</button>
</form>
This way you don't need to remember the state of a clicked radiobox, but just ask the browser when you need the data, that is, before submitting the data.
This tutorial may give you more ideas on how to visualize the message to the user instead of using an ugly alert call: http://www.the-art-of-web.com/html/html5-checkbox-required/
That the examples on the last link are for checkboxes shouldn't scare you, you can easily apply the same to radio- input-boxes and the like.
I made a input checkbox that contains array values. so it generates plenty of rows in a table.
But it needs for me to check it all to submit.
It doesn't allow me to check only few not all.
<form>
<table>
<td>
<input required="required" type="checkbox" name="id[]" id="id" value="<?php echo $result2["id"]; ?>"/>
</td>
<input type="submit" name="submit" value="submit"/>
</table>
</form>
How can i make the required field able to check atleast one and able to submit even if not all are checked?
I dont know if I understand you,
but maybee you need something like this:
Online demo
Main part with notes:
$('#frm').bind('submit', function(e) { // set this function for submit for your formular
validForm = true; // default value is that form is correct, you can chcange it as you wish
var n = $( "input:checked" ).length; // count of checked inputs detected by jQuery
if (n != 1) { validForm=false; } // only if you checked 1 checkbox, form is evaluated as valid
if (!validForm) { // if result of validation is: invalid
e.preventDefault(); // stop processing form and disable submitting
}
else {
$('#echo').html("OK, submited"); // ok, submit form
}
});
You can use any number of comboboxes under any tag and get count of selected by jQuery, then use any rule for validate form.