How can I reach specific div in JavaScript? - 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>

Related

How to create onclick ajax function in prestashop (1.7) and build right url link

I created an ajax reference in javasctript and I expect the link to be realized, it has appealed to the ajax_[modulename].php file in the background, but the url address is ignored and the main address is inserted into the module. I do not know what is causing this. Please help.
I created the javascript code in the file .... tpl as below. Then I added the ajax_[modulename].php file which I placed in the main module directory
The expected effect is to display messages that confirm this part is working correctly.
Unfortunately, this is not done in the background and the reference that is returned is the main link of the module.
The site is reloaded and the link "index.php? Controller = AdminModules & token = 3213789e146f56adaa445b96bb79956f & configure = dpeasye & module_name = dpeasy & List" is executed.
File - display_list.tpl
<td class="text-right">
<div class="btn-group-action pull-right">
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=47&ListDic=mg">
<i class="icon-layer"></i>
Display Sub
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=47&UpdateDic=mg">
<i class="icon-edit"></i>
Edytuj
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=47&DeleteDic=mg">
<i class="icon-trash"></i>
Delete
</a>
<a id="active-47" class="btn btn-success ajax-status" href=" " title="Enabled">
<i class="icon-check"></i>
Enabled
</a>
</div>
</td>
<td class="text-right">
<div class="btn-group-action pull-right">
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=65&ListDic=tt">
<i class="icon-layer"></i>
Display Sub
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=65&UpdateDic=tt">
<i class="icon-edit"></i>
Edytuj
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=65&DeleteDic=tt">
<i class="icon-trash"></i>
Delete
</a>
<a id="active-65" class="btn btn-success ajax-status" href=" " title="Enabled">
<i class="icon-check"></i>
Enabled
</a>
</div>
</td>
File - display_list.tpl
<script type="text/javascript">
$('a.ajax-status').click(function() {
var MainUrl = "";
var abtn = $(this);
var aidall = $(this).attr('id');
var aid = $(this).attr('id').replace('active-', '');
var aclass = $(this).attr('class').split(' ');
var atitle = $(this).attr('title');
var atext = $(this).text();
atext = atext.replace('\n', '');
var iclass = $(this).children().attr('class');
var data = '&id_field=' + aid ;
$.ajax({
url: baseDir + 'modules/dpeasye/ajax_dpeasye.php?action=changeStatus',
type: 'POST',
data: data,
cache: false,
dataType: "JSON",
success: function(aid){
if (aclass.class[2] == 'btn-danger'){
abtn.fadeOut(700);
atext.replace('Enabled','Disabled');
aclass[2].replace('btn-success','btn-danger');
atitle.replace('Enabled','Disabled');
iclass.replace('icon-check','icon-remove');
abtn.fadeIn(700);
}
if (aclass.class[2] == 'btn-danger'){
abtn.fadeOut(700);
atext.replace('Disabled','Enabled');
aclass[2].replace('btn-danger','btn-success');
atitle.replace('Disabled','Enabled');
iclass.replace('icon-remove','icon-check');
abtn.fadeIn(700);
}
showSuccessMessage(update_success_msg);
},
failure:function(aid){
console.log('test ok');
}
});
});
</script>
File - ajax_dpeasye.php
include_once('../../config/config.inc.php');
include_once('../../init.php');
include_once('dpeasye.php');
if (isset($_GET['action'])) {
switch ($_GET['action']) {
case 'changeStatus':
$this->displayConfirmation($this->trans('Test passed'));
break;
case 'sort':
break;
}
} else {
die('no action passed');
}
Why does the main link appear if there is no link in the link: "<a id="active-65" class="btn btn-success ajax-status" href="" title="Enabled"> <i class = "icon -check "> </ i> Enabled </a>"?
What is the reason that the javascript code is not being executed?

I can´t remove the last item of array

I can remove any item of array unless the last one. I also use angularjs to show information in the view. I don´t know what is happening with the last item of this array. Please, anyone can help me?
Here is HTML:
<div class="row">
<div class="col-md-12">
<h4><strong>Documento {{index + 1}} de {{documentos.length}}:</strong> {{documentos[index].nome}}</h4>
<iframe style="background: #ccc;" ng-show="exibirPreview" frameborder="0" ng-src="{{versaoLink}}" width="100%" height="300px"></iframe>
<div class="alert alert-warning" ng-hide="exibirPreview">
#Html.Raw(Resources.Dialog.SignDocuments.TypeDocumentCanNotPreDisplayed)
</div>
<hr />
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<button class="btn btn-default" type="button" ng-click="RemoveDoc(index)"><i class="fa fa-fw fa-times"></i> #Resources.Common.RemoveDocList</button>
</div>
</div>
</div>
Here is js/angularjs
$scope.documentos = [
{nome:"document1", chave: "8F65579E3737706F", extensao:".pdf"},
{nome:"document2", chave: "8F65579E3730007F", extensao:".pdf"},
{nome:"document3", chave: "8545579E3737706F", extensao:".pdf"},
{nome:"document4", chave: "8555579E3730007F", extensao:".pdf"}
]
$scope.ViewLink = function () {
var versao = $scope.documentos[$scope.index];
$scope.exibirPreview = versao.extensao == ".pdf" || versao.extensao == ".txt";
if (!$scope.exibirPreview) {
$scope.versaoLink = '';
} else {
$scope.versaoLink = '/Documento/VersaoView?chave=' + versao.chave;
}
};
$scope.ViewLink();
$scope.RemoveDoc = function (index) {
$scope.documentos.splice(index, 1);
$scope.ViewLink();
};
Or Plunker
In your HTML you are preventing the deletion of the last element:
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<!-- -->
</div>
documentos.length > 1 means "hide when it reaches one item in the array".
It should be documentos.length == 0.
It's either this or your index value starts from 1 and not from 0.
The simplest solution would be to change your remove function to take in the document instead of the index. Try this:
$scope.RemoveDoc = function(document) {
var index = $scope.documents.indexOf(document);
$scope.documents.splice(index, 1);
}
in view:
<button class="btn" type="button" ng-click="RemoveDoc(document)">Delete</button>

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

Change the onclick of a hyper link

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

jQuery remove class on closest

I'm trying to action a removeClass request using jQuery. Most of the below script is working fine except for the $(this).closest('.press-continue').removeClass('hidden'); part.
I have posted the jQuery and HTML below. Any ideas what could be the problem?
$(function () {
$('.step2').on('click', '.btn-book', function (e) {
$.ajax({
url: '/reserve/' + this.id,
type: 'get',
dataType: 'json',
context: this,
success: function (json) {
if (json['success']) {
$(this).addClass('btn-selected');
$('.btn-book').not(this).addClass('book-disabled').prop('disabled', true);
$('.next-step-hidden').addClass('show-button').prop('href', '/confirm/' + this.id);
$('.cancel').addClass('show-button').prop('id', this.id);
$('.alert-danger').addClass('hidden-error');
$(this).closest('.press-continue').removeClass('hidden');
} else if (json['error']) {
if (json['error'] == 1) {
alert("Another user has already booked this slot, please choose another slot.");
$(this).addClass('btn-selected').addClass('book-disabled').prop('disabled', true);
}
}
}
});
});
});
HTML
<div id="main">
<h2 class="info-bar clearfix"><b>Select parking time</b> <span>Step <i>2</i></span></h2>
<div class="alert alert-danger hidden-error">
<strong>Expired!</strong> Sorry, the slot that you reserved has now expired. Please choose another slot below.
<br><i>Note: slots are reserved for 15 minutes.</i>
</div>
<form class="step2">
<fieldset>
<legend><span>Select a Parking Slot</span></legend>
<div class="parking-time">
<div class="input-row">
<label class="label">12/06/2015
<br>Morning
<br>7am - 1pm</label>
<button class="btn btn-small btn-important btn-book" type="button" id="67"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
<div class="input-row">
<label class="label">12/06/2015
<br>Afternoon
<br>2pm - 7pm</label>
<button class="btn btn-small btn-important btn-book" type="button" id="68"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
<div class="input-row">
<label class="label">12/06/2015
<br>All Day
<br> </label>
<button class="btn btn-small btn-important btn-book" type="button" id="69"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
</div>
<!-- end parking-time -->
<div class="input-row input-row-last"> <a class="btn btn-small btn-info cancel">Cancel</a> <a class="btn btn-info next-step next-step-hidden">Continue <i class="sprite arrow"></i></a> </div>
</fieldset>
</form>
</div>
<!-- end main -->
.closest() is used to find an ancestor element, where as what you are looking for is the next sibling so you can use .next()$(this).next('.press-continue').removeClass('hidden');
$(function () {
$('.step2').on('click', '.btn-book', function (e) {
$.ajax({
url: '/reserve/' + this.id,
type: 'get',
dataType: 'json',
context: this,
success: function (json) {
if (json['success']) {
$(this).addClass('btn-selected');
$('.btn-book').not(this).addClass('book-disabled').prop('disabled', true);
$('.next-step-hidden').addClass('show-button').prop('href', '/confirm/' + this.id);
$('.cancel').addClass('show-button').prop('id', this.id);
$('.alert-danger').addClass('hidden-error');
$(this).next('.press-continue').removeClass('hidden');
} else if (json['error']) {
if (json['error'] == 1) {
alert("Another user has already booked this slot, please choose another slot.");
$(this).addClass('btn-selected').addClass('book-disabled').prop('disabled', true);
}
}
}
});
});
});

Categories

Resources