KnockoutJS: based on length of array enable button - javascript

In a project we're doing, we have created an inbox where the users (amongst other things) can select the items. If a user selects an item, the button should be enabled -- if none are selected, the button should be disabled.
Simple enough, but for the life of me, I can't get it working :-(
You can find a fiddle here: http://jsfiddle.net/rzrfp/
I presume I'm missing something very, very, VERY simple and stupid, but I've been tried virtually everything, and can't get it working ...

Use ko.computed instead of ko.computable.
Or even better: use data-bind="enable: selectedItems().length > 0" in your button element.
So you can omit the computed showButton.
EDIT: To use the right context use var modelImpl = new myModel("myParam");. Otherwise this inside the model refers to the window object.

Related

How to fill in Google Form's drop down and text inputs with Tampermonkey?

I am trying to automate an attendance form hosted by Google Forms, but the inputs aren't HTML <input> or <select> elements, so I am not sure how to change them other than manipulating the mouse and keyboard (an approach I used with Selenium).
Based off a fast peak; you could
let Form = document.querySelector('.freebirdFormviewerViewItemList');
let itemContainer = Form.querySelectorAll('.freebirdFormviewerViewNumberedItemContainer');
itemContainer.forEach((element)=>{
// Your code here, you should in theory be doing deeper loops depending on how advanced you want this.
});
Inside the loop we'd need to just find all the active inputs we want with a
itemContainer.forEach((element)=>{
if(element.querySelector('.exportOuterCircle')) {
console.log('we found ourselves a radio button but just one, we could go deeper with querySelector (and help of loops/etc)')
}
});
This is a bit of a large-task but not so bad, just make sure the freebirdFormviewerViewNumberedItemContainer class is correct every-form to or y ou find the pattern per-page that selects the questions for a fast loop through.
On loop, you're to query select one or more(if so apply another loop) to find the options you want. In this demo above radio button search, if the pages stay static you should with my example be able to grab/see a console pop-up no errors;
For setting these values, it's as easy in some cases setAttribute/value/ and other modifiers once selection is made. So you know click already and so the radio buttons be a good example. Any issues try navigating your elements in developer menu and sort if selections are going down correctly.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Appending a tail-select option maintaining the functionality

Created a select tag using jquery tail module: https://github.com/pytesNET/tail.select
I want to append a new option input taken from the user.
Using nodejs for this local server to automate file movement.
tail.select(".selectBox_custom",{placeholder:"Add custom"});
$("#idofselect")[0].options.add("New Option",true);
I expect to see the newly added option post this action. Whereas, the html source shows the new option but is not visible on tail select element on browser. Also, I don't believe that the functionality of multiple select is also added if somehow I could get the element to be displayed.
Also tried with following documentation, but could not get a clear demo:
https://github.com/pytesNET/tail.select/wiki/public-methods#addkey-value-group-selected-disabled-description-rebuild
As can be seen in documention you had provided:
This function will NOT rebuild the dropdown field, unless you pass
true as last argument!
So. it means that you have to provide true to your add() method call. Smth like this:
$("#idofselect")[0].options.add("New Option",true, false, false, false, '', true);
---==== EDIT ===---
I was able to add new option to tail select following documentation you had provided. I would suggest you to use for all select manipulations instance variable, it is going to save your debugging time and your code became more cleaner and readable. Here the sample fiddle.
Hellow,
It's not documented, but it's highly recommended to fill in the first both arguments on the options.add() method (so the key and value, even if it is the same). To update the dropdown field, you can use the tail.select.query() method on your own.
I wrote a small CodePen to demonstrate this.
Sincerely,
Sam, Developer of tail.select.

Javascript change the value of innerHTML or innerText not working

I am working on a form (which comes from the Laserfiche Forms application) and I am trying to change the text on a button that currently reads "Auto Fill" which is very non-descriptive since I have 5 of those buttons.
A little backstory: My code used to work and then all of a sudden one day it doesn't and creates an error where the user can only see the "Submit" button and the title of the form, but as soon as I comment out the below code the form works again but then I have those non-descriptive buttons again.
Is something wrong with my code?
document.getElementById("lookup1573").innerHTML = "Fill Section";
On button inspection, I see something a little odd:
<button id="lookup1573" class="autofill" type="button vo="d">Auto fill</button>
You had a typo in the html:
type="button vo="d"
This is the correct way:
<button id="lookup1573" class="autofill" type="button">Auto fill</button>
Here is the full example:
https://jsfiddle.net/o2er21v0/
That is not a typo but a customer parameter of Forms.
So here is the easy way to use these kind of things with forms:
Firstly, give all of your elements classes. Whilst outside of using Forms it is recommended to use ID's to reference your elements, doing that with Forms will give you more work, tenfold.
To note about Autofill buttons: they only appear on lookups that you have enabled them on (unless you are using an old version of Forms) and will appear next to the last element in your lookup (if that makes sense).
To change the name of your autofill buttons you are going to have to do so after the page has loaded.
Below is example code to do just that, assuming that the element that has the Autofill button you have given it a class of "vendorName".
The "vo" is actually very useful as you can use it to easily interact with your field content in conjunction with your classes. In the below example I am changing what is in the field without having to go into the code and work out what the number of the id is. This makes any code you make more portable as you can then implement it in other projects, projects where you ID numbers will be different. This is so flexible that it does not matter if the "vendorName" element is a normal text input, multi-line text area or a drop down menu as that same piece of code will work the same.
4:
$(function() {
$( ".vendorName .autofill").text( "Fill Section" );
});
5:
$( ".vendorName [vo]").val( "A New Vendor Name" );
Forms already uses the jQuery library so this will work just fine. Remember to give all of your elements a class (I usually name it the same as the variable). You can also give them multiple classes by separating the classes with a space.

How do I destroy all instances of Bootstrap Popover?

I have a single page app using Backbone, and whenever I over over something and then click the "back" button, the popover forever stays.
I want to destroy all instances of popover when a new instance is loaded.
Finding the popovers that are created through the data API is not difficult and has been covered in other answers like those of David Mulder and Amir Popovich. You just do:
$("[data-toggle='popover']").popover('hide');
Or you can use destroy if you need to or prefer to.
The challenge is to handle those popovers that are created dynamically.
Marking the Elements with Popovers
I would implement something like this. I'd override the default popover method and I'd try to perform this override as early as possible so that everything that needs a popover uses my override. What it does is just mark elements that use a popover with a class. Bootstrap does not mark them itself:
// Override popover so as to mark everything that uses a popover.
var old_popover = $.fn.popover;
function my_popover() {
this.addClass('marked-as-having-a-popover');
return old_popover.apply(this, arguments);
}
$.fn.popover = my_popover;
Then to clear everything before the unloading, I'd put in the code that detects the unloading the following:
$(".marked-as-having-a-popover").popover('hide');
Or it could use destroy rather than hide if testing shows that it works better for your use-case.
Now, the method above will work if the override happens early enough and you do not have a page where multiple jQueries are loaded. (Yep, this is possible.) I use something similar to deal with tooltips in one of my applications so I know the principle is sound. It so happens that in my app, all tooltips are created by my code so there is no risk of missing something.
Finding All Elements with Popovers, Even Unmarked
If you are in a situation where a popover can be created without being marked (I call this an "escapee"), then you need to query the whole DOM and find which elements have popovers. There is no shortcut here. You cannot rely on attributes like data-content because popovers can be created wholly dynamically (i.e. without any of the data- attributes). Also, all kinds of elements can get popovers, so you cannot reliably assume that only button elements will have a popover. The only surefire way to find everything that needs handling is to look at each element in the DOM and check whether it has a popover:
// Obviously this is quite expensive but in a situation where there *can* be escapees
// then you have to check all elements to see if they have a popover.
$("*").each(function () {
// Bootstrap sets a data field with key `bs.popover` on elements that have a popover.
// Note that there is no corresponding **HTML attribute** on the elements so we cannot
// perform a search by attribute.
var popover = $.data(this, "bs.popover");
if (popover)
$(this).popover('hide');
});
Again, destroy could be used rather than hide.
Proof of Concept
Here is a fiddle that illustrates the entire thing:
"Add a Dynamic Popover" simulates code that would add a popover when the override is in effect.
"Add an Escapee" simulates code that would add a popover and somehow manage to use the original Bootstrap code.
"Clear Marked" clears only the marked popovers.
"Clear All" clears every single popover marked or not.
try with this:
$('YOUR_ELEMENT_SELECTOR').popover('dispose');
reference url: https://getbootstrap.com/docs/4.1/components/popovers/
Its very simple, just you have to call one function popover() with argument "destroy" to destroy the popover. It will destroy all popovers which is created by $("[data-toggle=popover]").popover();
you can check documentation for more options and arguments of popover().
I suggest you to destroy popovers with having specific class name instead of using following code.
$("[data-toggle='popover']").popover('destroy');
The above code will destroy all popovers in the page. So instead of this, use class selector.
$(".YourClassName").popover('destroy');
If you have problems and need to remove all for sure:
$('.popover').remove();
will help (Popover automatic add this class, even for dynamicly created objects). It destroys all the popover DOM-Object incl. callbacks, etc.
But thats the rough way. Typically I displose all by popover class (clean way) and to be sure I do a hard clean up after. Works for me fine!
$('.popover').popover('dispose');
$('.popover').remove();
If you like to remove all execpt one, use a filter() with :not-Selector
$('.popover').filter(':not(#yourID)').popover('dispose');
$('.popover').filter(':not(#yourID)').remove();
popover adds also a id with a random number
#popoverxxxxx where xxxxx is a five digit number.
this helps sometimes to compare popovers. Of cause this could also be used to identify the popovers.
Something generic like this (assuming you're using data-bindings) should do the trick:
$('[data-toggle="popover"]').popover('hide')
or the more extreme call
$('[data-toggle="popover"]').popover('destroy')
though I doubt that would make sense often. Still to address the specific bug you're encountering you should create a minimal test case so that that bug itself can be addressed.
Oh and if you specifically want to check for open popovers you can use .data("bs.popover").$tip.parent().length (which is a bit of an hack), for example:
$('[data-toggle="popover"]:eq(0)').data("bs.popover").$tip.parent().length == 1
You can hide all popovers by using this:
$("[data-toggle='popover']").popover('hide');
You can destroy all popovers by using this:
$("[data-toggle='popover']").popover('destroy');
The difference between hide and destory is that when you hide a popover you do not need to reactive it, but when you destroy it you do.
Check out my JSFIDDLE and then:
Click on all popovers and then click hide. After clicking hide you can click on the popovers again.
Click on all popovers and then click destroy. After clicking destroy try clicking on the popovers again and see that nothing will happen since they are destroyed. In order to make them functional again, you will need to click on reactive and then try.
Popovers must be initialized manually, so you know exactly what you have to destroy because you did initialize it.
You should just call the destroy function with the same selector.
Or maybe I am missing something ?

Updating script to run for newly created table rows with incremented IDs

I've got a table with the type ahead feature from jQuery UI. It is working with my form when there is only 1 table row (initial view). There's a button to allow the user to create additional table rows as required which also increments the IDs for the text inputs and select menus.
There's another script that inserts a matching value into the select menu based on the typeahead selection. Both of these work fine for the first row, but stop working for any additional Rows that are created.
I've setup a sample JSFiddle:
http://jsfiddle.net/fmdataweb/hxzME/1/
I think I understand why they only work for the first row - they are tied to these IDs: #lastYearSelect1 and #nextYearSelect1 - but I'm not sure how to change them so they then work with #lastYearSelect2, #nextYearSelect2, #lastYearSelect3, #nextYearSelect3 and so on.
There's a few problems with the script.
Firstly you're right, you need to setup all the scaffolding again after you clone the row, the clone method will not copy the functionality, just the html elements.
To find the right element you can use the JQuery ^= selector, which matches the start of an attribute name, on the on the clone object to find the right child input to turn into an autocomplete field. You can do the same trick in the function to change the dropdown to the correct function.
Finally a lot of your code and variables were in the wrong scope to be accessible properly. I've moved a lot of the vars around so they're accessible, mainly into the global scope. When you're a bit more experienced you won't want to do this, but for now this is fine.
I also created a new function setDropDown, but this code is almost identical to what was there before.
Here is a working version of your code:
http://jsfiddle.net/hxzME/3/
Add classes to elements and use class selectors when binding an event handlers.

Categories

Resources