I have a web page that I'd like to automate with a bookmarklet.
It has a drop-down that lets the user select time range types: minutes, hours, days. I want to select Days in the bookmarklet code, but I don't know how to go about these data-bind
attributes in knockout:
The HTML looks like this:
<span class="btn-group">
<button class="dropdown-toggle" tabindex="-1" data-bind="disable: settings.disabled">
<span data-bind="text: settings.offsetUnits">Days</span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" data-bind="foreach: settings.offsetUnitsChoices">
<li><a tabindex="-1" href="#" data-bind="text: $data, click: $parent.selectUnits">Minutes</a></li>
<li><a tabindex="-1" href="#" data-bind="text: $data, click: $parent.selectUnits">Hours</a></li>
<li><a tabindex="-1" href="#" data-bind="text: $data, click: $parent.selectUnits">Days</a></li>
</ul>
</span>
If you fire a jquery click event on the element in the list you would like to select it will trigger the $parent.selectUnits function, which should select the element. See an example below.
$('ul > li:nth-child(6) > a').click()
var pageViewModel = {
selectUnits: function(itemClicked) {
alert(`You selected ${itemClicked}`);
pageViewModel.settings.offsetUnits(itemClicked);
},
settings: {
offsetUnits: ko.observable(0),
offsetUnitsChoices: [5, 15, 30, 45]
}
};
ko.applyBindings(pageViewModel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="btn-group">
<button class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span data-bind="text: `${settings.offsetUnits()} Units`"></span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" data-bind="foreach: settings.offsetUnitsChoices">
<li><a href="#" data-bind="text: `${$data} Minutes`, click: $parent.selectUnits"></a></li>
<li><a href="#" data-bind="text: `${$data} Hours`, click: $parent.selectUnits"></a></li>
<li><a href="#" data-bind="text: `${$data} Days`, click: $parent.selectUnits"></a></li>
</ul>
</span>
<a href="javascript:$('ul > li:nth-child(6) > a').click()">My bookmark to select the 6th item in the dropdown</a>