JavaScript - If Else - javascript

I have JavaScript code for some function with If Else statements. But it is too long. I need to make it easy. So the problem is, how to reduce the line of codes in the following function?
function clickFunction(e) {
if(document.getElementsByName('insert_data1')[0].value == 1 || document.getElementsByName('insert_data1')[0].value == 0){
document.getElementsByName('inputvalue1')[0].innerHTML = document.getElementsByName('insert_data1')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
if(document.getElementsByName('insert_data2')[0].value == 1 || document.getElementsByName('insert_data2')[0].value == 0){
document.getElementsByName('inputvalue2')[0].innerHTML = document.getElementsByName('insert_data2')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
if(document.getElementsByName('insert_data3')[0].value == 1 || document.getElementsByName('insert_data3')[0].value == 0){
document.getElementsByName('inputvalue3')[0].innerHTML = document.getElementsByName('insert_data3')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
if(document.getElementsByName('insert_data4')[0].value == 1 || document.getElementsByName('insert_data4')[0].value == 0){
document.getElementsByName('inputvalue4')[0].innerHTML = document.getElementsByName('insert_data4')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
e.preventDefault();
return false;
}

This is not tested at all but perhaps something like this might do the trick?
function clickFunction(e) {
e.preventDefault();
var inputs=['inputvalue1','inputvalue2','inputvalue3','inputvalue4'];
var fields=['insert_data1','insert_data2','insert_data3','insert_data4'];
fields.forEach( function(e,i,a){
var field=document.getElementsByName( e )[0];
if( field.value==1 || field.value==0 ) document.getElementsByName( inputs[i] )[0].innerHTML=field.value;
else alert("Please enter 0 or 1 !!");
});
return false;
}

Related

Console log for foreach javascript didn't show up

I've been trying to work on some validation in javascript, just a simple one. But, the error can't show up in the console log. If all the inputs are correct, it will show the "Registration success text" but in the other side, it won't show any of the error text. But it somehow still can get the focus function to the wrong input, only the error texts that are not showing up in the console. I am so confused. Can you guys help me? I'd appreciate that.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
if(name.value === ''){
error.push("Name is required.");
name.focus();
return false;
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
name.focus();
return false;
}
if(uname.value === ''){
error.push("Username is required.");
uname.focus();
return false;
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
uname.focus();
return false;
}
if(email.value === ''){
error.push("Email is required.");
email.focus();
return false;
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
return false;
}
if(passw.value === ''){
error.push("Password is required.");
passw.focus();
return false;
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
confpassw.focus();
return false;
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
if(region.value == 0){
error.push("Region is not selected");
region.focus();
return false;
}
if(gender.value == 0){
error.push("Gender is not selected");
gender.focus();
return false;
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
termss.focus();
return false;
}
if(error.length == 0){
alert("Registration Success!");
} else{
for(var i=0; i<error.length; i++){
console.log(error.length[i]);
};
}
}
You are returning too early so it is never reaching your consoles. You are focusing on multiple fields.
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
You are also doing console.log(error.length[i]); instead of console.log(error[i]);.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
let firstFailedField = null;
const setFirstFailedField = (field) => {
if (!firstFailedField) firstFailedField = field;
};
if(name.value === ''){
error.push("Name is required.");
setFirstFailedField(name);
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
setFirstFailedField(name);
}
if(uname.value === ''){
error.push("Username is required.");
setFirstFailedField(uname);
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
setFirstFailedField(uname);
}
if(email.value === ''){
error.push("Email is required.");
setFirstFailedField(email);
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
setFirstFailedField(email);
}
if(passw.value === ''){
error.push("Password is required.");
setFirstFailedField(passw);
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
setFirstFailedField(confpassw);
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
setFirstFailedField(confpassw);
}
if(region.value == 0){
error.push("Region is not selected");
setFirstFailedField(region);
}
if(gender.value == 0){
error.push("Gender is not selected");
setFirstFailedField(gender);
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
setFirstFailedField(termss);
}
if(error.length == 0){
alert("Registration Success!");
return true;
}
error.forEach((err) => (console.log(err)));
if (firstFailedField && typeof firstFailedField.focus === 'function') firstFailedField.focus();
return false;
}

I am trying to validate mobile with javaScript but it not working

I have a mobile and I want to check if the mobile number is less then 10 or greater then 13 then I want to show the message
My code:
<input name="mobile" id="mobile" placeholder="+91" class="form-control tboxs" type="text" style="font-family: 'JameelKhushkhatLRegular'">
<button style="width: 100%" type="button" id="submit" value="submit" class="btn-theme-colored btn">SUBMIT <span class="glyphicon glyphicon-send">
<script>
$('#submit').click(function(){
if($('#first_name').val() == '' ){
alert('Name can not be left blank and atleast 4 char long');
return false;
}else if(!$("input[name='redio_gender']:checked").val()){
alert('Please Select Gender');
return false;
}else if($('#multiple').val( ) == '') {
alert('Please Select Age');
return false;
}else if($('#profession').val( ) == '') {
alert('Please Select your Profession');
return false;
}else if($('#taluka').val( ) == '') {
alert('Please Select Taluka');
return false;
}else if($('#village').val( ) == '') {
alert('Please Enter village');
return false;
}else if($('#interest').val( ) == '') {
alert('Please Select Area of Interest');
return false;
}else if($('#masjid').val( ) == '') {
alert('Please Enter Nearest Masjid');
return false;
}else if($('#mobile').val( ) == '' || parseInt($('#mobile').val() < 10 ) || parseInt($('#mobile').val() > 13)) {
alert('Please Enter Valid Mobile Number');
return false;
}else{
$.ajax({
--
--
});
}
});
</script>
In the above code, I validate my code with javascript.
Try this :
var mob = '03311111111';
if( mob.length < 10 || mob.length > 13){
// show error message
}
https://jqueryvalidation.org
$.validator.addMethod(
'phone',
function (value, element, requiredValue) {
var phoneRegexp = /^\+380\d{7,10}$/;
return phoneRegexp.test(value);
},
);
var validator = $('#form_id').validate({
debug: true,
errorClass: 'error-class',
errorElement: 'div',
rules: {
'phone': {
required: true,
phone: true,
minlength: 10,
maxlength: 13
}
},
}
);
You can try the following:
$('#submit').click(function(){
var mobile = $('#mobile').val();
if(mobile.length < 10 || mobile.length > 13) {
//mobile length is less than 10 or greater than 13, show error message
}
});
Your final code would be this:
<script>
$('#submit').click(function(){
var mobile = $('#mobile').val();
if($('#first_name').val() == '' ){
alert('Name can not be left blank and at least 4 char long');
return false;
} else if(!$("input[name='redio_gender']:checked").val()){
alert('Please Select Gender');
return false;
} else if($('#multiple').val( ) == '') {
alert('Please Select Age');
return false;
} else if($('#profession').val( ) == '') {
alert('Please Select your Profession');
return false;
} else if($('#taluka').val( ) == '') {
alert('Please Select Taluka');
return false;
} else if($('#village').val( ) == '') {
alert('Please Enter village');
return false;
} else if($('#interest').val( ) == '') {
alert('Please Select Area of Interest');
return false;
} else if($('#masjid').val( ) == '') {
alert('Please Enter Nearest Masjid');
return false;
} else if(mobile.length < 10 || mobile.length > 13) {
alert('Please Enter Valid Mobile Number');
return false;
} else {
$.ajax({
--
--
});
}
});
</script>
Or you could use html attributes to do that by using minlength and maxlength on the text input and you may even want to switch the input type from text to tel
<input name="mobile" id="mobile" placeholder="+91" class="form-control tboxs" type="tel" style="font-family: 'JameelKhushkhatLRegular'" minlength='10' maxlength='13'>

Jquery form validation coding

My Jquery validation is not working, below is the script coding. I am getting a
Fatal error: Uncaught exception
error and not sure why. I know one of the reasons can be the validation code isnt correct. Is the coding correct or is there errors?
<script type="text/javascript">
$('form#contact').submit(function(e) {
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(jQuery('#form_zip').val());
var isValidYear = /^\d{4}$/.test(jQuery('#gradDate').val());
var year_number = parseInt(jQuery('#gradDate').val());
var isValidEmail = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(jQuery('#form_email').val());
var first_name = jQuery.trim(jQuery('#first_name').val());
var last_name = jQuery.trim(jQuery('#last_name').val());
var form_email = jQuery.trim(jQuery('#form_email').val());
var street = jQuery.trim(jQuery('#street').val());
var city = jQuery.trim(jQuery('#city').val());
var state = jQuery.trim(jQuery('#state').val());
var isValidPhone = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/.test(jQuery('#phone_day').val());
function validZip(zip)
{
if (zip.match(/^[0-9]{5}$/)) {
return true;
}
zip=zip.toUpperCase();
if (zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
return true;
}
if (zip.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
return true;
}
return false;
}
if(!validZip(jQuery('#form_zip').val())){
alert('Please enter a valid Zip Code.');
}
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){
alert('Please enter a valid High School Graduation Year.');
}
else if(!isValidEmail (jQuery('#form_email').val())){
alert('Please enter a valid Email Address.');
}
else if(first_name.length <= 0 || first_name == 'First Name' || (!first_name.match(/[a-zA-Z]/)) || (first_name.match(/[0-9]/))){
alert('Please enter your First Name.');
}
else if(last_name.length <= 0 || last_name == 'Last Name' || (!last_name.match(/[a-zA-Z]/)) || (last_name.match(/[0-9]/))){
alert('Please enter your Last Name.');
}
else if(street.length <= 0 || street == 'Street Address'){
alert('Please enter your Street Address.');
}
else if(city.length <= 0 || city == 'City'){
alert('Please enter your City.');
}
else if(state.length <= 0 || state == 'State'){
alert('Please enter your State by 2 letter abbreviation.');
}
else if(country.length <= 0 || country == 'Other'){
alert('Please enter your Country.');
}
else if(!isValidPhone){
alert('If your phone number is correct, close this box and then Click the button in the form.');
}
else {
$('form#mainform').submit();
}
return false;
}
return false;
}
});
</script>
You have php inside your JavaScript code:
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){

Conditional valdiation of required fields

I have a page where the user enters their address. I want to make city, state and zip code required fields, but here's the catch. Either the user is required to enter both the city and the state OR they are required to enter the zip code. How do I do this javascript?
For now I have
function Form(f) {
for (var n = 0; n < f.elements.length; n++) {
if ((f.elements[n].name).indexOf("zip_code") > -1) {
var zipcode = f.elements[n].value;
if (zipcode.length == "") {
if ((f.elements[n].name).indexOf("cityname") > -1) {
var city = f.elements[n].value;
if (city.length == "") {
alert("Enter City name");
break;
}
}
if ((f.elements[n].name).indexOf("statename") > -1) {
var state = f.elements[n].value;
if (state.length == "") {
alert("Enter State name");
break;
}
}
} else {
//return true; then do something
return false;
}
} else if (zipcode.length == "") {
alert("Enter zipcode");
break;
return false;
}
}
}
Can you please try this?
function Form(f) {
var cityname = document.getElementsByName('cityname')[0].value;
var statename = document.getElementsByName('statename')[0].value;
var zip_code = document.getElementsByName('zip_code')[0].value;
if( (cityname.length==0 && statename.length==0 ) ){
if(zip_code.length==0){
alert("Enter zipcode");
return false;
}
return true;
}else if( (cityname.length==0 || statename.length==0 ) ){
if (cityname.length == 0) {
alert("Enter City name");
return false;
}else if (statename.length == 0) {
alert("Enter State name");
return false;
}
return true;
}
}
Something like this should help
if( zipcode.length){
/* validate zipcode*/
}else{
if( city.length && state.length){
}else{
/* must have city and state*/
}
}
use a variable flag.
flag = 0;
if city and state
make flag as 1
if zip
make flag as 1
if flag==0 then validation failed
else allow to submit form

Javascript Focus Is Not Working on Aspx Page

Hy Guys,
Please Look at the code and Try to Help Out. The function ive written is not working but its RUNNING properly. Its about To set focus on next content on page im using it on an ASPX page. Heres my code Below :
function SetFocusOnSave(CTag,NTag)
{
alert('Running'+CTag+NTag);
var CurrentTag=document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ( (event.keyCode==13)||(event.keyCode==9) )
{
if(CurrentTag.value=="")
{
alert("Please Enter Detail First");
CurrentTag.focus();
}
if(CurrentTag.value!="")
{
event.returnValue=true;
document.getElementById(NextTag).focus();
}
}
}
snametxt.Attributes.Add("onkeypress",
SetFocusOnSave('<%=snametxt.ClientID%>','<%=sdesctxt.ClientID%>');");
have you tried to replace
document.getElementById(NextTag).focus();
with
NextTag.focus();
?
You have to add return false; after you found the false in validation otherwise the flow will continue till end.
Try this function:
function SetFocusOnSave(CTag, NTag) {
alert('Running' + CTag + NTag);
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ((event.keyCode == 13) || (event.keyCode == 9))
{
if (CurrentTag.value == "")
{
alert("Please Enter Detail First");
CurrentTag.focus();
return false;
}
if (CurrentTag.value != "") {
event.returnValue = true;
NextTag.focus();
return false;
}
}
};
Hy Guys Ive Tried A NEW CODE AND Fortunately Its Working Fine Here its my Code
function Navigation(CTag, NTag, Number) {
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
var IsNumber = Number; //Checking if value is number
if (NextTag.disabled == true) {
NextTag.disabled = false;
NextTag.className = "txt";
}
if (event.keyCode == 9) {
CurrentTag.focus();
event.returnvalue = false;
}
if (event.keyCode != 9) {
if (event.keyCode == 13) {
if (IsNumber == "Y") {
if (NextTag.disabled == true) {
NextTag.disabled = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (isNaN(CurrentTag.value)) {
alert("Please Enter A Valid Number");
CurrentTag.value = "";
CurrentTag.focus();
}
}
if (IsNumber == "N") {
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
}
}
}
};
Thanks ya'll !! :)

Categories

Resources