Change the onclick of a hyper link - javascript

I want to update the click event of the hyperlink onClick and want to update the html inside the hyperlink in jquery
HTML
<a class=" save" href="javascript:void(0);" onclick="save_unsave('unsave','UID','ID',this);">
<div class="jopt_iconwrap" title="Unsave" alt="Unsave" >
<span class="saved"></span>
</div>
Unsave
</a>
Now onlick of save_unsave function i want to update the html design as below:
<a class=" save" href="javascript:void(0);" onclick="save_unsave('save','UID','ID',this);">
<div class="jopt_iconwrap" title="Save" alt="Save" >
<span class=""></span>
</div>
Save
</a>
I am trying to do this in the function:
jQuery
if(type == 'save')
{
var new_type = "'unsave'";
jQuery(elem_obj).html("");
jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class="saved" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="saved"></span></div>Unsave</a>');
}
else if(type == 'unsave')
{
var new_type = "'save'";
jQuery(elem_obj).html("");
jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class=" save" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="mico"></span></div>Save</a>');
}
How can we do this in jquery.Please help me in the i have the elmenet object in the function.

simply i will suggest you to use replaceWith() in place of .html() it will work properly for you.

$('a').click(function() {
if ($(this).hasClass('save')) {
$(this).removeClass('save').addClass('unsave');
$(this).text('Unsave')
$(this).attr('id','save')
} else {
$(this).removeClass('unsave').addClass('save');
$(this).text('Save')
$(this).attr('id','unsave')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class=" save">
<div class="jopt_iconwrap" title="Save" alt="Save">
<span class=""></span>
</div>
Save
</a>
Try this way

You can replace the onclick event, like this:
$('.save')[0].onclick = function() {
save_unsave('save', 'UID', 'ID', this);
}

Related

How can I change the .innerHTML property of an appended button text using Javascript?

I'm trying to make a "Like" button for a post which was fetched by AJAX using jQuery. Here, I want to change button text while clicked. But it's not changing.
Here is my Like button codes:
$('.posted-area').append('\
<div class="posted-footer">\
<ul>\
<li>\
<button class="btnLike btn-danger" id="btnLike" onclick="btnLikefunction()"> Like </button>\
</li>\
<li>\
<i class="fa fa-comments-o"></i> \
<span>15 comments</span>\
</li>\
</ul>\
</div>\
');
Here is my onClick event for the "Like" button:
function btnLikefunction(){
var btnTextChange = document.getElementById(".btnLike");
btnTextChange.innerHTML= "Liked!";
}
You just need 2 changes
onclick="btnLikefunction(this)"
and
function btnLikefunction(elm) {
$(elm).text("Liked").css('color', 'red'); // set text and color
}
Example
$('.posted-area').append('\
<div class="posted-footer">\
<ul>\
<li>\
<button class="btnLike btn-danger" id="btnLike" onclick="btnLikefunction(this)"> Like </button>\
</li>\
<li>\
<i class="fa fa-comments-o"></i> \
<span>15 comments</span>\
</li>\ </ul>\ </div>\
');
function btnLikefunction(elm) {
$(elm).text("Liked").css('color', 'red');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="posted-area"></div>
let html = $(`<div class="posted-footer">
<ul>
<li>
<button class="btnLike btn-danger" id="btnLike"> Like </button>
</li>
<li>
<i class="fa fa-comments-o"></i>
<span>15 comments</span>
</li>
</ul>
</div>
`)
html.appendTo('#post-wrapper')
html.find(".btnLike").on("click",e=>{
$(e.target).html("Liked!")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="post-wrapper"></div>
This is method is to use jquery to wrap your html first, then you can use jquery event listener on on the html.
Problem with your code is you use the wrong JS selector, where you use select by ID function but you pass a class name into it, since you are using jquery, you can change from:
var btnTextChange = document.getElementById(".btnLike");
btnTextChange .innerHTML= "Liked!";
to
$(".btnLike").html("Liked!")
Here you go. Find your button inside appended div and change your text.
Working Example:
$('.posted-area').append('\
<div class="posted-footer">\
<ul>\
<li>\
<button class="btnLike btn-danger" id="btnLike" onclick="btnLikefunction()"> Like </button>\
</li>\
<li>\
<i class="fa fa-comments-o"></i> \
<span>15 comments</span>\
</li>\ </ul>\ </div>\
');
function btnLikefunction() {
var btnTextChange = $(".posted-area").find(".btnLike")
$(btnTextChange).addClass("red");
$(btnTextChange).html("Liked!")
}
.red {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="posted-area"></div>
To change text color you can use addClass like above example.
Note: Don't mismatch JavaScript and jQuery.

jQuery: change link text and icon on click

So I am trying to change the the icon of my link for collapse section alongside with the text of the link.
Here is my code:
<a href="#collapse", class="btn", role="button", data-bs-toggle="collapse" id="btn-collapse">
<i class="material-icons" style="vertical-align: middle;">expand_more</i>
<label style="vertical-align: middle;">PRIMARY TEXT</label>
</a>
<!--CONTENT-->
<script>
$(document).ready(function(){
$('#btn-collapse').on('click', function () {
var text=$('#btn-collapse').text();
if(text === "SECONDARY TEXT"){
$(this).text('PRIMARY TEXT');
$(this).find("i").html("expand_more");
} else{
$(this).text('SECONDARY TEXT');
$(this).find("i").html("expand_less");
}
});
});
</script>
I've been trying to find a solution for this for a while now, but nothing seems to work.. Text changes fine, but the icon completely vanishes on click. I don't think it is a major issue, but there is something I don't get with this. Any help here how to adjust?
$(document).ready(function() {
$('#btn-collapse').on('click', function() {
var thisElement = $(this);
var anchorLabelElement = thisElement.find('label');
if (anchorLabelElement.text() === "SECONDARY TEXT") {
anchorLabelElement.text('PRIMARY TEXT');
thisElement.find("i").text('expand_more');
} else {
anchorLabelElement.text('SECONDARY TEXT');
thisElement.find("i").text("expand_less");
}
});
});
<link href="https://cdn.jsdelivr.net/npm/material-design-icons-iconfont#6.7.0/dist/material-design-icons.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#collapse" , class="btn" , role="button" , data-bs-toggle="collapse" id="btn-collapse">
<i class="material-icons" style="vertical-align: middle;">expand_more</i>
<label style="vertical-align: middle;">PRIMARY TEXT</label>
</a>

How can I reach specific div in JavaScript?

I have a plp page which are listed items. And user can favorite any item.
My problem is when the user favorite one item, I want to change star icon it should be show favorited.
Here my item structure:
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342">
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>
<img class="favorite" src="/_ui/responsive/common/images/favorite.svg" height="17px;">
</span>
</div>
</span>
</div>
</div>
Every item has unique id like this:
<span role="button" class="wish-list-icon" id="grc398342">
So, I want to reach and change only this section when user favorite:
<span>
<img class="favorite" src="/_ui/responsive/common/images/favorite.svg" height="17px;">
</span>
I changed my code like this but its not running?
var newURL = "/_ui/responsive/common/images/favorite-red.svg";
function fav(elemId){
$("#elemId").find(".favorite").attr("src", newURL)
}
$('#addBtn').click(function() {
var listName = $('#listName').val();
var productCode = $('#productCode').val();
$('#notificationP').text('');
if (listName.trim() == '') {
$('#notificationP').text($('#nameValidate').val());
return;
}
$('.loading-overlay').show();
$.ajax({
type : "POST",
url : ACC.config.encodedContextPath + "/wishlist/add",
data : 'productCode=' + productCode + '&listName=' + listName,
success : function(loginPopup) {
$('.loading-overlay').hide();
if (loginPopup.code == '0' || loginPopup.code == '2') {
$('#notificationP').text($('#duplicate').val());
} else if (loginPopup.code == '1') {
$('#notificationP').text($('#add').val());
fav(productCode);
}
else if(loginPopup.code == '3'){
$('#notificationP').text($('#maxProductsError').val()+' '+loginPopup.errorCodeMeg+')');
}
else {
$('#notificationP').text($('#globleError').val());
}
},
error : function(error) {
$('.loading-overlay').hide();
$('#notificationP').text($('#globleError').val());
}
});
});
How can I access this image?
Onclick of the div invoke a function and push the id of the div. Using children get the span child and make changes
function a(id) {
var ele = document.getElementById(id).children[0].children[0];
ele.style.color = "red";
ele.children[0].setAttribute('url',"www.xyz.com")
console.log(ele.children[0].getAttribute('url'))
}
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342" onclick=a(this.id)>
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>dd
<img class="favorite" src="/_ui/responsive/common/images/favorite.svg" height="17px;">
</span>
</div>
</span>
</div>
</div>
You can use .find() method on the passed element in jquery like this. We give .find() the class name of the image and then change src attribute of the image. In this example if you click on the icon it will change to a star.
var newURL = "https://img.freepik.com/free-vector/start_53876-25533.jpg?size=338&ext=jpg";
function fav(elem){
$(elem).find(".favorite").attr("src", newURL)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342" onclick="fav(this)">
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>
<img class="favorite" src="https://img.freepik.com/free-vector/yellow-star-trail-set_23-2147739091.jpg?size=338&ext=jpg" height="17px;">
</span>
</div>
</span>
</div>
</div>
As for your comment how to do this in ajax. You can return the item id in your ajax call and then access it like this
var newURL = "https://img.freepik.com/free-vector/start_53876-25533.jpg?size=338&ext=jpg";
function fav(elemId){
$("#elemId").find(".favorite").attr("src", newURL)
}
// your ajax call
$.ajax({
url: "",
data: { /*Your parameters*/},
success: function(returnedData){
fav(returnedData);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342">
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>
<img class="favorite" src="https://img.freepik.com/free-vector/yellow-star-trail-set_23-2147739091.jpg?size=338&ext=jpg" height="17px;">
</span>
</div>
</span>
</div>
</div>

The server responded with a status of 500 AJAX Post

I have this javascript function which should redirect me to
http://localhost:8888/ID OF A PRODUCT/add-to-cart".
But instead I got this:
http://localhost:8888/undefined/add-to-cart".
$('.add-to-cart').on('click', function () {
var productId = $(this).find('.indexImg').attr('id');
$.ajax(productId+"/add-to-cart",
{
});
});
<img class="indexImg" src="{{$product->image}}" id="{{$product->id}}">
Can someone help me to get ID of a product ?
HTML:
#foreach($products as $product)
<div class="col-md-3">
<div class="box-product">
<div class="img-wrapper item">
<a href="/product/{{$product->id}}/{{$product->slug}}">
<a class="thumbnail" href="/product/{{$product->id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
<img class="indexImg" src="{{$product->image}}" id="{{$product->id}}">
</a>
</a>
<div class="tags">
#if($product->discount > 0)
<span class="label-tags"><span class="label label-danger">Išpardavimas</span></span>
#endif
<span class="label-tags"><span class="label label-info">Nauja</span></span>
</div>
<div class="option">
<i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white"></i>
</div>
</div>
Do one thing
Change
<i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white"></i>
With
<i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white" id="{{$product->id}}"></i>
and get by
$(this).attr('id');
So the code will be
$('.add-to-cart').on('click', function () {
var productId = $(this).attr('id');
$.ajax(productId+"/add-to-cart",
{
});
});
$('.add-to-cart').on('click', function (event) {
var productId = event.target.id;
$.ajax(productId+"/add-to-cart",
{
});
});
.find is try to find inside current element u need to go up then find indexImg
$('.add-to-cart').on('click', function () {
var productId = $(this).parents('.box-product').find('.indexImg').attr('id');
$.ajax(productId+"/add-to-cart",
{
});
});
The way you are trying to get product ID based on DOM is incorrect. The jQuery .find() method looks for specified elements within the elements, i.e. its descendants. If you look at the HTML, you'll see that the div elements containing the add-to-cart button and the image whose id attribute you are trying to fetch are on the same level.
So you've got to change the way you are traversing to reach the id attribute of the <img> tag.
var productId = $(this).closest('.box-product').find('.indexImg').attr('id');

Getting data-* attribute for onclick event for an html element

<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);">
Click to do something
</a>
I want to get the data-id and data-option values inside the function goDoSomething(10, 21) I have tried to use this reference: this.data['id'] but it did not work.
How can I do this?
You can achieve this $(identifier).data('id') using jquery,
<script type="text/javascript">
function goDoSomething(identifier){
alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
javascript : You can use getAttribute("attributename") if want to use javascript tag,
<script type="text/javascript">
function goDoSomething(d){
alert(d.getAttribute("data-id"));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
Or:
<script type="text/javascript">
function goDoSomething(data_id, data_option){
alert("data-id:"+data_id+", data-option:"+data_option);
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
Click to do something
</a>
Like this:
$(this).data('id');
$(this).data('option');
Working example: http://jsfiddle.net/zwHUc/
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a element and gets the data-id attribute from it.
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at
https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
here is an example
<a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>
$('.facultySelecter').click(function() {
var unhide = $(this).data("faculty");
});
this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get
you can directly use anchor id or data-action attributes to trigger the event.
Html Code
<a id="option1" data-action="option1" data-id="10" data-option="21" href="javascript:void(0);" title="Click Here">Click Here</a>
jQuery Code:
$('a#option1').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option')) ;
});
OR
$('[data-action="option1"]').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option'));
});
User $() to get jQuery object from your link and data() to get your values
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>

Categories

Resources