Please imagine this part of a web form. Two checkboxes (with the same name="myCheckbox") and two text inputs. If the first checkbox is checked, the first text input must not be empty. If the second checkbox is checked, the second text input must not be empty. To validate this I use the script below:
// huge validation code above
}else if (!document.myForm.myCheckbox[0].checked && !document.myForm.myCheckbox[1].checked){
jAlert ('Please select one of the two checkboxes!',function(){$(myForm.myCheckbox).focus();});
return false;
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value=="") {
jAlert ('You have selected the first checkbox. Please make sure that the first text input is not empty!',function(){$(myForm.myFirstTextInput).focus();});
return false;
}else if (myForm.myCheckbox[1].checked && myForm.mySecondTextInput.value=="") {
jAlert ('You have selected the second checkbox. Please make sure that the second text input is not empty!',function(){$(myForm.mySecondTextInput).focus();});
return false;
// huge validation code below
Everything works just fine. But now, I also want to check if in the first text input the user has entered at least 10 digits. I update my validation code, please see below:
// huge validation code above
}else if (!document.myForm.myCheckbox[0].checked && !document.myForm.myCheckbox[1].checked){
jAlert ('Please select one of the two checkboxes!',function(){$(myForm.myCheckbox).focus();});
return false;
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value=="") {
jAlert ('You have selected the first checkbox. Please make sure that the first text input is not empty!',function(){$(myForm.myFirstTextInput).focus();});
return false;
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value!=="")
var x = document.getElementById("myFirstTextInput");
var y = x.value;
var totalNrOfDigits = 0;
for(var i = 0; i < y.length; i++){
if(/\d/.test(y[i])){
totalNrOfDigits++;
}
}
if(totalNrOfDigits < 10) {
jAlert ('Please make sure that the first text input contains at least 10 digits!',function(){$(myForm.myFirstTextInput).focus();});
return false;
}else if (myForm.myCheckbox[1].checked && myForm.mySecondTextInput.value=="") {
jAlert ('You have selected the second checkbox. Please make sure that the second text input is not empty!',function(){$(myForm.mySecondTextInput).focus();});
return false;
// huge validation code below
My problem: after I add the check for at least 10 digits, if the users clicks the SECOND check box, then "mySecondTextInput" is no longer validated and the form is submitted. I really don't get it why and already wasted most of may day...
Sorry because I have not added the whole code: It's really huge, it's a pretty complex web form.
In the second code example, you forgot the opening curly bracket on line 11, so only the first statement following the else if condition will be evaluated.
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value!=="")
^
|
Related
I've been working on a simple form that will have several (2-3) sets of questions that contain radio buttons as answers. Each radio button has a number value. I was able to work in a logic that shows or hides a text box when the user selects a certain radio button.
In the original code I found, the validation checks only one specific question, but I'm wanting to update the validation code in a way that if ANY of the questions have a text box visible, and its empty, the alert pop up should come up.
Here is a JSFiddle page with the code: https://jsfiddle.net/nxenxoo/92myvwc3/25/
At this moment, if on question #1 I click on radio buttons 1-3, and forget to fill in the text box, move onto the second question and hit radio button 10, for example, the validation works great. I get a pop up.
However, lets say I fill in the text box required for question #1 and leave the text box that appears for question #2, then I get a 404 error upon submit.
I was trying to work in a OR statement || below, I was hoping it would work, but unfortunately it does not.
function validateForm(){
var x= $("form input[type=text]").val();
if ($('.showother' || '.showother2').is(":visible")) {
if ( x==null || x=="")
{
alert("Please fill in all text boxes");
return false;
I am curious to figure out what could be the problem. I know very little of javascript, so I am sorry if this is a very basic queston!
HTML
<div id="Other" class="showother" style="display:none">Please specify <input name="textbox" id="textbox" type="text">
</div>
...
<div id="Other2" class="showother2" style="display:none">Please specify <input name="textbox" id="textbox2" type="text">
</div>
Javascript
var x= $("form input[type=text]").val();
...
"form input[type=text]" matches both text inputs, but only returns the value of the first match.
function validateForm(){
var x1= $("#textbox").val(); // first textbox, use id
var x2= $("#textbox2").val(); // second textbox, use id
if ($('.showother' || '.showother2').is(":visible")) {
// check if either are null or empty
if ( x1==null || x1=="" || x2==null || x2=="") {
alert("Please fill in all text boxes");
return false;
}
}
}
Alternatively, check all visible text inputs with one block of code:
$("form input[type=text]").each(function() {
if (
($(this).parent().is(":visible"))
&& ($(this).val()==null || $(this).val()=="")
) {
alert("Please fill in all text boxes");
return false;
}
})
I have a drop-down generated by a backoffice. I cannot change how this drop-down is coded by the backoffice. But I need to make user selection mandatory for this dropdown.
I am using the following code and this works in the JSFIDDLE HERE. However, this code sees if the user chooses another value than value "A" to determine if a selection is made. But this in not good enough in my situation because this value indication changes in other drop-downs.
I need the code to see if the user choice has changed from the text "PLEASE SELECT - $0,00" The "- $0,00" may also vary in different drop-downs, so I need the code to only filter on the "PLEASE SELECT" part of the drop-down text.
Also I need the browser to not ask to turn these warnings off in this case.
Can anyone help please?
function selection()
{
var cat = document.getElementById('select').value;
if (cat == "A") {
alert('Please make a selection');
return false;
}
return true;
}
Alert whatever text you want in a span instead of using alert()
document.getElementById('alert').innerHTML = "Please make a selection";
Check the updated fiddle
So there is couple of questions in your question, lets start with
1) Ensuring the selected item does not start with "PLEASE SELECT".
function selection()
{
var sel = document.getElementById('select');
var selectedText = sel.options[sel.selectedIndex].text;
if (selectedText.startsWith("PLEASE SELECT")) {
alert('Please make a selection');
return false;
}
return true;
}
2) Stopping the user forcing the browser to no longer allow alert
This is not something you can control. If you want full control over a model dialog then there are plenty of these available - bootstrap has one, jQueryUI has one. Any UI framework you're using will almost certainly have one
You can try something like:
function selection()
{
var cat = $('#select option:selected').val();
if (cat == $('#select option:first-child').val()) {
alert('Please make a selection');
return false;
}
return true;
}
For the warnings you will need to change you alert to a modal or on the page as a notice/warning message
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
disable textbox using jquery?
How to prevent changing a textbox value using jquery in document.getElementsByName().
There is an option like this.
document.getElementById("Quantity").defaultValue;
Is there any option to stop my textbox's value from changing in document.getElementsByName().
After my alert, I want to make the value of textbox stay the same when the condition is not matched.
My code:
$(function () {
$('input[name=Quantity]').blur(allownumbers);
});
function allownumbers() {
var elements = document.getElementsByName('Quantity');
for (var i = 0; i < elements.length; i++) {
if (elements[i].value == '' || elements[i].value < 1) {
alert('Please enter a valid value');
return false;
}
else if (elements[i].value > 100) {
alert('There is no enough inventory for this product to fulfill your order');
return false;
}
}
return true;
}
<input id="Quantity" type="text" name="Quantity"/>
Any suggestions.
EDIT :
I tried using this code.
$("#textbox1").removeAttr("disabled");
If I enter 200. The alert appears and the textbox becomes disabled and so I cant even re-enter the correct value in textbox. How to bring back the defaultvalue of my textbox. ?
you would store the original value in a variable or hidden field then replace the value if the update failed. If the range is known when the page loads, you can use a range validation.
An alert is generally too obtrusive for a validation on blur.
Like adamb posted, you can just disable the input. The alternative is to set an attribute on the input (maybe defaultval='the default') and replace the value of the input with the defaultval attribute.
In your example, it may be best for your customers to have the input actually be set to the limit. For instance, you have a condition of 100 being the max, so if someone puts in a bigger number, say 200, it will change the box to the max possible, 100.
I need to be able to tell if the checkboxes are checked to do some basic validation. Problem: I don't have access to the PHP generating this. There is no class added, or the basic checked=checked that most forms have. What's the easiest way to target the checked boxes?
http://www.inpresence.in/event-registration?ee=4
EDIT: freak out!! here's the code, i just need to target the checked boxes, everything else is working. the :checked method of jquery uses checked=checked within the checkbox, which isn't there.
$(document).ready(function(){
//when the submit button is clicked...
$("input.btn_event_form_submit").click(function(){
//find the value of the drop down with one evening or four evenings
var priceOption = $("#price_option-4").val();
//match a string ending with "one evening" as the first numbers will be randomly generated by php
var oneEvening = /^\d{2}\|One Evening$/.test(priceOption);
//match a string ending with "four evenings" as the first numbers will be randomly generated by php
var fourEvenings = /^\d{2}\|Four Evenings$/.test(priceOption);
//HOW DO I GET THE CHECKED BOXES?!
var checkedBoxCount = $('#dates-1351733097 .valid').is(':checked').length;
//if one evening is selected make sure the checked boxes count does in fact equal one
if(oneEvening && checkedBoxCount != 1){
//if it doesn't alert the user and return false
alert('You must select one date');
return false;
}
//if one evening isn't selected, four is. make sure the count does indeed in 4
else if (fourEvenings && checkedBoxCount != 4){
//if it doesnt alert the user and return to the form
alert('You must select four dates');
return false;
}
//else, everything checks out!
else {
return;
}
});
});
Using this JavaScript code you can check if a checkbox is checked:
var isChecked = document.getElementById("my-checkbox").checked;
Or using jQuery:
var isChecked = $('#my-checkbox').is(':checked');
EDIT: Try this and tell me if it works:
var checkedBoxCount = $('#dates-1351733097 .valid:checked').length;
Have you tried using jquery to resolve this?
http://jquery-howto.blogspot.co.uk/2008/12/how-to-check-if-checkbox-is-checked.html
$('#edit-checkbox-id').is(':checked');
use the jquery :checked selector. http://api.jquery.com/checked-selector/
This will give you a boolean in javascript of what you want:
document.getElementById("Nov.12-4_1").checked
You can view source and find the elements to view whatever id's they have.
Other answers: the OP didn't specify that he wanted a jquery answer. If he hasn't used jquery for anything up to this point. I think adding it just for this would be a tad overkill.
I need help creating a javascript loop for an object that I am validating. The validation works, it displays the alert, but it does not focus on the field. The reason it will not focus on the field is because that field's id is unique each time the user adds another account. The code is below:
if ((theForm.LinkedAccts.value == "Yes")&&
(document.getElementById('DLAccount').selectedIndex == ""))
{
alert("Please enter the Delink Account number.");
document.getElementById('DLAccount').focus();
return (false);
}
Thanks!