if-statements with && and || in JavaScript - javascript

code:
// if (image.substring(0,7) != "http://" && image.substring(image.length-4) != ".jpg" || ".png")
if (image.substring(0,7) != "http://" && image.substring(image.length-4) != ".jpg" && image.substring(image.length-4) != ".png")
{
// do stuff
}
context: Trying to do an if-statement in JavaScript which uses the && and || operators but it's not working out... Might be due to the fact of how JavaScript returns true-like and false-like values.
EDIT:
full code:
function validateContent(title, rating, link, image, desc)
{
var flag = true;
// add more if-statements
if (title == "")
{
$("#inputTitle").css("background-color", "red");
flag = false;
}
if (rating == 0)
{
$("#selectRating").css("background-color", "red");
flag = false;
}
if (link.substring(0,26) != "http://www.imdb.com/title/")
{
$("#inputLink").css("background-color", "red");
flag = false;
}
// if (image.substring(0,7) != "http://" && image.substring(image.length-4) != ".jpg" || ".png")
//if (image.substring(0,7) != "http://" && image.substring(image.length-4) != ".jpg" && image.substring(image.length-4) != ".png")
//if ((image.substring(0,7) != "http://") && (image.substring(image.length-4) != ".jpg") && (image.substring(image.length-4) != ".png"))
//if (image.substring(0,7) != "http://" && (image.substring(image.length-4) != ".jpg" || image.substr(image.length-4) != ".png"))
//if (/^http:\/\/.*\.(jpg|png)$/.test(image))
if ((image.substring(0,7) != "http://") && ((image.substring(image.length-4) == true) != ".jpg") && ((image.substring(image.length-4) == true) != ".png"))
{
$("#inputImage").css("background-color", "red");
flag = false;
}
return flag;
}
function addContent()
{
var title = $("#inputTitle").val();
var rating = $("#selectRating option:selected").index();
var link = $("#inputLink").val();
var image = $("#inputImage").val();
var desc = $("#textareaDescription").val();
if (validateContent(title, rating, link, image, desc))
{
document.forms.formFilmerPHP.submit();
}
}
function disableOption(pos)
{
$("#selectRating option:eq(" + pos + ")").prop("disabled", true);
}
function validateInputs(inputType)
{
// add more cases
switch(inputType)
{
case "title":
var title = $("#inputTitle").val();
if (title != "")
$("#inputTitle").css("background-color", "white");
break;
case "rating":
var rating = $("#selectRating option:selected").index();
if (rating != 0)
$("#selectRating").css("background-color", "white");
break;
case "link":
var link = $("#inputLink").val();
if (link.substring(0,26) == "http://www.imdb.com/title/")
$("#inputLink").css("background-color", "white");
break;
}
}
function preventDefault()
{
$("#btnAddContent").click(function(event) {event.preventDefault();});
}
function addEventListeners() // QUESTION: when to use anonymous functions and when not to when adding eventlisteners in order to safely attach functions without invoking them?
{
// misc eventlisteners
$("#selectRating").on("focus", function() {disableOption(0);});
// real-time polling of invalid input correction
$("#inputTitle").on("input", function() {validateInputs("title");}); // QUESTION: takes some time before this fires, how to make it fire more quickly?
// ANSWER: use the "oninput" event, previously used onkeydown
$("#selectRating").on("change", function() {validateInputs("rating");});
$("#inputLink").on("input", function() {validateInputs("link");});
// main eventlisteners
$("#btnAddContent").on("click", function() {addContent();});
}
function init()
{
preventDefault();
addEventListeners();
}
/* method used to test during development */
function devtest()
{
}
$(document).ready(init);
EDIT:
var a = image.substring(0,7);
var b = image.substring(image.length-4);
alert(a);
alert(b);
if(a != "http://" && b != ".jpg" && b != ".png")
{
$("#inputImage").css("background-color", "red"); // <-- not being executed
flag = false;
}
return flag;
can't get the $("#inputImage").css("background-color", "red"); statement to execute even though the condition should be evaluated to true.

The below code will be evaluated as true when the first part of the string isn't http:// and the strings last four characters are neither .jpg nor .png
if (image.substring(0,7) != "http://" &&
image.substring(image.length-4) != ".jpg" &&
image.substring(image.length-4) != ".png")

Ok, after a night of good sleep, here's the proper solution:
var imagebegin = image.substring(0,7);
var imageend = image.substring(image.length-4);
if(imagebegin != "http://" || (imageend != ".jpg" && imageend != ".png"))
{
$("#inputImage").css("background-color", "red");
flag = false;
}
return flag;
The validation will occur only if the beginning of the string is "http://" and the end is either ".jpg" or ".png", if either of these conditions aren't met then the if-statement will evaluate to true and the statements within will be executed (including setting the flag to false).

sorry i didnt read your answer proper but i think i gave the right hint anyway
if (image.substring(0,7) != "http://" && image.substring(image.length-4) != ".jpg" && (image.substring(image.length-4) != ".png" || image.substring(image.length-4) != 'or'))

Related

Rewrite script from js to jquery

I have a script that I want to make more bulletproof. At the moment the page breaks because class box-tip is not found. To make this bulletproof and not throw an error how can I rewrote the below code to jquery getting the same results as js
function applyRecommendedSleeveLength(selectedVal) {
if (selectedVal !== undefined) {
var recommendedVal = map[selectedVal.trim()];
var selected = $('.attribute__swatch--selected:first div').text().trim();
if (recommendedVal === null || recommendedVal === undefined) {
selectedVal = $('.attribute__swatch--selected:first div').text().trim();
recommendedVal = map[selectedVal.trim()];
}
if (selected === null || selected === '' || selected === undefined) return;
var recommendedLis = document.querySelectorAll('[class*="attribute__swatch--length-' + recommendedVal + '"] div');
recommendedLis.forEach(function(recommendedLi, i) {
if (recommendedLi !== null && recommendedLi !== undefined) {
recommendedLi.classList.add('showBorder');
$('.box-tip').show();
var currentPosition = $('.showBorder').parent().position().left;
var sleeveRecom = document.getElementsByClassName('box-tip');
var info = sleeveRecom.length ? sleeveRecom[0] : false;
info.style.paddingLeft = currentPosition + -75 + 'px';
}
});
}
}
If you want to check if the div exists, you can use this (using JQuery):
if ( $('.box-tip').length != 0 ){
//do something
}
OR- since you've edited your post- without JQuery:
if ( document.getElementsByClassName('box-tip').length != 0 ){
//do something
}
Just use jQuery for all of this. If the class doesn't exist the jQuery methods won't cause errors
function applyRecommendedSleeveLength() {
$('.box-tip').show().first().css('paddingLeft', (currentPosition - 75) + 'px');
}

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!

How to use javascript validating two text areas

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;
};

Cannot invoke function

See the bottom of this post;
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(aString)
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);
You iterate on sString wich doesn't exist and not on your parameter aString.
Where is sString being declared in your function? Try with aString (or declare var sString = aString) and try again.
Please change function myF(aString) to function myF(sString)
There is a naming mistake. Here is a working copy of your code .
http://jsfiddle.net/hXarY/
You can try using "firebug" to catch such errors if you do not already do.
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(sString) // this should be sString , not aString
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);

modify click event script to be more specific

I have to the following function that I would like to modify so that it only binds the click event to all href's that = /ShoppingCart.asp?ProductCode="whatever" (whatever = whatever is in there") but not if it is specifically /ShoppingCart.asp?ProductCode="GFT". It must also check or convert a gft or Gft to upper case to check for those as well. So basically it has to check for any variation of the case of GFT.
If it finds a "GFT" do not bind the click event.
function sacsoftaddtocart() {
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a[href^='/ShoppingCart.asp?ProductCode']").click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
You can do it using .toUpperCase() and .filter(), like this:
function sacsoftaddtocart (){
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a[href^='/ShoppingCart.asp?ProductCode']").filter(function() {
return this.href.length - this.href.toUpperCase().indexOf('PRODUCTCODE=GFT') != 15;
}).click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
You cant test it in a demo here. The this.href.length - matchPosition == 15 is checking that the ProductCode=GFT is both matched and there's nothing after the "GFT", so a product code like "GFT5" won't match.
using the filter in this post link text
function sacsoftaddtocart() {
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a:regex('href','*/ShoppingCart.asp\?ProductCode=(!?=GFT)*)").click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
or if you don't want to use an exrat plugin:
function sacsoftaddtocart() {
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a['href^='/ShoppingCart.asp?ProductCode']")
.filter(function(){ return !/ProductCode=GTF/.test($(this).attr('href')) };
.click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
Try them and see what happens ;)

Categories