get bound data on click event - javascript

This is my Razor Page containing multiple divs with each div containing either follow or unfollow button with NeighbourhoodName and other stuff.
<p class="lead" style="display: none" data-bind="visible: profiles().length == 0">No neighbourhood found...</p>
<ul data-bind="visible: profiles().length > 0, foreach: profiles">
<li class="media" style="border-top: solid 1px lightgrey; padding-top: 15px;">
<div class="media-body">
<h4 class="media-heading">
<a class="btn pull-right" data-bind="visible: !IsFollowed, attr: { href: followAction }">Follow</a>
<a class="btn btn-danger pull-right" data-bind="visible: IsFollowed, attr: { href: unfollowAction }">Unfollow</a>
</h4>
<em data-bind="text: NeighbourhoodName"></em>
<em data-bind="text: NeighbourhoodId"></em>
//stuck at this line
</div>
</li>
I want to Generate a new page with click on any of the div. So,I want to send id of the neighbourhood to action method with click on respective div. Right now, i am able to get NeighbourhoodId with data-bind attribute but dont know how to send this id to action method with click on any area of div means how to mix this anchor tag. something like that.
This is my follow action url in a knockout code which send neighbourhoodId on follow button click:
self.followAction = location.protocol + "//" + location.host + '/Neighbourhood/Follow?uid=' + data.NeighbourhoodId;
But, i dont want any button. simple click on div should send id to action method.
how to achieve this. please suggest me something.

You simply have to use the click binding on the div, and bind it to a function in your viewmodel.
The function in your viewmodel receives as parameter the knockout context available in the bound element. So, you can directly access the desired data from that function.
<div class="media-body" data-bind="click: yourViewModelFunction">
In your viewmodel, your function should be implemented like this:
yourViewModelFunction = function(data) {
// here you can use data.NeighbourhoodId
}

Related

Dynamic p tag depends on dropdown select - Javascript Laravel

I guess its simple for javascipt masters . Basically I want to change price(which is default by large) when i select the small size pizza .. Ive tried something but nothing happened
Here is HTML
<div class="row portfolio-containerr">
#foreach($product as $p)
<div class="col-lg-3 text-center portfolio-item {{$p->category_id}} ">
<div class="card bg-transparent " style="width: 14rem;">
<img class="card-img-top" src="{{asset('front/')}}/assets/img/1.png" alt="Card image cap">
<div class="card-body">
<h5 class="card-title text-center">{{$p->title}}</h5>
<p class="card-text text-center">{{$p->description}}</p>
<p product-id="" style="color:#ff4a17;font-size: 20px ">{{$p->price}}</p>
<div class="btn-group">
<button type="button" class="btn btn-danger">Large</button>
<button type="button" class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<a product-id="{{$p->id}}"class="dropdown-item size-click" href="#">Large</a>
<a product-id="{{$p->id}}"class="dropdown-item size-click" href="#">Small</a>
</div>
</div>
Controller
public function getData(Request $request){
$product = Product::findOrFail($request->id);
return response()->json($product);
}
javascript
$(function(){
$('.portfolio-item').on('click', '.size-click', function(){
id = $(this)[0].getAttribute('product-id');
$.ajax({
type:'GET',
url:'{{url("/getData")}}',
data:{id:id},
success:function(data){
console.log(data);
$('p')[0].getAttribute("product-id", data.id);
$('p[product-id="data.id"]').text(data.priceS);
}
})
})
});
That code has several issues which I'll try to address one by one.
PHP/HTML
In your HTML (generated by PHP), you are using a non-existent attribute product-id to attach an ID to several elements. Instead of "inventing" your own attributes, you should use a data- attribute here, because that's what they are made for. For example, instead of
<a product-id="..." class="..." href="#"> ... </a>
you should use
<a data-product-id="..." class="..." href="#"> ... </a>
This goes for all elements that currently have a product-id attribute.
Fixed PHP/HTML
Using data- attributes.
Note: Both <a>-elements receive the same product ID, regardless of the product's size – is that correct?
<div class="row portfolio-containerr">
#foreach($product as $p)
<div class="col-lg-3 text-center portfolio-item {{$p->category_id}} ">
<div class="card bg-transparent " style="width: 14rem;">
<img class="card-img-top" src="{{asset('front/')}}/assets/img/1.png" alt="Card image cap">
<div class="card-body">
<h5 class="card-title text-center">{{$p->title}}</h5>
<p class="card-text text-center">{{$p->description}}</p>
<p data-product-id="" style="color:#ff4a17;font-size: 20px ">{{$p->price}}</p>
<div class="btn-group">
<button type="button" class="btn btn-danger">Large</button>
<button type="button" class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<a data-product-id="{{$p->id}}" class="dropdown-item size-click" href="#">Large</a>
<a data-product-id="{{$p->id}}" class="dropdown-item size-click" href="#">Small</a>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScript
The JavaScript (as it seems) has the following errors/issues that should be fixed:
Implicit global variables
As it stands, you try to grab the product ID from the clicked element and store it in a variable id (line 4). However, it looks as if that variable is an implicit global variable (hence it will be attached to the window object). You should use var id = ... instead of id = ....
Too much complexity
The same line has too much complexity. Why do you wrap the current element that has been clicked (this) into a jQuery collection if you immediately unwrap it (via [0])? Just write this.getAttribute( ... ) and you're done, no need for $(this)[0].getAttribute( ... ).
Oh, and if you follow my suggestion and use data- attributes, don't use getAttribute – use this.dataset.productId to get the ID and this.dataset.productId = ... to set it.
Invalid URL and/or useless interpolation
On line 8, you are passing an invalid URL to $.ajax( ... ). It seems you want to generate the correct URL with the help of a url( ... ) function and use string interpolation to pass the URL to the call to $.ajax. However, the url( ... ) function seems to already return a string that contains the URL. Therefor, it's unlikely that you need string interpolation at all. If I'm right, just use url: url('/getData'), and you are fine.
Useless call to getAttribute
The code in line 12 (success callback) makes a useless call to getAttribute. It's useless because the value returned by getAttribute isn't used anywhere. Also, getAttribute takes a single parameter, not two parameters. Did you mean setAttribute instead? If not, you can safely delete line 12. Otherwise, use setAttribute.
I'm not really sure that the code works correct, even if you use setAttribute. Let me explain: Calling $('p')[0] will give you the first paragraph/<p>-element of the whole page – probably not what you want. Instead, you want the first paragraph inside the corresponding .portfolio-item element. To do that, you have to pass a second argument to $( ... ) that marks the root element. Just save a reference to the .portfolio-item inside the click handler (but outside of the success callback) in a variable that you can then use later.
Wrong selector
Finally, in line 13 you pass the selector 'p[product-id="data.id"]' to the $( ... ) function. It seems you want to select the <p> element that has the product ID returned by the call to $.ajax. In that case, you have to generate a selector that contains the actual ID. Something like this:
`$('p[product-id="' + data.id + '"]')`
Although it seems you don't need any of this if you save the <p>-element you manipulated in line 12 into a variable. That's because the mentioned selector queries the DOM for exactly the same <p>-element. This means you can use the "native" .textContent property instead of jQuery's .text function.
Fixed JavaScript (with data-attributes)
Here is the complete JS code with most of the above mentioned issues gone.
$(function(){
$('.portfolio-item').on('click', '.size-click', function(){
var id = this.dataset.productId, // <-- uses data-attributes now
pitem = $(this).closest('.portfolio-item'); // <-- reference to containing portfolio-item element
$.ajax({
type: 'GET',
url: url('/getData'), // <-- fixed URL
data: { id: id },
success: function (data) {
console.log(data);
var p = $('p', pitem)[0]; // <-- get first paragraph in parent
p.dataset.productId = data.id; // <-- assign product id to data-attribute
p.textContent = data.priceS; // <-- display the price
}
})
})
});

Display all the data along with the image/icon when list is clicked

Above is the dropdown that when list is clicked, its value will be displayed in the field above (which is a button btw) together with the image. I've already achieved displaying the text but I cannot seem to display the image. This is my markup below...
<button type="button" onclick="showbanks(); return false;" name="button" class="banknam btn dropdown-toggle center-right glyph form-control d-inline-block" data-toggle="dropdown-menu" aria-haspopup="true" aria-expanded="false">广东</button>
<ul class="dropdown-menu menu-banknam">
#foreach (array_slice($chosen_bank,0,5) as $index =>$bank)
<li value="{{$bank}}" onclick="clickbanks(); return false;">
<span class="bankimg d-inline-block"><img src="{{ asset($chosen_bankimg[$index]) }}" alt=""></span>
<span class="bank_nam d-inline-block">{{ $bank }}</span>
</li>
#endforeach
</ul>
...and my function...
function clickbanks(){
$(".menu-banknam li").click(function(){
$(this).parents(".bb-container").find('.banknam').html($(this).text());
return false;
});
}
Is there any way to achieve this? Thank you.
Use .html() instead of .text() to get the entire content of the li instead of just the text.
e.g.
$(this).parents(".bb-container").find('.banknam').html($(this).html());
You are also assigning a new click event to the li each time you click on it.
You should remove the clickbanks function and instead assign the click event once when the document is ready. You'll also have to remove it from the onclick attribute of the li.
e.g.
$(function() {
$(".menu-banknam li").click(function() {
$(this).parents(".bb-container").find('.banknam').html($(this).text());
return false;
});
});

Laravel ajax model to show posts

I have a foreach() from database table, I want to show a popup/model to show its extra information.
I am showing just title and description and on click i want to open up a popup and show its extra information.
#foreach($myProjects as $project)
<div class="col-sm-4 col-md-4 notes notes--blue">
<a href="#edit-note" data-toggle="modal" style="background-color: #f9f9f9;border-bottom: 5px solid #42A5F5">
<div class="notes__title">{{$project->title}}</div>
<div class="notes__body">{{$project->description}}</div>
</a>
<div class="notes__actions" data-demo-action="delete-listing">
<i class="zmdi zmdi-delete"></i>
</div>
<div class="notes__actions1" data-demo-action="delete-listing">
<i class="zmdi zmdi-edit"></i>
</div>
<div class="notes__actions2" data-demo-action="delete-listing">
<i class="zmdi zmdi-eye"></i>
</div>
</div>
#endforeach
I am completely blank, Should i fetch post id to a hidden html tag and on model button click an ajax call will fetch the record info based on the id ?
I would add a data-id attribute to one of the elements, possibly the wrapper, then add something like
$(document.body).on('click', '.clickable_element', function(e){
if ($(this).data('id')) {
$.ajax({
url : 'your detail url',
data: { id: parseInt( $(this).data('id'), 10 ),
success : function(response){
// open popup and add response into it.
}
})
}
});
Update
I just noticed you already have bootstrap modal there.
you can add your data-id to data-toggle element then in javascript
$('[data-toggle=modal]').on('shown.bs.modal' , function(){
// do your ajax stuff
// add response in `.modal-body`
})

How to show an icon on click in meteor?

I am building an application in a meteor and I have a below code in the template.
<h3>
<b>
<a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a>
</b>
<span class="job-type part-time">Part Time</span>
</h3>
<div id="eyeIcon">
<span class="glyphicon glyphicon-eye-open" style="color:green"></span>
</div>
I have to display the glyphicon eye icon on click of a href tag and storing them into a collection. How can I do that? I am new to the meteor. Can anyone help me how can we do it using Meteor. Thanks in advance.
<h3>
<b>
<a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a>
</b>
<span class="job-type part-time">Part Time</span>
</h3>
{{showIcon}}
<div id="eyeIcon">
<span class="glyphicon glyphicon-eye-open" style="color:green"></span>
</div>
{{/if}}
Template.yourTemplate.helpers({
'showIcon': function() {
return Session.get('showIcon');
},
});
Template.yourTemplate.events({
'click .viewed': function(event, instance) {
event.preventDefault();
Session.set('showIcon', true);
},
});
Please note that I have used session to persist your data throughout the app. If you also want to retain this value permanently than you can use collections.
Also, if you to just retain it's value to be persisted on page refresh also, then you can use Session.setPersistent (https://github.com/okgrow/meteor-persistent-session) instead of Session.set
Start by hiding your #eyeIcon div by default. For example, add the following to /client/main.css:
#eyeIcon {
display: none;
}
Then leverage the Blaze Template event system to show the div when the link is clicked. So in your Template:
Template.yourTemplate.events({
'click .viewed'(event, instance) {
event.preventDefault();
instance.$('#eyeIcon').show();
},
});

Click button to copy text to another div with angularjs

I have a list of Items with different button with them. Plunker
Quick View:
I want something like if I click on any of the buttons, related text will be copy to the div above. Also if I click on the button again it will removed from the Div.Same for each of the buttons. [I added manually one to show how it may display ]
I am not sure how to do that in Angular. Any help will be my life saver.
<div ng-repeat="item in csTagGrp">
<ul>
<li ng-repeat="value in item.csTags">
<div class="pull-left">
<button type="button" ng-class='{active: value.active && !value.old}' class="btn btn-default btn-xs">{{value.keys}}</button>
<span>=</span>
</div>
<div class="pull-left cs-tag-item-list">
<span>{{value.tags}}</span>
</div>
</li>
</ul>
</div>
The simplest thing would be to use $scope.tags object to store selected tags and add/remove them with the scope method similar to this:
$scope.tags = {};
$scope.toggleTag = function(tag) {
if (!$scope.tags[tag]) {
$scope.tags[tag] = true;
}
else {
delete $scope.tags[tag];
}
};
Demo: http://plnkr.co/edit/FrifyCrl0yP0T8l8XO4K?p=info
You can use ng-click to put in your scope the selected value, and then display this value instead of "Win".
http://plnkr.co/edit/IzwZFtRBfSiEcHGicc9l?p=preview
<div class="myboard">
<span>{{selected.tags}}</span>
</div>
...
<button type="button" ng-click="select(value)">{{value.keys}}</button>

Categories