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;}
Related
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 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 file the other is textarea
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
User has to either upload a file or type text. If the user leaves blank both of the inputs, it should say like "choose a file or type info" if he/she fills both, it is ok.
My JQuery:
$(function(){
$(".input_field").prop('required',true);
});
I have this code. How can we implement something like if else condition to make it required one of the fields?
See this fiddle https://jsfiddle.net/LEZ4r/652/
I modified your code to each all the elements with a class of input_field when the form is submitted.
$(function(){
$('form').submit(function (e) {
var failed = false;
$(".input_field").each(function() {
if (!$(this).val()) {
failed = true;
}
});
console.log(failed);
if (failed === true) {
e.preventDefault();
}
});
});
Based on your question, there are only two possible conditions:
if either one field or both fields are filled, user passes validation
if no fields are filled, user fails validation
This can be easily done by checking for the value of either input. As long as one is not empty, user passes the test. This if/else condition can be written as:
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
// Passed validation
} else {
// Failed validation
}
A simple pattern to check for errors is to create an error flag, which will be raised when one or more validation checks have failed. You evaluate this error flag at the end of the script before manual form submission:
$(function(){
$('form').on('submit', function(e) {
e.preventDefault();
// Perform validation
var error = false;
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
alert('Passed validation');
error = false;
} else {
alert('Please fill up one field');
error = true;
}
// Check error flag before submission
if(!error) $(this)[0].submit();
});
});
See working fiddle here: http://jsfiddle.net/teddyrised/LEZ4r/653/
Check inside your form If atleast one is done break the loop and go for submit else return false
$(function(){
$('form').on('submit',function(e){
var doneOnce = false;
$(this).children().each(function(){
if($(this).val()){
doneOnce = true;
return false;//return false will break the .each loop
}
});
alert(doneOnce)
if(!doneOnce){
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
<input type=submit />
</form>
You can write codes in Javascript to validate form. You have to make an onclick or onsubmit function, and the function will check whether any of the input field is empty. You can write something like the following code:
<script>
function validateForm() {
var fstname=document.getElementById("fname").value;
var lstname=document.getElementById("lname").value;
if(fstname===null || fstname===""){
alert("Plese choose a file.");
return false;
}
else if(lstname===null || lstname===""){
alert("Plese type file info.");
return false;
}
else{
return confirm("Your file: "+fstname+" and it of type "+lstname);
}
}
<body>
<form action="text.php" name="myForm" onsubmit="return validateForm()">
First Name: <input type="file" id="fname" name="FirstName">
Last Name: <input type=text" id="lname" name="LastName"><br/>
<input type="submit" value="Submit">
<form>
</body>
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 want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.