Toggle with ! operator not working on page load JavaScript - javascript

I have an onClick (using angular.js ng-click) where i have to toggle color of a table row with on click.
This is the initial implementation.
<tr>
<td ng-class="{'setType': types.isTypeSet('TYPE') == true}" ng-click="types.setType('TYPE')">
<img class="typebox-img" src="">
<div class="typebox">TYPE</div>
</td>
</tr>
where 'type' is the type of table row and 'types' is the angular controller.
types.setType(type):
...
this.types[type] = ! this.types[type];
...
while this toggles values from the second click on, it doesnt change the value on the first click.
I implemented the functionality using the if-else statement, but cant figure out why this wont work as it is a pretty basic thing to do.
this.types[type] is set to false as default.
Could someone explain why is this happening..

It doesn't surprise me that this doesn't work:
ng-click='types.setType('type')
Use " for the inner quotes to make the parser understand what you're trying to do (or the other way around):
ng-click='types.setType("type")'
Incidentally, you don't need a function to do this. Just initialize in your controller a bool:
$scope.toggle = true
And use in your view like this:
ng-click='toggle = !toggle'

Related

Django Modelmultiplechoicefield Checkboxselectmultiple Problem Getting Selected Checkbox

I have been working all day to try and get the selected values on one set of checkboxes on my Django form and copy the selected ones only to an identical checkbox on my form. If a user clicks on a checkbox in form.author defined below, I want the same identical checkbox to automatically be checked on form.favorite_author defined below.
I've tried a JQuery approach as documented here...Copy Selected Checkbox Value From One Checkbox To Another Immediately Using JQUERY but no luck so far. I've recently begun exploring an avenue with the Modelmultiplechoicefield and the checkboxselectmultiple parameters within the form itself. From what I can tell, when I am using JQuery and trying to check a box on the form, the value is coming back as undefined which is most likely why it is not propagating the checkbox selection to the other checkbox.
Here is my form....
class ManagerUpdateNewAssociateForm(forms.ModelForm):
class Meta:
model = Library
self.fields['author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
self.fields['favorite_author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
My HTML...
<div class="spacer83">
{{ form.author }}
</div>
<div class="spacer83">
{{ form.favorite_author }}
</div>
When I tried to trace JQuery, it told me the checkbox selections are undefined. I did read a bit about how Modelmultiplechoicefield, since it uses a queryset it doesn't show the selections, but I can't figure out how to get it to.
Thanks in advance for any thoughts.
In combination with the other issue included in this one, I went back to the JQuery route and explored further. From what I can tell, I was not able to use the class for the input because of the way the HTML for Django forms is generated in this use case. I ultimately was able to leverage the input name and then used the code below to interrogate the checkboxes accordingly:
$(document).ready(function() {
$("[name=author]").change(function() {
let selectedValA = $(this).val();
let isAChecked = $(this).prop("checked");
$(`[name=favorite_author][value="${selectedValA}"]`).prop("checked", isAChecked);
});
});
});

Stimulus: how to handle repeating items with the same target name

I have a list of items, and each one has a link to click to edit it. I am using stimulus to make the edit "modal" form visible when they click that edit link. The id of what is going to be edited is present as an id= on the corresponding link tag of the list
So, the edit link looks like this:
<td>
<a data-action="click->content#edit"
data-target="content.editBtn"
id="<%= url_for(content) %>")>
Edit
</a>
</td>
And the idea is that the content#edit action in the stimulus controller examines the and locates the id of it and uses that to edit the right row.
However the problem I am having is, I think, that as a result all the rows of this list have a data-target with the same name and the wrong one (the first one?) gets bound to the target..
However if I wanted to make each data-target different by e.g. appending the id to it, now I have a long list of targets in the controller.js so that doesn't make sense.
What's the right way to handle?
If you're using Rails as the backend like your other questions seem to indicate, there may be a simpler, non-Stimulus solution. To use Stimulus, you'd need to fetch the data for the item from the server or from the DOM, display it in a form, then submit the correct form with the correct ID to the server through JavaScript. Why not just have a remote link_to button to the edit action for each item? Rails gets a JS request to the edit controller action, and you can load the modal form with the data that you have from your Ruby object.
If you use Stimulus for anything on the form, I'd use this opportunity to craft a Stimulus controller that listens to the ajax->send/error/complete events and automatically disables/enables buttons, sets loading spinners on buttons, and closes the modal. Those would be good areas to sprinkle in some functionality that Stimulus makes very simple.
This is actually a good use of Stimulus since it is modular. You add a controller for each row instead of having the controller around the page or table.
<tr data-controller="content">
<td>
<a data-action="click->content#edit" data-target="content.editBtn" id="<%= url_for(content) %>")>
Edit
</a>
</td>
</tr>
I was just having a similar problem.
This helped:
https://codepen.io/smashingmag/pen/ExPprPG
Basically you can loop over the targets like:
for(let tgt of this.mySameNameTargets) {
tgt.innerHTML = "Some Value"
}
This assuming you have this in the controller:
state targets = ["mySameName"]
You can also use "Action Parameters" to put the id in each row:
https://stimulus.hotwired.dev/reference/actions#action-parameters
From those docs it looks like this:
<div data-controller="item spinner">
<button data-action="item#upvote spinner#start"
data-item-id-param="12345"
data-item-url-param="/votes"
data-item-payload-param='{"value":"1234567"}'
data-item-active-param="true">…</button>
</div>
// ItemController
upvote(event) {
// { id: 12345, url: "/votes", active: true, payload: { value: 1234567 } }
console.log(event.params)
}
You can set the id of the item in that row in a param, and then when they click on that row you can dig it out of the params.

Vue.js weird rendering with class binding

So basically I have an html table with a v-for that loops over an array of objects, nothing complicated here. When the user clicks on a row, it toggles the selected property of the object "linked" to the given row.
Now, I also setup a simple class-binding with v-bind:class="{'active': n.selected}" where n is my object, but it doesnt update. Now what is more weird is that I use the webpack template from the vue-cli, and when I :
Select a bunch of rows (no active class binded)
update code
hit F5 which triggers the webpack hot-reload
The selected rows suddenly get the active class, as the CSS says so, until the webpack hot-reload has regenerated the page.
Here is my code :
<tr
v-for="n in node.children"
track-by="id"
v-on:click="toggleElement(n)"
v-bind:class="{'active': n.selected}">
<td>
<i class="icons">
<i class="folder yellow icon"></i>
</i>
</td>
<td><a v-on:click.stop="getLevel(n.id)">{{ n.name }}</a></td>
<td><span v-if="n.modification_date">{{ n.modification_date | moment "calendar"}}</span><span v-else>-</span></td>
<td><span v-if="n.size">{{ n.size }}</span><span v-else>-</span></td>
And for the javascript method
toggleElement: function(element) {
element.selected = !!(element.selected === undefined || !element.selected);
},
Now some more details, the objects are being retrieved by an ajax call, and the selected property doesnt exist from the start.
Any advice or solution ?
Thanks a lot!
by default,vue.js can not track the property you add after vue instance had been created
BUT,there is some method you can call to tell vue that new properties been added:
vm.$set('selected', true) //this will make "selected" propertie
trackable
First, do not forget to add the closing </tr> in your code.
Second, you can not add new attributes on objects after creating them with VueJS.
If when creating the element, its attribute selected was undefined, then VueJS will not add the getter/setter on it and changing it won't update the interface.
You will need to add the selected attribute before passing it to VueJS.

Add clickable element within a clickable table row

Let's say I have a table row with a clickable element in it:
<tr ng-repeat="product in products" onclick="showProductDetail()">
<td>{{product.id}}</td>
<td>{{product.title}}</td>
<td>{{product.price}}</td>
<td>
<switch id="enabled" name="enabled" ng-model="product.enabled" ng-change="enableProduct()"></switch>
</td>
</tr>
I'm using Angular UI Switch but the issue would be the same for any clickable element.
How do I make the row clickable but isolate the behavior of the switch? Currently it tries to do both, resulting in wonky behavior. I know I could just make each cell except that last one clickable, but is there a cleaner way?
If Dmitry's answer does not work.
Try calling the ng-change with enableProduct($event)
And within that function, call
function enableProduct($event) {
$event.stopPropagation();
...
}
I believe the <switch> handler should stop the event propagation. Try to return false from you ng-change handler. E.g.
ng-change="enableProduct(); return false"

angularjs remove Selected Items using splice Function

I was looking for a solution to remove items from the Grid; that's why I posted the question before. But when I got the solution from someone, at that time, I thought it solved the issue, but it was using a Filter method.
However, I want the items to be removed from the GRID using a Splice Function.
Here is my old Question Link
Angularjs, Applying Action on Selected Checkboxes in Table
I want it to execute using a Splice Function.
Right now the problem I am facing is to pass the index value to the function so that the item can be deleted if that index value is selected/fetched. I am not sure how to fix it.
It would be nice if someone solves the problem and gives a demo link to the updated code.
Here is the Plunker Link for what I have tried so far.Plunker link to show my execution
Definition of JS array.splice method (from MDN):
array.splice(index , howMany[, element1[, ...[, elementN]]])
So, your removefunction should be written as:
$scope.remove = function(index){
$scope.students.splice(index, 1);
};
DEMO PLUNKER
EDIT:
I figured you wanted to remove the items by clicking the "x" button with ng-click pointing to remove function.
To remove the items by clicking the checkbox you should set checkbox ngModel to a student property and than put a $watcher on students that would remove those students who have this property set to true:
<tr class="color2" ng-repeat="student in students | filter:search | filter:new_search">
<td>{{student.Rollno}} <input type="checkbox" ng-model="student.checked"> </td>
<td>{{student.Name}}</td>
<td>{{student.Uni}} <button ng-click="remove($index)">x </button></td>
</tr>
$scope.$watch('students', function(students){
if(!students){
return;
}
$scope.students = students.filter(function(student){
return !student.checked;
});
}, true);
PLNUKER
I have added ng-click to checkbox to make it working
http://plnkr.co/edit/DSVPj3holsf4nhNvEMbQ?p=preview

Categories

Resources