How to use javascript validating two text areas - javascript

The below works, how would i go about including a 2nd "txtArea2"? I've tried joining a & (document.getElementById("txtArea2").value == '') but doesnt work. I'm new to js syntax if someone could help.
if(document.getElementById("txtArea1").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};

I'm not sure if I understand your question correctly but you probably want to compare them with || (OR) operator, so if txtArea1 or txtArea2 is empty then the validation shall not pass. That means both textareas will be required fields.
if (document.getElementById("txtArea1").value == '' || document.getElementById("txtArea2").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};

Double && specifies the AND condition.
if (document.getElementById("txtArea1").value == '' && document.getElementById("txtArea2").value == '')

If you want to treat both separately, you'll have to use two separate if statements as well. (I outsourced the textareas into variables for readability)
var txtarea1 = document.getElementById("txtArea1");
var txtarea2 = document.getElementById("txtArea2");
if(txtarea1.value == '')
{
alert("debug");
txtarea1.style.display = "none";
return false;
};
if(txtarea2.value == '')
{
alert("debug");
txtarea2.style.display = "none";
return false;
};
If you want to do one thing if either of them (1 or 2) is empty, try this:
if(txtarea1.value == '' || txtarea2.value == '')
{
alert("debug");
txtarea1.style.display ="none";
txtarea2.style.display ="none";
return false;
};

var t1 = document.getElementById("txtArea1").value;
var t2 = document.getElementById("txtArea2").value;
if( t1 == '' || t2 == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};

Related

Validating numeric values using JavaScript

I have the following code. It works fine for blank fields, but it doesn't catch the other numeric exceptions. What am I doing wrong?
function validateForm() {
var a = document.forms["Form"]["percentage"].value;
var b = document.forms["Form"]["minutes"].value;
if (a == null || b == null || a == "" || b == "") {
alert("Please Fill All Required Field");
return false;
} else if (isNan(a) == true || isNan(b) == true) {
alert("Please enter valid numeric values");
return false;
} else if (parseInt(a) > 100) {
alert("Percentage can't exceed 100");
return false;
} else if (parseInt(b) < 0 || parseInt(a) < 0) {
alert("Values can't be negative");
return false;
}
}
Change this line:
else if((isNan(a)==true) ||(isNan(b)==true)){
to this:
else if (isNaN(a) || isNaN(b)) {
as the function is named #isNaN(). Using == true in conditionals is quite redundant, so I removed them.
I have also made a fiddle for you. It contains the fixed code, and it is working well.

onclick event of input button type is not working in chrome for some users

Here is my html code
<input type="button" name="Button" value=" Next " runat="server" id="btnNext" class="button" onclick ="if (!EmptyCheck()) return false;" />
and
function EmptyCheck() {
debugger;
var txtRSI = $("input[id$=txtRSI]").val();
var txtQFix = $("input[id$=txtQFix]").val();
var txtPassPercent = $("input[id$=txtPassPercent]").val();
var txtDefRejRate = $("input[id$=txtDefRejRate]").val();
var txtBuildVar = $("input[id$=txtBuildVar]").val();
var txtEffortVar = $("input[id$=txtEffortVar]").val();
var txtScheVar = $("input[id$=txtScheVar]").val();
var txtDeliMet = $("input[id$=txtDeliMet]").val();
var txtBudgetVar = $("input[id$=txtBudgetVar]").val();
var ddlOwner = $('select[id$="ddlOwner"]').val();
var ddlAccount = $('select[id$="ddlAccount"]').val();
var ddlProgramme = $('select[id$="ddlProgramme"]').val();
var ddlMonth = $('select[id$="ddlMonth"]').val();
var ddlYear = $('select[id$="ddlYear"]').val();
if ((txtRSI == "") || (txtQFix == "") || (txtPassPercent == "") || (txtDefRejRate == "") || (txtBuildVar == "") || (txtEffortVar == "") || (txtScheVar == "") ||
(txtDeliMet == "") || (txtBudgetVar == "") || (ddlOwner == "-1") || (ddlAccount == null) || (ddlProgramme == null) || (ddlMonth == 0) || (ddlAccount == "-1")
|| (ddlProgramme == "-1") || (ddlYear == 0)) {
alert("All fields are Mandatory");
return false;
}
else {
return true;
}
}
This is javascript method works fine in my browser.whereas the same is not working for others.
couldnt find why this happens..
inline code is not supported in chrome..i saw this in several posts..but it works for me..but not for others.. can somebody give an alternate solution to this???
also i have server side implememnted...wanted to achieve both.
i have tried like this also
getelementbyid('btnid').addeventlistener('click', function()){}
Have you tried just using the function? If your function returns a boolean value, why are you checking it to then return another boolean value? Just return EmptyCheck()
However, I will say that using the inline functions in my experience has been a poor decision. The functions can be managed/called more efficiently from an external jscript file. Here's an example:
Step 1
In your .js file, create a generic (but not anonymous) function for each page. For examples, we'll work in a hypothetical "Home" page.
function HomePageEvents() {
}
Step 2
Now we have a function that will serve as a container for your home page's javascript . . . But of course we need to run the function at some point. Well, we want to make sure the function is run once the document is finished loading of course, since we'll likely need to reference elements of the rendered page. So let's go ahead and create an anonymous function that will trigger this container function (aka, HomePageEvents() function). In your Home page, add the following:
<script type="text/javascript">
$(document).ready({function(){
HomePageEvents();
});
</script>
Step 3
What was it we were trying to do again? Oh, right! We want to add a click event for your button. Well, we can first start by creating the function for the click event. Now, I'm assuming your button has some kind of innate functionality, and all we are doing here is validating the button. If this is indeed the case, all we need to do is return a true or false indicating whether the event should continue.
function HomePageEvents() {
// Function to perform our validation.
function validateNext() {
if ((txtRSI == "") || (txtQFix == "") || (txtPassPercent == "") || (txtDefRejRate == "") || (txtBuildVar == "") || (txtEffortVar == "") || (txtScheVar == "") || (txtDeliMet == "") || (txtBudgetVar == "") || (ddlOwner == "-1") || (ddlAccount == null) || (ddlProgramme == null) || (ddlMonth == 0) || (ddlAccount == "-1") || (ddlProgramme == "-1") || (ddlYear == 0)) {
alert("All fields are Mandatory");
return false;
} else {
return true;
}
};
};
Step 4
Now that we have the validation function ready, we just need to add the function as a click event for our btnNext button.
function HomePageEvents() {
// Add function to btnNext button . . .
$('#btnNext').on('click', function(){
validateNext();
});
// Function to perform our validation.
function validateNext() {
if ((txtRSI == "") || (txtQFix == "") || (txtPassPercent == "") || (txtDefRejRate == "") || (txtBuildVar == "") || (txtEffortVar == "") || (txtScheVar == "") || (txtDeliMet == "") || (txtBudgetVar == "") || (ddlOwner == "-1") || (ddlAccount == null) || (ddlProgramme == null) || (ddlMonth == 0) || (ddlAccount == "-1") || (ddlProgramme == "-1") || (ddlYear == 0)) {
alert("All fields are Mandatory");
return false;
} else {
return true;
}
};
};
The end result is you get (1) all your javascript in a single file--which is better for caching, (2) the file is easily manageable, and (3) you can isolate code for each page.
As an alternate you can use jQuery click event. Read documentation from here .
$('.button').click(function(){ // button is the class name of your input control
// Your EmptyCheck Logic goes here.
});
Note that there are other solutions as well to bind click event using jQuery like .on().
$('.button').on('click', function() {
// Your EmptyCheck Logic goes here.
});
Hope this helps!

What is the right way to check a input form field value(empty and null..) using jQuery?

I have some input filed into a form. I am trying to check the empty and null of those value.
My js code as:
$(function(){
$('#submit').click(function(){
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
var path = '/admin/exam_schedule';
if (cid ==''||cid==null || sid==''||cid==null || d==''||d==null || t==''||t==null) {
alert('Input all data fields');
}
else{
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});
});
But the problem of this code are: When I give space into the input field then it takes the space as input.But, I want to validate all of the possible way, so that I can take real data as input.
val() will only return null for a select element, everything else should return '', therefore, if you aren't using a select element then str != '' or str.length > 0 should be sufficient.
If you are using a select element then you check whethre the value is assigned first e.g. str && str != '' or str && str.length > 0 (or alternatively you default null to '' for consistency).
If you want to exclude whitespace-only strings then use trim() during validation.
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
if (cid.trim() == '' || sid.trim() == '' || d.trim() == '' || t.trim() == '') {
// data invalid
}
else {
// data valid
}
Try,
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
DEMO
Improvised version,
var condition = false;
$('#CTID,#sbj,#bdate,#time').each(function(){
if($.trim(this.value) === "") {
condition = true;
return false;
}
})
if(condition){ alert('Input all data fields'); }
Full code would be,
$('#submit').click(function(e){
e.preventDefalut();
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
else {
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});

Trouble with basic javascript

I'm trying to do some extremely simple form validation, my current problem is that my window.onload function doesn't call in the function I specify.
When I watch the flow of logic with firebug it just skips to the end of the code.
Here is an example of my code:
window.onload = init;
function init() {
var regForm = document.getElementById("registerform");
regForm.onsubmit = validatepostcode();
}
function validatepostcode() {
var postCode = document.getElementById("postcode");
var postCodeStr = postCode.charAt(0);
var state = document.getElementById("state");
var result = true;
if (postCodeStr == 3 || 8 && state == "Vic") {
result = true;
} else if (postCodeStr == (1 || 2) && state == "NSW") {
result = true;
} else if (postCodeStr == (4 || 9) && state == "QLD") {
result = true;
} else if (postCodeStr == 0 && state == "NT" || state == "ACT") {
result = true;
} else if (postCodeStr == 6 && state == "WA") {
result = true;
} else if (postCodeStr == 5 && state == "SA") {
result = true;
} else if (postCodeStr == 7 && state == "TAS") {
result = true;
} else
result = false;
if (result = false) {
alert("Your postcode does not match your state")
}
}
Five problems:
In init, you have this:
regForm.onsubmit = validatepostcode();
That calls validatepostcode and puts its return value in onsubmit. You probably meant to put the function itself it, not its return value in. Remove the parentheses:
regForm.onsubmit = validatepostcode;
In validatepostcode, you're fetching elements like this:
var postCode = document.getElementById("postcode");
…but then try to use them as values, like this:
var postCodeStr = postCode.charAt(0);
But an element and the current value of that element are not the same thing. More likely, you meant to retrieve the value on the first line:
var postCode = document.getElementById("postcode").value;
Same goes for state.
In validatepostcode, you have lines like this:
} else if (postCodeStr == (1 || 2) && state == "NSW") {
Specifically, 1 || 2 won't work like that. It will look at them like booleans and say, “one or two? well, they're both truthy…true it is!” and you'll essentially be doing
} else if (postCodeStr == true && state == "NSW") {
(Actually, it uses 1, not true, since the first operand was truthy, but that's not the important point here.)
Instead of using that abbreviated notation, you'll have to write it out longhand:
} else if ((postCodeStr == 1 || postCodeStr == 2) && state == "NSW") {
You mixed up = and == here:
if(result=false){
= will set result to false and leave the condition always false. Change it to == to test equality:
if(result==false){
You probably meant to return result at the end to prevent the form from being submitted when there is a validation error. With the other changes applied, you'd get an alert if there was a validation error, but it'd go on submitting anyway. As such, add a return result at the end of the validatepostcode function.

Regex to check if input matches a landline area code

In Australia we have area codes 02,03,07,08 however when i try to put 04 into the field it allows the form to be submitted when it should not allow it.
I am wondering if anyone knows how to fix this please.
function phtest(){
OTHERRegex = /^[07]{2}[0-9]{8}$/
NSWRegex = /^[02]{2}[0-9]{8}$/
VICRegex = /^[03]{2}[0-9]{8}$/
WARegex = /^[08]{2}[0-9]{8}$/
if (document.getElementById('phone2').value != '' || NSWRegex.test(document.getElementById('phone2').value)
|| VICRegex.test(document.getElementById('phone2').value)
|| WARegex.test(document.getElementById('phone2').value)
|| OTHERRegex.test(document.getElementById('phone2').value))
alert('Please input correct Landline Phone Field\n');
return false;
else
return true;
}
When you don't enclose the if / else in curlybraces, you close it with semicolons, so the alert closes the if, and the return false does nothing.
function phtest(){
var elem = document.getElementById('phone2');
if (/^[(02|03|07|08)]{2}[0-9]{8}$/.test(elem.value)) {
return true;
}else{
alert('Please input correct Landline Phone Field\n');
return false;
}
}
FIDDLE
You have missed curly braces in your if statement. So, you will get false anyway.
if (document.getElementById('phone2').value != '' || NSWRegex.test(document.getElementById('phone2').value)
|| VICRegex.test(document.getElementById('phone2').value)
|| WARegex.test(document.getElementById('phone2').value)
|| OTHERRegex.test(document.getElementById('phone2').value))
{
^^^
alert('Please input correct Landline Phone Field\n');
return false;
}
^^^
else
{
return true;
}
I have modified your code, you can try it:
function testPattern(phone){
var OTHERRegex = /^[07]{2}[0-9]{8}$/,
NSWRegex = /^[02]{2}[0-9]{8}$/,
VICRegex = /^[03]{2}[0-9]{8}$/,
WARegex = /^[08]{2}[0-9]{8}$/;
return (VICRegex.test(phone)
|| WARegex.test(phone)
|| NSWRegex.test(phone)
|| OTHERRegex.test(phone));
}
function phtest(){
var phone = document.getElementById('phone2').value;
var isValid = (phone
&& phone.length > 0
&& testPattern(phone));
if (!isValid) alert('Please input correct Landline Phone Field\n');
return isValid;
}
Try this. It is good for almost all formats - +61255555555, 0255555555, +61 2 5555 5555, +61-2-5555-5555
function validateLandline(numberStr) {
var landlineRegex = /^((00|\+)61|0)(2|3|7|8)\d{8}$/;
return landlineRegex .test(numberStr.replace(/ /g,'').replace(/-/g,''));
}
validateLandline('+61255555555') // true
validateLandline('+61-2-5555-5555') // true
validateLandline('+61 2 5555 5555') // true
validateLandline('0255555555') // true
validateLandline('02 55555555') // true
validateLandline('+61455555555') // false
validateLandline('0455555555') // false and so on

Categories