modify click event script to be more specific - javascript

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

Related

How could I add the ability to navigate onclick to the code?

I am trying to add links eg <a> to the code from here, it is a treeview using JS and JSON.
It fully works and the children are already <a></a> with href="#", I have replaced the following code, to grab a href : "example.com" attribute from the JSON and set it to the href, which works. I have also made a change to the onclick, but that only does something if you click twice :/
I would like for it to instantly href, and not when you click twice on the child.
class SimpleTree extends Emitter {
constructor(parent, properties = {}) {
super();
// do not toggle with click
parent.addEventListener('click', e => {
// e.clientX to prevent stopping Enter key
// e.detail to prevent dbl-click
// e.offsetX to allow plus and minus clicking
if (e && e.clientX && e.detail === 1 && e.offsetX >= 0) {
if (parent.href != null) {
window.location.href = parent.href;
}
return e.preventDefault();
}
const active = this.active();
if (active && active.dataset.type === SimpleTree.FILE) {
e.preventDefault();
this.emit('action', active);
if (properties['no-focus-on-action'] === true) {
window.clearTimeout(this.id);
}
}
});
[...]
class SelectTree extends AsyncTree {
constructor(parent, options = {}) {
super(parent, options);
/* multiple clicks outside of elements */
parent.addEventListener('click', e => {
if (e.target.href !== '#' || e.target.href !== 'javascript:void(0)' || e.target.href !== undefined || e.target.href !== '' || e.target.href !== null) {
window.open(href, '_blank');
}
if (e.detail > 1) {
const active = this.active();
if (active && active !== e.target) {
if (e.target.tagName === 'A' || e.target.tagName === 'SUMMARY') {
return this.select(e.target, 'click');
}
}
if (active) {
this.focus(active);
}
}
});
The simplest answer to this, add an eventlistener for the <a> element and navigate if it's not empty, null, etc.
Solution below is using Jquery.
$("a").click(function(e) {
e.preventDefault();
var href = $(this).attr("href");
if (href !== '#' || href !== 'javascript:void(0)' || href !== undefined || href !== '' || href !== null) {
window.open(href, '_blank');
}
});

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

Page Middle Click Listener

I need to pop-up alert when I use Middle Click and it must don't pop-up if I click it on a link but on any other element of page (or just on empty space).
var test = {
pageMiddleClickListener : function(e) {
if(e.which === 2) {
//if (!gContextMenu.onLink) {
alert('ok');
//}
}
}
window.addEventListener("click",test.pageMiddleClickListener,false);
Alert show-ups when I use Middle Click on a link, but I need to prevent this behavior to links
I need something like "!gContextMenu.onLink" but not for context menu (without)
There are multiple ways that you can test for the target of the click being a link. One way would be to check to see if the Element.tagName is A, another would be to test for the href property. As it turns out is is also necessary to test to see if any of the target's parentNodes are links.
var test = {
pageMiddleClickListener : function(e) {
if(e.button === 1) {
if (!test.isLinkOrAParentIsLink(e.target)) {
e.view.alert('ok');
}
}
},
isLinkOrAParentIsLink : function(el) {
if (el.tagName === "A") {
return true;
} //else
let parent= el.parentNode;
while (parent !== null && typeof parent.tagName !== "undefined") {
if (parent.tagName === "A") {
return true;
} //else
parent= parent.parentNode;
}
return false;
}
}
window.addEventListener("click",test.pageMiddleClickListener,false);
or
isLinkOrAParentIsLink : function(el) {
if (el.hasAttribute("href")) {
return true;
} //else
let parent= el.parentNode;
while (parent !== null && typeof parent.tagName !== "undefined") {
if (parent.hasAttribute("href")) {
return true;
} //else
parent= parent.parentNode;
}
return false;
}
Note: I changed e.which to e.button as that is what is in the specification for click events and MouseEvent.which is non-standard. Note this also required testing for e.button === 1 instead of 2.
You can check if you have clicked an <a> with the prop method.
$(this).prop("tagName") == "A"
In your event listener:
var test = {
pageMiddleClickListener : function(e) {
if(e.which === 2) {
// not an <a> ?
if ($(this).prop("tagName") !== "A") {
alert('ok');
}
}
}
window.addEventListener("click",test.pageMiddleClickListener,false);

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!

if-statements with && and || in 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'))

Categories