jQuery - Field values and comparisons - javascript

I am making a form validation and want to check a number of radio button values. By default no values are selected. There are two options for each question - yes and no.
First I hide the 'caution message' and check whenever one of the inputs are changed. What I want to happen is when all options are set to no (value is N), then the error message will show, otherwise it will hide. I want it so that if any of the options are then changed to yes the error message will hide. What happens here is if any of the values are changed to yes the error message shows. Maybe I'm over complicating how this should work?
$('.cautionMessage').hide();
$('.weeeDetailsChange input').change(function () {
var ownBrand = $('input[name="ownbrand"]:checked').val();
var resell = $('input[name="resell"]:checked').val();
var ImportBasis = $('input[name="importbasis"]:checked').val();
var distributeEEE = $('input[name="distributeeee"]:checked').val();
var exportEU = $('input[name="exporteu"]:checked').val();
var distanceSelling = $('input[name="distanceselling"]:checked').val();
if ( ownBrand && resell && ImportBasis && distributeEEE && exportEU && distanceSelling === 'Y' ) {
$('.cautionMessage').show();
console.log('Show');
} else {
$('.cautionMessage').hide();
console.log('Hide');
}
});

Ah I see what's happening -- probably just needed a fresh set of eyes on this.
What you're currently doing is checking that only distanceSelling is yes whereas you should be checking that all values are no and running your show/hide based on that since you want to show the message if any of the values are 'yes'.
Try the following:
$('.cautionMessage').hide();
$('.weeeDetailsChange input').change(function () {
var ownBrand = $('input[name="ownbrand"]:checked').val();
var resell = $('input[name="resell"]:checked').val();
var ImportBasis = $('input[name="importbasis"]:checked').val();
var distributeEEE = $('input[name="distributeeee"]:checked').val();
var exportEU = $('input[name="exporteu"]:checked').val();
var distanceSelling = $('input[name="distanceselling"]:checked').val();
if (ownBrand == 'N' && resell == 'N' && ImportBasis == 'N' && distributeEEE == 'N' && exportEU == 'N' && distanceSelling == 'N' ) {
// all values are 'N'
$('.cautionMessage').show();
console.log('Show');
} else {
// not all values are 'N'
$('.cautionMessage').hide();
console.log('Hide');
}
});
I hope I understood that correctly. Hope that helps!

A couple of changes that I made. I use the property checked prop('checked') instead of val() because it actually returns me a Boolean so I do not need to compare it to y or anything. I then flip the hide and show where the caution message is only hidden when all check boxes are check. Click here to see example
$('.caution').hide();
$(".weeeDetailsChange").change(function(){
var ownBrand = $('input[name="ownbrand"]:checked').prop('checked')
var resell =$('input[name="resell"]:checked').prop('checked')
var ImportBasis = $('input[name="importbasis"]:checked').prop('checked')
var distributeEEE = $('input[name="distributeeee"]:checked').prop('checked')
var exportEU = $('input[name="exporteu"]:checked').prop('checked')
var distanceSelling = $('input[name="distanceselling"]:checked').prop('checked')
if ( ownBrand && resell && ImportBasis && distributeEEE && exportEU && distanceSelling) {
$('.caution').hide();
console.log('hide');
} else {
$('.caution').show();
console.log('show');
}
});

Related

Check value of both text boxes if they have values in it or not

My page have multiple textboxes i wanted to make sure if user select value from text box 1 and leaves text box 2 empty then it should alert a popup that you must have to enter values in both textboxes.
i do not want to compare values with each other.(Like both textbox value must be same)
Textbox 1 is Number field and text box 2 is date field.
If any one value is entered then it should not allow user to submit page it should stop processing and redirect to that textbox which is empty.
Now what i have tried so far.
$( "#button_id" ).click(function() {
var n = document.getElementById('text1');
var m = document.getElementById('text2');
if(n.value.trim() != "" || n.value == undefined)
{
if (n.value.trim() != "" && m.value.trim() == "")
{
alert("text1 should have some value");
return false;
}
}
if(m.value.trim() != "" || m.value == undefined)
{
if (m.value.trim() != "" && n.value.trim() == "")
{
alert("text2 should have some values");
return false;
}
}
});
As mention below code i just wanted to check if textbox is disable or not if textbox is disable then do not test for validation else do.
Partial Solution :
var _domArray = [$("#textbox1"),$("#textbox2")]
var chk = $x('textbox2').disabled = false;
$( "buttonid" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" );
this.browserEvent.preventDefault();
this.browserEvent.stopImmediatePropagation();
return false;
}
})
});
Use the required attribute on your <input>s, then you can check in JavaScript with document.querySelector('form.insertSelectorHere').matches(':valid').
Use an array to store the DOM element,Loop through it and check to check if it is empty, If so through an alert.
Also assuming you are using input type number & date
var _domArray = [$("#text1"),$("#text2")]
$( "#button_id" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" )
}
})
});
Using jquery since you have tagged this with jquery
jsfiddle

Form is submitting even after failing Javascript validation?

I have a form called here:
<span class="aligncenter button">Submit</span>
And I have a JavaScript function here:
if (myForm == 'newIncident')
{
var vDemAge = document.forms['newIncident']['demAge'].value;
var vBibNumber = document.forms['newIncident']['bibNumber'].value;
// Run through validations before submitting form
validateTime();
validateDate();
validateAge();
validateGender();
validateLocation();
validateType();
validateDisposition();
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
else
{
document.getElementById(myForm).submit();
}
So I have each of the validations as a separate function that I am calling in sequence when submitting the form. If I comment out the "document.getElementById(myForm).submit();", the validations run as expected. However, if I leave it uncommented, it submits every time even if the validations fail. How can I stop this from happening?
Thanks!
EDIT:
So this is one of the validations I'm running. They're all structured the same way. Somewhere I should be returning a boolean true/false? How exactly would I insert that in this one below?
function validateDisposition()
{
var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
if (vIncidentDisposition == '')
{
document.forms['newIncident']['incidentDisposition'].className = 'required';
}
else
{
document.forms['newIncident']['incidentDisposition'].className = 'formborder';
}
}
assuming your validation functions return a bool, you should have something like
if( validateTime() && validateDate() && validateAge()... etc ) {
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
I got it working! The boolean idea put me on the right path. Thanks!
I just added a "return true" and "return false" to each of the validations, then used the answer above with the "&&" if to build the logic into the myform "if". If it doesn't pass all of them the else does a "return false". Works like a charm!

How to check drop-down values using JavaScript

I have drop-down and Textbox inside a Gridview so I want to check the followings on a button click:
(1) Check if NOTHING is selected from the drop down first (the drop-down options are either YES, NO or NA) . If nothing is selected, I want to show message that reads like this “Please make selection from the drop-down”
(2) If the selection from the drop-down is NO and the Textbox is blank or empty then I want to show message that says: “Please provide comments”
The first code checks if the text-box is blank and it works and the 2nd code checks if no selection is made from the drop down and that one works fine too so how can i combine between those 2 codes? I want to execute both codes on button click, right now it is only calling the first code. please help. Thanks.
here is my code that checks if the textbox is blank:
<script type ="text/javascript">
function Validate() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var selects = gridView.rows[i].getElementsByTagName('select');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (selects != null && areas != null) {
if (areas[0].type == "textarea") {
var txtval = areas[0].value;
var selectval = selects[0].value;
if (selectval == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true;
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
}
}
}
}
if (!flag) {
alert('Please note that comments are required if you select "No" from the dropdown box. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
and here is the code that checks the drop-down
<script type="text/javascript">
function validate_DD() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('Select'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == 'Select') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select either Yes, No or NA in each dropdown and click the Save button again. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
Try this:
<select id="ddlCars">
<option value="1">Honda</option>
<option value="2" selected="selected">Toyota</option>
<option value="3">BMW</option>
</select>
Accessing dropdown:
To get the value:
var el = document.getElementById("ddlCars");
var val = el.options[el.selectedIndex].value; // val will be 2
To get the text:
var el = document.getElementById("ddlCars");
var car = el.options[el.selectedIndex].text; //car will be Toyota

Adding an if statement inside if statement

I have a function for a button which submits a form. This function checks to see if the 5 checkboxes are selected #co1,#co2,#co3,#div1,#cc1.
It then also checks to see if tcaccept select is set to 1.
If so the form submits, else the alert pops up.
This is the code i have at the moment:
$('#submit2pd').click(function(event) {
var $finishBoxes = $('#co1,#co2,#co3,#div1,#cc1');
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' )) {
alert('Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College');
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
All works brilliantly, but i want to add to this line as i have another option that is required. But this needs to be an if statement.
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' && THE IF STATEMENT))
this is what i need to incorporate into the if statement above.
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank
}
Any help would be greatly appreciated.
How about:
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length &&
$('#tcaccept').val() == '1' &&
!($("#ctl").val() == "1" && $('#ctlapp').val() === "")))
What we're adding here is another condition which says, "And make sure it's not the case that #ctl is 1, and #ctlapp is blank".
Edit: and please see my comment above - your question is not about jQuery, forms, or validation. It's barely about JS.
if($('#tcaccept').val() == '1' && validate()) {
// do something
}
var validate = function(){
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
return false;
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank;
return true;
}
return true;
}
I'd say clean up the code a little, and things will get a bit simpler:
$('#submit2pd').click(function(event) {
var fail_message = 'Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College',
$finishBoxes = $('#co1,#co2,#co3,#div1,#cc1'),
$checkedBoxes = $finishBoxes.filter(':checked'),
tcaccept = $('#tcaccept').val(),
ctl = $("#ctl").val(),
ctlapp = $('#ctlapp').val();
if (tcaccept == '1' && $finishBoxes.length != $checkedBoxes.length ) {
alert( fail_message );
return false;
} else if( ctl == "1" && ctlapp == "" ) {
alert( "some other message" );
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
I left the test for $('#ctl').val() == "0" out because it sounds like that's the only other value it can have, and there's no validation that needs to take place if it is "0".
Use a logic or || to capture both constalations:
$("#ctl").val() == "1" && $('#ctlapp') != ""
OR
$("#ctl").val() == "0"
if (
!(
$finishBoxes.length == $finishBoxes.filter(':checked').length
&&
$('#tcaccept').val() == '1'
&&
(
($("#ctl").val() == "1" && $('#ctlapp') != "")
||
$("#ctl").val() == "0"
)
)
)

How do I prevent JavaScript error message from hiding after just first of multiple corrections?

I have a form that validates user input. When the user clicks the submit button and one or more required fields are empty, a "Required" message appears to the right of the field or label and a general message at the top and bottom. This seems to work fine. However, when I test the form by updating one of the empty required fields, the general messages vanish even though other required fields remain blank. How can I prevent this? I appreciate any assistance. Thanks--DJH
$(document).ready(function() {
$('form').submit(function(event){
var isErrorFree = true;
$('input.required, select.required, textarea.required',this).each(function(){
if ( validateElement.isValid(this) == false ){
isErrorFree = false;
};
});
return isErrorFree;
return getFocus;
}); // close .submit()
var validateElement = {
isValid:function(element){
var isValid = true;
var $element = $(element);
var id = $element.attr('id');
var name = $element.attr('name');
var value = $element.val();
var hideMsg = true;
// <input> uses type attribute as written in tag
// <textarea> has intrinsic type of 'textarea'
// <select> has intrinsic type of 'select-one' or 'select-multiple'
var type = $element[0].type.toLowerCase();
switch(type){
case 'text':
case 'textarea':
case 'password':
if ( value.length == 0 ||
value.replace(/\s/g,'').length == 0 ){ isValid = false; hideMsg = false; }
break;
case 'select-one':
case 'select-multiple':
if( !value ){ isValid = false; hideMsg = false; }
break;
case 'checkbox':
case 'radio':
if( $('input[name="' + name +
'"]:checked').length == 0 ){ isValid = false; hideMsg = false; };
break;
} // close switch()
var method = isValid ? 'removeClass' : 'addClass';
var msgStat = hideMsg ? 'removeClass' : 'addClass';
if ( type == 'checkbox' || type == 'radio' ) {
// if radio button or checkbox, find all inputs with the same name
$('input[name="' + name + '"]').each(function(){
// update each input elements <label> tag, (this==<input>)
$('#errorMessage_' + name)[method]('showErrorMessage');
$('#errorMessage1')[msgStat]('showErrorMessage');
$('#errorMessage2')[msgStat]('showErrorMessage');
});
} else {
// all other elements just update one <label>
$('#errorMessage_' + name)[method]('showErrorMessage');
$('#errorMessage1')[msgStat]('showErrorMessage');
$('#errorMessage2')[msgStat]('showErrorMessage');
}
// $('#errorMessage1')[msgStat]('showErrorMessage');
// $('#errorMessage2')[msgStat]('showErrorMessage');
// after initial validation, allow elements to re-validate on change
$element
.unbind('change.isValid')
.bind('change.isValid',function(){ validateElement.isValid(this); });
return isValid;
// close validateElement.isValid()
// close validateElement object
// close ready object
Do you need to specifically write your own validation script?
Seems a lot of what you're testing for is covered in the jQuery validation plugin - http://docs.jquery.com/Plugins/Validation
Might make life easier

Categories

Resources