How to fire JS function from area href - javascript

I have a image with a link map like this (generated in PHP):
<map name="map_bc-03" id="map_bc-03">
<area shape="circle" coords="166,28,12" href="#" onClick="changeCount('plus','bc-03');">
<area shape="circle" coords="166,82,11" href="#" onClick="changeCount('minus','bc-03');">
</map>
I am trying to fire a JS function called changeCount(type,product).
JS function purpose is to take the current value of a HTML element (<span>) and add 1 to it (x+1). JS function looks like:
function changeCount(type,product)
{
if ( type == "plus" )
{
$("#count_" + product).val() = $("count_" + product).val() + 1;
}
}
Problem is that 1/ the JS function is not fired with error message "ReferenceError: changeCount is not defined", which I do not understand why as clearly the function is defined....
Problem number 2/ the JS function itself causes a "ReferenceError: Invalid left-hand side expression in postfix operation" error (even though not fired)....
Any help greatly appreciated!

val() is for form elements. For <span> you need html() or text(). try this
function changeCount(type,product){
if ( type == "plus" ){
$("#count_" + product).text(function(index, val){
return parseInt(val)+1;
});
}
}

Use val(value); instead of using val() = value;.
Important thing is,
if your target selector is an input or any form element then use .val().
Otherwise, if it is any of div, span or any other non-form element then use .text() instead of .val(). Because, non-form elements don't have any values.
According to your question, you are targetting a <span>. So, I think you have to use .text().
function changeCount(type,product)
{
if ( type == "plus" )
{
$('#count_'+ product).text(Number($('#count_' + product).text()) + 1);
}
}

It should be
$("#count_" + product).val() = parseInt($("#count_" + product).val()) + 1;
"#" is missing while getting value and parseInt should be used.

Related

Removing Class Using Jquery According to Parameter Value

I have the following button link:
×
And the following js:
function reEnableBtn(prodId) {
alert(prodId);
};
Until now all good, on click of the link I get an alert with the content: 573 as expected.
Next thing I want to do is with the following html:
<a href="/new-page/?add-to-cart=573" class="button product_type_simple add_to_cart_button ajax_add_to_cart added" data-product_id="573">
<i class="fa fa-shopping-cart finished disabled-button"></i>
</a>
Within the JS I want to add a removeClass function which removes the classes 'finished' and 'disabled-button' from the <i> where the data-product_id of the parent <a> matches the value of prodId within the JS function (because I have other links with same structure but different data-product_id).
How do I do this?
You can
1) use attribute equal selector to target anchor element with same data product id
2) find element i in above anchor element
3) use removeClass to remove multiple classes from it
function reEnableBtn(prodId) {
$('[data-product_id=' + prodId + '] i').removeClass("finished disabled-button");
}
function reEnableBtn(prodId) {
$("a[data-product_id='"+prodId+"']").find("i").removeClass("finished disabled-button");
};
Use this simple script.
Use this code
jQuery(function($){
var s = $("body").find('[data-product_id=573]');
s.on("click", function(e){
var i = $(this).find('i');
if (i.hasClass('finished'))
i.removeClass('finished');
if (i.hasClass('disabled-button'))
i.removeClass('disabled-button');
alert("The classes was removed.");
return false; // this is for disabling anchor tag href
});
})
jsfiddle
If you have any other question feel free to ask in comments.

jQuery syntax error, unrecognised expression

syntax error, unrecognised expression: #2015-11-30|1112|1
I have an anchor tag with an Id of '2015-11-30|1112|1' that I would like to apply a class to. I am doing the same method for on a '' and this works, but I am getting syntax errors with the following. Can anyone explain the syntax error?
$(document).ready(function() {
$("#tbl_calendar").on("click", "a", null, clickAppointment);
});
function clickAppointment(eventData)
{
//Get the Id of the appointment that has been clicked:
currentAppointment = $(this).attr('id');
//alert('clicked' + '#'+currentAppointment)
$('#'+currentAppointment).addClass('selected');
}
You should escape the special chracters in your id using \\, check example bellow.
Hope this helps.
console.log( $("#2015-11-30\\|1112\\|1").text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="2015-11-30|1112|1">Div text example</div>
For your current code to work, you don't have to use that id selector since you already have the reference of the object inside the event function.
$(document).ready(function() {
$("#tbl_calendar").on("click", "a", clickAppointment);
function clickAppointment(eventData) {
//"this" will have a reference to the clicked object
$(this).addClass("selected");
}
});
Not sure about your HTML, but considering something similar to the below one.
<ul id="tbl_calendar">
<li>
<a id="2015-11-30|1112|1">Click</a>
</li>
</ul>
Working sample

How do I execute a javascript function from an HTML element and send that elements name without use its name specifically?

If there is an answer to this question out there I can not find it.
I have the following function in JavaScript and need to be able to reuse it over and over.
function ParentService_load(_Object) {
$(_Object.parent.parent).jqxDropDownButton({
...
});
$(_Object).jqxGrid({
...
});
$(_Object).bind('rowselect', function(event) {
...
var row = $(_Object).jqxGrid('getrowdata', args.rowindex);
...
$(_Object.parent.parent).jqxDropDownButton('setContent', dropDownContent);
if (row["servicename"].toString().toLowerCase() === "new") {
$(_Object.parent.parent).jqxDropDownButton('close');
...
}
});
}
<div id="jqxParentServiceDropdownButton">
<div id='jqxParentServiceDropdownWidget' style="font-size: 13px; font-family: Verdana; float: left;">
<div id="jqxParentServiceDropdownGrid" onload="ParentService_load(this);"></div>
</div>
</div>
I haven't found a definitive way to call a javascript or jquery function from an element and have that function use that elements' name, etc... So how would I accomplish this?
If by "name" you mean id, then within your function, you can access that as _Object.id. Because you're passing this in your onload=... (but see below), that's a reference to the element on which the event occurred. Within the function, you're receiving that argument as _Object, so you can use the properties on _Object to access information about the element, including its id.
But note that div elements don't have a load event. Also, div elements don't have a parent property; you may be thinking of parentNode.
I'm not completely sure what you are asking, so here are a bunch of examples about returning values embedded in the HTML from a function;
$(document).ready(function(){
$(".lw").click(function() {
alert("Class:" + $(this).attr("class") +
"\nID:" + $(this).attr("id") +
"\nData:" + $(this).data("test") +
"\nName:" + $(this).attr("name") +
"\nTagname:" + $(this).prop("tagName"));
alert($(this).parent().prop("tagName"));
});
});
http://liveweave.com/CZSYqW
Clicking on either of the <p> elements returns a different value in an alert box.

How to find div that has matching data attr then remove class

Here is my attempt that doesn't seem to be working:
$('container').find("[data-slider='" + one + "']").removeClass('hidden');
Here is the full function that is wrapped in a document. ready function
$("#service-icon").on('click', function(){
var $this = $(this);
event.preventDefault();
$this.addClass('ease-transition').toggleClass('active-slider-btn');
$(".page-wrapper").find("[data-slider='" + one + "']").toggleClass("hidden");
});
The error that I am getting is:
"Uncaught ReferenceError: one is not defined"
Things to check:
Is `container` a class or id? If so you'll need to add a `.` or `#` respectively
That the expression in the `.find()` function returns what you're expecting
Can you post a link to a JSFiddle or something?
I have a working example here that is similar to your situation.
HTML
<div class="container">
<div data-slider="1" class="hidden">1</div>
<div data-slider="2">2</div>
</div>
<button id="show-1">show slider 1</button>
CSS
.hidden {
display: none;
}
JavaScript
var one = "1";
$("#show-1").click(function(e){
$(".container").find("[data-slider='" + one + "']").removeClass("hidden");
});
Something like this has to work:
$('.page-wrapper').find("[data-slider='" + one + "']").removeClass('hidden');
See it working here: http://jsfiddle.net/sNp7x/2/
Maybe the data attribute is set via javascript as well, so you have to be aware of the timing?!

jQuery, selecting just number from id like "article-23"

All right, I have a div tag which got a class="blog-post" and id like id="article-23" (where "23" could be any number, as it is id of blog post in a database). I need to somehow get just a number from that id and than apply some rules to that div tag. So say:
if number from id % 2 == 0 {
set text colour black to associated div tag with class of blog-post
} else {
set text colour white to associated div tag with class of blog-post
}
Thats just a "pseudo" code to show logic that I wan't to apply dependent if number from id is even or odd, but the question remains same, how do I just get number from id like "article-23" ?
As simple as
var number = "article-23".match(/\d+/)[0];
But you have to be sure that any digit exists in the string, otherwise you'd get a error.
You can actually apply rules via function, which makes this the cleanest solution (in my opinion):
$(".blog-post").css('color', function () {
return +this.id.replace('article-', '') % 2 ? 'blue' : 'red';
});
http://jsfiddle.net/ExplosionPIlls/Jrc5u/
Try this:
$('.blog-post[id^="article-"]').each(function () {
if (parseInt(this.id.replace('article-', '')) % 2 === 0) {
$('#' + this.id).css('color', 'black');
} else {
$('#' + this.id).css('color', 'white');
}
});
jsFiddle Demo
As an alternative, HTML5 supports these things called "data attributes", which are specifically meant for attaching data to your DOM without abusing things like the "class" or "id" attributes. jQuery provides a handy .data method for reading these attributes in a more obvious way.
You can add your own numeric ID attribute using something like "data-id":
<div class="blog-post" data-id="23" />
$("#blog-post").each(function () {
console.log($(this).data("id")); // Look up the data-id attribute
});
If I'm understanding correctly, you want the number after the hyphen of the id tag of your .blog-post class.
var article = $(".blog-post").attr('id'); //get the id
var article = article.split("-"); // split it on hyphens
return article = article[article.length-1]; // return the last element

Categories

Resources