Removing Class Using Jquery According to Parameter Value - javascript

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.

Related

Remove html element with javascript

When I press the Submit button if any error is generated then code create a span element.
My question is how I can clear the old error from the error container element, or if not possible then please sum up the errors.
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
I tried remove() but I cannot do it.
Thanks
you can remove the span with next().
next() finds the next sibling to the input field you are referring to.
it will give you the span:
el.next().remove();
you can use a class on the span f.e. class="validation-span"
el.next(".validation-span").remove();
this will make sure you only remove the span and no other element if existent :)
Add an span element after the input and set its HTML each time instead of using .after.
<input name="yourName">
<span class="errors"></span>
<script>
$(document).find('[name="'+i+'"] + .errors')
.html('<span style="color: red;">'+error[0]+'</span>');
</script>
I updated the both way you want, please pick which is more suitable to you
function logErrorCleanSpan(errorMessage){
$('#errorContainer').text(errorMessage);
}
logErrorCleanSpan("Hello");
logErrorCleanSpan("Jarvis");
function logErrorAppendSpan(errorMessage){
var span = $("<span>"+errorMessage+"</span>");
$('#errorContainerSpanAppend').append(span);
}
logErrorAppendSpan("1. Hello ");
logErrorAppendSpan("2. Jarvis ");
#errorContainerSpanAppend{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Append Error and clean the previous error<h3>
<span id="errorContainer"></span>
<h3>Append Error and keep the older one<h3>
<span id="errorContainerSpanAppend"></span>
Assign a id with index to span after each click remove previous span using id
Use jquery remove
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span id="error'+i+'" style="color: red;">'+error[0]+'</span>'));
if($(document).find('span#error+i - 1+')) {
$( "span#error+i - 1+" ).remove();
}
});
this is just an example code not correct code.

jQuery disable the previous span and the next span, on click span

I'm having trouble applying class to the previous element or the next element.
<a href="#"><span class="glyphicon glyphicon-thumbs-up up"></span>
<a href="#"><span class="glyphicon glyphicon-thumbs-down down"></span>
I want to disable the second span, when I click the first span and vice versa.
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(this).parent().nextAll('a.comment-vote-down');
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(this).parent().prevAll('a.comment-vote-up');
up.removeClass('disable-link').addClass('disable-link');
}
});
example on jsfiddle
You try to find class .comment-vote-down that doesn't exist in your HTML code
https://jsfiddle.net/xnovq390/4/
try this:
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(".down");
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(".up");
up.removeClass('disable-link').addClass('disable-link');
}
});
It's because you don't have an a with a class of .comment-vote-down, or comment-vote-up.
Either take that part out of your nextAll selection:
.nextAll('a');
https://jsfiddle.net/xnovq390/1/
or, add in the class to your HTML:
<a href="#" class="comment-vote-up">
https://jsfiddle.net/xnovq390/3/
If the .up element is always the previous element from the .down one, you can simply do:
$(document).on('click', '.up, .down', function(e) {
e.preventDefault();
if ($(this).hasClass('up')) $(this).next().addClass('disable-link');
else $(this).prev().addClass('disable-link');
}
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
$(this).addClass('disable-link');
$('span.down').removeClass('disable-link');
}else if($(this).hasClass('down')){
$(this).addClass('disable-link');
$('span.up').removeClass('disable-link');
}
});
As the other answers already stated, there is no spoon element with .comment-vote-down class.
But additionally to make life easier, you could buffer the 2 elements, bind the click to them and disable the ones not clicked, reducing the code to
var btns = $('.up, .down');
btns.click(function(){
btns.not(this).addClass('disable-link');
});
fiddle
If you'd want to disable the containing a, the 'other's parent could be obtained by chaining parent() : btns.not(this).parent().addClass('disable-link'); ( or .closest('a') if there is a deeper hierarchy)

Getting the class name which triggered the event

I have a tag with below HTML :
<a href='#' class='create_account singup header-icon'>Create Account</a>
I am using a common click handler of the 3 button with Class create_account , member_login , product_service
Now inside the handler , I want the class name which triggered the click event, in best possible way (with minimal condition)
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class'));
/**
In case , user click on button with class `create_account` , I get in console
`create_account singup header-icon` , which is correct,
**but I want `create_account` i.e is the class which triggered the Click event**
*/
});
I would just create a separate click handler for each class, like so:
// Define all the required classes in an array...
var selectors = ["create_account", "member_login", "product_services"];
// Iterate over the array
$.each(selectors, function(index, selector) {
// Attach a new click handler per-class. This could be a shared function
$("."+selector).click(function(e) {
e.preventDefault();
alert(selector); // Logs individual class
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="create_account" href="">Create</a>
<a class="member_login" href="">Login</a>
<a class="product_services" href="">Services</a>
If you want you can abstract the shared logic out into another function, like this Fiddle
Alternative Approach with Data Attributes
<a href='#' class='action-trigger' data-action='Creation'>Create Account</a>
$('.action-trigger').click(function(){
console.log($(this).data('action'));
});
Retrieve Class Based on it Being First
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class').split(' ')[0]);
});
Alternative Approach with Parameters
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account').click(function(){
MyFunction('CreateAccount');
});
$('.member_login').click(function(){
MyFunction('MemberLogin');
});
function MyFunction(type)
{
console.log(type);
}
$(this).attr('class');
This will always return the list of classes that the element has. You can actually include an 'id' attribute to the element to access it when clicked.
<a href='#' class='but' id='create_account'>Button 1</a>
$('.but').click(function(){
alert($(this).attr('id'));
});
Demo: https://jsfiddle.net/dinesh_feder/2uq5h03j/
There are good solutions put forth using an array of selectors, but here is a solution using the strings of the selectors and the classes of the triggering element.
It's unfortunate that .selector was removed in jQuery 1.9 or else this would be even simpler. The approach is to get the original selector as an array and intersect it with the array of classes on the triggering element. The result will be the class that triggered the event. Consider this example:
[".create_account", ".member_login", ".product_services"]
[".class1", ".class2", ".create_account"]
Their intersection is:
[".create_account"]
Here is working code:
var selector = '.create_account, .member_login, .product_services';
$(selector).on("click", { sel: selector.split(", ") }, function(e){
var classArr = $(this).attr("class").split(" ").map(function(a){ return "."+a; });
var intersect = $.map(e.data.sel,function(a){return $.inArray(a, classArr) < 0 ? null : a;});
alert(intersect[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1 class2 create_account">class1 class2 create_account</button><br/><button class="class3 product_services class4">class3 product_services class4</button><br/><button class="class5 class6 member_login">class5 class6 member_login</button>
I would add the classes into an array and then iterate to it to see if our target has one of those into its class attribute :
var classes = ['.create_account' , '.member_login' , '.product_services'];
$(classes.join()).click(function(){
for(var i=0; i<classes.length; i++){
var classPos = $(this).attr('class').indexOf(classes[i].substring(1));
if(classPos>-1)
$('#result').html(classes[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='create_account singup header-icon'>Create Account</a>
<a href='#' class='member_login singup header-icon'>Member Login</a>
<a href='#' class='singup header-icon product_services'>product services</a>
<p id="result"></p>
Well, to take back the Manish Jangir .... example, if you have to retrieve only the concerned class, then why don't you test it? you use jquery so you can use "hasClass" don't you?
$('.create_account , .member_login , .product_services').click(function(e){
if($(this).hasClass('create_account')){
alert('create_account');
}
if($(this).hasClass('member_login')){
alert('member_login');
}
if($(this).hasClass('product_services')){
alert('product_services');
}
});
This is maybe not a "perfect solution" but it fits your requirements...^^
You can also do it this way with jquery :
$('body').on('click','.create_account',function(event){
alert('.create_account');
//do your stuff
});
$('body').on('click','.member_login',function(event){
//...
});
$('body').on('click','.product_services',function(event){
//...
});
this way you just have to add a block if you add a new class that needs an event on click on it... I do not see any more "specific" answer to your question... I always used to do it this way since the way I handle the event on classes can be really different...

Show/Hide Content without reloading the page

I have three content boxes that i want to show and hide using controls.
The HTML is as follows:
<div id="leermat1">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
<div id="leermat2">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
<div id="leermat3">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
I have the two anchors pag-next and pag-prev that will control which of the content divs should be visible at any given point:
I want to write jquery such as, when #leermat1 'pag-next' is clicked, it hides #leermat1 and shows #leermat2. Then when #leermat1 is hidden and #leermat2 shows, when '.pag-next' is clicked, it hides #leermat2, and shows #leermat3.
Also the 'pag-prev' should work the same way.
I started with the following but dont know where to go from here.
$(document).ready(function() {
$('.pag-next').on('click',function() {
$('#leermat1').addClass('hide');
$('#leermat2').addClass('show');
});
});
One more thing is that the '.pag-next' should stop functioning after it has shown #leermat3.
You need this
$('[class^=pag-]').click(function() {
var elem = $('[id^=leermat]').filter(":visible"); // take the visible element
var num = Number(elem[0].id.match(/\d+$/)[0]); // take the number from it
var step = $(this).is('.pag-next') ? 1 : -1; // ternary operator
$('#leermat'+ (num + step)).show(); // show next or back
elem.hide(); // hide the visible element
});
Looks like in your anchor tag you have not given it a class.
Next
You then go on in your JQuery code to add a click function to a class which does not exist.
$('.pag-next').on('click',function()
Try adding class="pag-next" to your anchor tag.
This is what worked for me through a little trial and error. Although I am not sure if this is the most efficient solution.
$('#leermat1 .pag-next').on('click',function(){
$('#leermat1').addClass('hide');
$('#leermat1').removeClass('show');
$('#leermat3').addClass('hide');
$('#leermat3').remove('show');
$('#leermat2').addClass('show');
});
$('#leermat2 .pag-next').on('click',function(){
$('#leermat1').removeClass('show');
$('#leermat2').addClass('hide');
$('#leermat2').removeClass('show');
$('#leermat3').addClass('show');
});
$('#leermat2 .pag-prev').on('click',function(){
$('#leermat2').addClass('hide');
$('#leermat2').removeClass('show');
$('#leermat1').addClass('show');
$('#leermat3').removeClass('show');
});
$('#leermat3 .pag-prev').on('click',function(){
$('#leermat3').addClass('hide');
$('#leermat2').addClass('show');
$('#leermat1').addClass('hide');
$('#leermat3').removeClass('show');
$('#leermat1').removeClass('show');
});

JQuery Show/Hide Link

So here is my dilemma. Been trucking on this Jquery extreme code here and I need help telling if a certain link is showing or not. Here is what I have.
The toggles:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
(notice the only thing that is different is the icon number) These need to toggle back and forth when someone clicks the #visbilitybutton. Not sure of the best way to do this and to capture what is selected as well.
The only code I have currently makes the toggle go one way, but doesn't go back when clicked again.
$(document).ready(function () {
$('#visbilitybutton').click(function() {
$(this).replaceWith('<span class="icon icon85"></span>');
});
});
First things first, you shouldn't have multiple identical id attributes on your page. Make visibilitybutton a class.
Anyways, you can use the jQuery toggle() function to specify what to do on each consecutive click:
$(".visibilitybutton").toggle(function(){
$(this)
.attr("title","Invisible")
.find("span").toggleClass("icon84 icon85");
}, function(){
$(this)
.attr("title","Visible")
.find("span").toggleClass("icon84 icon85");
});
If you want to be more efficient, you can do it all in one fell jQuery swoop like so, with some good techniques:
var vis = ["Invisible","Visible"];
$(".visibilitybutton").click(function(){
var i = 0;
$(this)
.attr("title",vis[i])
.find("span").toggleClass("icon84 icon85");
i = (i==0)?1:0;
});
Even more so would be to make a class that hides the element when added to it and shows it when you remove it (a classname with display:none applied in the CSS works fine):
$(".visibilitybutton").click(function(){
$(this)
.toggleClass("hide")
.find("span").toggleClass("icon84 icon85");
});
You need to have unique ids; therefore, you should select the items by class. You can use toggle() to handle the consecutive clicks, and you can use toggleClass() to handle the swapping of classes.
HTML:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
Javascript:
$(document).ready(function () {
$('.button').toggle(function() {
var $button = $(this);
$button.prop("title","Invisible");
$button.find('.icon85').toggleClass('icon85', 'icon84');
}, function() {
var $button = $(this);
$button.prop("title","Visible");
$button.find('.icon85').toggleClass('icon84', 'icon85');
});
});
The id attribute is supposed to be unique to each element. Change the id attribute to the class attribute for each hyperlink.
Then, in your jQuery code, get the hyperlinks by their class name:
$('.visbilitybutton').click(function() {
// code goes here
});
In your event handler, you should use test the title attribute, like so:
$('.visibilitybutton').click(function() {
$this = $(this);
if ($this.attr("title") == "Visible")
$this.attr("title", "Invisible").find("span")
.removeClass("icon85").addClass("icon84");
else
$this.attr("title", "Visible").find("span")
.removeClass("icon84").addClass("icon85");
});

Categories

Resources