Adding buttons to the interface - toloka

I'd like add a button and let performers to copy some text to their clipboard once they click on the button. However, I found:
the element interface { {button}} does not accept an "on-click" property
the original html button tag may work, but when I add the the function to the on_click property and the js section, the page returns the error "the function does not found".
So, my question is, how I can add a user defined js function to a project? Is there any example code/project I can reference to?

Try to add the following code in TASK INTERFACE in your project:
<div>
{{field type="input" name="whatever" value=link size="L" width="70%"}}
{{button label="Copy text to clipboard" href="#" size="L"}}
</div>
<textarea class="hiddenInput"></textarea>
in onRender() in JS field:
onRender: function() {
var _document = this.getDOMElement(),
button = _document.querySelector('.button'),
hiddenInput = _document.querySelector('.hiddenInput'),
task = this;
button.addEventListener('click',function (e) {
e.preventDefault();
hiddenInput.value = task.getTask().input_values.link;
/*hiddenInput.focus();*/
hiddenInput.click();
hiddenInput.select();
document.execCommand('copy');
button.classList.add('button_disabled');
button.querySelector('.button__label').textContent = 'Done';
setTimeout(function () {
button.classList.remove('button_disabled');
button.querySelector('.button__label').textContent = 'Copy text to clipboard';
},1000)
})
},

Related

Insert custom button on Insert/Edit Link dialog?

I want to add a custom button on the Insert/Edit Link dialog/popup in tinymce v5.
I only got this code for the setup option where I put in call to a function.
function tinyMceEditLink(editor) {
console.log("tinyMceEditLink");
editor.on("click", function(e) {
console.log("this click");
});
}
I'll be the first to admit this is a bit hacky, but you could try:
function tinyMceEditLink(editor) {
editor.windowManager.oldOpen = editor.windowManager.open; // save for later
editor.windowManager.open = function (t, r) { // replace with our own function
var modal = this.oldOpen.apply(this, [t, r]); // call original
if (t.title === "Insert/Edit Link") {
$('.tox-dialog__footer-end').append(
'<button title="Custom button" type="button" data-alloy-tabstop="true" tabindex="-1" class="tox-button" id="custom_button">Custom button</button>'
);
$('#custom_button').on('click', function () {
//Replace this with your custom function
console.log('Running custom function')
});
}
return modal; // Template plugin is dependent on this return value
};
}
This will give you the following result:
Setup:
tinymce.init({
selector: "#mytextarea", // change this value according to your HTML
plugins: "link",
menubar: "insert",
toolbar: "link",
setup: function(editor) {
// Register our custom button callback function
editor.on('init',function(e) {
tinyMceEditLink(editor);
});
// Register some other event callbacks...
editor.on('click', function (e) {
console.log('Editor was clicked');
});
editor.on('keyup', function (e) {
console.log('Someone typed something');
});
}
});
Tips:
You can replace $('.tox-dialog__footer-end')... with $('.tox-dialog__footer-start')... if you want your button on the left hand side of the footer.
This currently works on the default skin, changes to .tox-dialog__footer class could break this.
Any updates to the library that change the title "Insert/Edit Link" will break this.
The above example requires jQuery to work.
This is a bare minimum example. Use the configuration guide to customize the toolbar, setup events etc.

Clearing form input in Meteor

I have tried multiple options that I have found on SO and elsewhere for clearing form inputs, all listed below in the code, but nothing seems to work. Is there anything specific about this form that would determine which one I should use?
<template name="CompanyAdd">
<div>
<form class="form-inline">
<div class="form-group">
{{> inputAutocomplete settings=companySettings id="companyAdd" name="companyAdd" class="input-xlarge" autocomplete="off" placeholder="Add Company"}}
</div>
<button type="submit" class="btn btn-default company-add">Add</button>
</form>
</div>
</template
Template.CompanyAdd.events({
'submit form': function(e) {
e.preventDefault();
var selection = $(e.target).find('[id=companyAdd]').val();
var company = {
ticker: selection
};
if(Companies.findOne({ticker:selection})) {
console.log("Do nothing");
} else {
Meteor.call('companyAdd', company, function(error, result) {
});
}
//event.target.reset();
//e.target.reset();
//target.text.value = '';
//template.find("form").reset();
//document.getElementById("companyAdd").reset();
}
});
Given that you have
var selection = $(e.target).find('[id=companyAdd]').val();
That is the input you want to clear and that - I assume - works, I would do:
var field = $(e.target).find('[id=companyAdd]');
var selection = field.val();
...
field.val('')
Otherwise if you wish to reset all form, go for #JeremyK`s #reset.
Your second attempt:
e.target.reset();
should work fine. If it is not working, check if there are any errors in the console and report back here.
The handler function receives two arguments: event, an object with
information about the event, and template, a template instance for the
template where the handler is defined.
In your code above you define your handler like this:
'submit form': function(e) {
You have named the event argument e, and discarded the template argument.
e is has information about the event
e.target is the form element (The event was defined on 'submit form')
e.target.reset succeeds because reset is a valid function to call on a form.
Briefly, your other attempts failed because:
event.target.reset(); event is not defined or passed in, at least not with the name event (you used e)
target.text.value = ''; target is an undefined variable
template.find("form").reset(); this fails because template is undefined. If you change your handler definition to receive the template variable, this will work (change 'submit form': function(e) to 'submit form': function(e, template)
document.getElementById("companyAdd").reset(); This fails because the element with the id companyAdd is the input element, not the form, so .reset() is undefined. You could change this to document.getElementById("companyAdd").text.value = ''

trigger a href sip/tel link on button click jquery

I'm trying to trigger a click event that will open my href sip/tel link when user clicks the button, but it doesn't trigger the click event after the button has been pressed.
jquery code:
$('#next_button').click(function() {
var num = $(this).val();
$('#call-num'+num).trigger('click');
alert(num);
});
href code:
(999) 888-3333
<button id="next_button" value="1">Next</button>
$('#next_button').on('click', function() {
var num = $(this).val();
var call = $('#call-num'+num).attr('href');
location.href = call;
alert(call);
});

Angular app wont load (JSFiddle)

I have a simple angular app here
<div ng-app="WhereToMeet" ng-controller="MapCtrl">
<leaflet shape="shape"></leaflet>
<button ng-click="clicked()">Clicked</button>
</div>
app = angular.module("WhereToMeet", [])
app.directive "leaflet", ->
restrict: "E"
replace: true
transclude: true
template: "<div id=\"map\"></div>"
scope:
shape: "=shape"
link: (scope, element, attrs, ctrl) ->
scope.$watch attrs.shape,( (newValue, oldValue) ->
watched newValue
), true
watched = (newValue) ->
alert newValue
#MapCtrl = ($scope) ->
clicked = (clicked) ->
$scope.shape = "Clicked"
alert "clicked"
I have it in a JSFiddle http://jsfiddle.net/charliedavi/bezFB/22/ but it wont run. Really odd. I think its an error with my coffee script but I can not see it
error:
Uncaught SyntaxError: Unexpected string fiddle.jshell.net:22
Uncaught Error: No module: WhereToMeet
in pure JS
var app;
app = angular.module("WhereToMeet", []);
app.directive("leaflet", function() {
var watched;
({
restrict: "E",
replace: true,
transclude: true,
template: "<div id=\"map\"></div>",
scope: {
shape: "=shape"
},
link: function(scope, element, attrs, ctrl) {
return scope.$watch(attrs.shape, (function(newValue, oldValue) {
return watched(newValue);
}), true);
}
});
return watched = function(newValue) {
return alert(newValue);
};
});
this.MapCtrl = function($scope) {
var clicked;
return clicked = function(clicked) {
$scope.shape = "Clicked";
return alert("clicked");
};
};
http://jsfiddle.net/charliedavi/gsPx3/2/
i dont know coffee script but angular. i just tried to solve it. ;-)
Select no-wrap body, under select framework
Select no-library(pure-js)
Add angular js as resources
Manually initialize angular using this angular bootstrap
angular.bootstrap document, ['WhereToMeet']
The generated javascript code is in another scope. You have to solve this
by either adding the -b parameter to the coffeescript compiler or export your function
explicitly via
root = exports ? this
root.clicked = ->
alert "clicked"
$scope.shape = "Clicked"
It is working now Fiddle Here
I had a similar issue with jsfiddle and angular yesterday. I had to do a couple of things to make it work:
Jsfiddle is adding the tags for html and body, so just write the markup that should end up inside the body tag.
Add a wrapping div with ng-app="myApp" instead of trying to specify another html-tag
Select no-wrap body, under select framework
I don't know what your "leaflet" is doing but I have updated your fiddle so that the click will trigger an alert
I've had to change the how the controller is instantiated to get the onclick to work.
http://jsfiddle.net/t9nsY/2/
app.controller("MapCtrl", function ($scope) {
$scope.clicked = function (clicked) {
console.log("clicked");
$scope.shape = "Clicked";
return alert("clicked");
};
});

Google Autocomplete - enter to select

I have Google Autocomplete set up for a text field of an HTML form, and it's working perfectly.
However, when the list of suggestions appear, and you use the arrows to scroll and select using enter, it submits the form, though there are still boxes to fill in. If you click to select a suggestion it works fine, but pressing enter submits.
How can I control this? How can I stop enter from submitting the form, and instead be the selection of a suggestion from autocomplete?
Thanks!
{S}
You can use preventDefault to stop the form being submitted when enter is hit, I used something like this:
var input = document.getElementById('inputId');
google.maps.event.addDomListener(input, 'keydown', function(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
});
Using the Google events handling seems like the proper solution but it's not working for me. This jQuery solution is working for me:
$('#inputId').keydown(function (e) {
if (e.which == 13 && $('.pac-container:visible').length) return false;
});
.pac-container is the div that holds the Autocomplete matches. The idea is that when the matches are visible, the Enter key will just choose the active match. But when the matches are hidden (i.e. a place has been chosen) it will submit the form.
I've amalgamated the first two answers from #sren and #mmalone to produce this:
var input= document.getElementById('inputId');
google.maps.event.addDomListener(input, 'keydown', function(e) {
if (e.keyCode == 13 && $('.pac-container:visible').length) {
e.preventDefault();
}
});
works perfectly on the page. prevents the form from being submitted when the suggestion container (.pac-container) is visible. So now, an option from the autocomplete dropdown is selected when the users presses the enter key, and they have to press it again to submit the form.
My main reason for using this workaround is because I found that if the form is sent as soon as an option is selected, via the enter key, the latitude and longitude values were not being passed fast enough into their hidden form elements.
All credit to the original answers.
This one worked for me:
google.maps.event.addDomListener(input, 'keydown', e => {
// If it's Enter
if (e.keyCode === 13) {
// Select all Google's dropdown DOM nodes (can be multiple)
const googleDOMNodes = document.getElementsByClassName('pac-container');
// Check if any of them are visible (using ES6 here for conciseness)
const googleDOMNodeIsVisible = (
Array.from(googleDOMNodes).some(node => node.offsetParent !== null)
);
// If one is visible - preventDefault
if (googleDOMNodeIsVisible) e.preventDefault();
}
});
Can be easily converted from ES6 to any browser-compatible code.
The problem I had with #sren's answer was that it blocks the submit event always. I liked #mmalone's answer but it behaved randomly, as in sometimes when I hit ENTER to select the location, the handler ran after the container is hidden. So, here's what I ended up doing
var location_being_changed,
input = document.getElementById("js-my-input"),
autocomplete = new google.maps.places.Autocomplete(input),
onPlaceChange = function () {
location_being_changed = false;
};
google.maps.event.addListener( this.autocomplete,
'place_changed',
onPlaceChange );
google.maps.event.addDomListener(input, 'keydown', function (e) {
if (e.keyCode === 13) {
if (location_being_changed) {
e.preventDefault();
e.stopPropagation();
}
} else {
// means the user is probably typing
location_being_changed = true;
}
});
// Form Submit Handler
$('.js-my-form').on('submit', function (e) {
e.preventDefault();
$('.js-display').text("Yay form got submitted");
});
<p class="js-display"></p>
<form class="js-my-form">
<input type="text" id="js-my-input" />
<button type="submit">Submit</button>
</form>
<!-- External Libraries -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
The flag ensures that if the location is being changed & user hits enter, the event is blocked. Eventually the flag is set to false by google map's place_changed event, which then allows the form to be submitted on hitting the enter key.
Here's a simple code that worked well for me (uses no jquery).
const googleAutcompleteField = this.renderer.selectRootElement(this.elem.nativeElement);
this.selectOnEnter(googleAutcompleteField);
This piece of code, to follow the code above, is used to implement google maps autocomplete (with or without the Enter key functionality sought in this question):
this.autocomplete = new google.maps.places.Autocomplete(googleAutcompleteField, this.googleMapsOptions);
this.autocomplete.setFields(['address_component', 'formatted_address', 'geometry']);
this.autocomplete.addListener('place_changed', () => {
this.zone.run(() => {
this.googleMapsData.emit([this.autocomplete.getPlace()]);
})
})
selectOnEnter (called above in the first piece of code) defined:
selectOnEnter(inputField) {
inputField.addEventListener("keydown", (event) => {
const selectedItem = document.getElementsByClassName('pac-item-selected');
if (event.key == "Enter" && selectedItem.length != 0) {
event.preventDefault();
}
})
}
This code makes the google maps autocomplete field select whichever item user selects with the down arrow keypress. Once user selects an option with a press of the Enter key, nothing happens. User has to press Enter again to trigger onSubmit() or other command
You can do it in vanilla :
element.addEventListener('keydown', function(e) {
const gPlaceChoices = document.querySelector('.pac-container')
// No choices element ?
if (null === gPlaceChoices) {
return
}
// Get choices visivility
let visibility = window.getComputedStyle(gPlaceChoices).display
// In this case, enter key will do nothing
if ('none' !== visibility && e.keyCode === 13) {
e.preventDefault();
}
})
I tweaked Alex's code, because it broke in the browser. This works perfect for me:
google.maps.event.addDomListener(
document.getElementById('YOUR_ELEMENT_ID'),
'keydown',
function(e) {
// If it's Enter
if (e.keyCode === 13) {
// Select all Google's dropdown DOM nodes (can be multiple)
const googleDOMNodes = document.getElementsByClassName('pac-container');
//If multiple nodes, prevent form submit.
if (googleDOMNodes.length > 0){
e.preventDefault();
}
//Remove Google's drop down elements, so that future form submit requests work.
removeElementsByClass('pac-container');
}
}
);
function removeElementsByClass(className){
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
I've tried the above short answers but they didn't work for me, and the long answers I didn't want to try them, so I've created the following code which worked pretty well for me. See Demo
Suppose this is your form:
<form action="" method="">
<input type="text" name="place" id="google-places-searchbox" placeholder="Enter place name"><br><br>
<input type="text" name="field-1" placeholder="Field 1"><br><br>
<input type="text" name="field-2" placeholder="Field 2"><br><br>
<button type="submit">Submit</button>
</form>
Then the following javascript code will solve the problem:
var placesSearchbox = $("#google-places-searchbox");
placesSearchbox.on("focus blur", function() {
$(this).closest("form").toggleClass('prevent_submit');
});
placesSearchbox.closest("form").on("submit", function(e) {
if (placesSearchbox.closest("form").hasClass('prevent_submit')) {
e.preventDefault();
return false;
}
});
And here is how the full code looks like in the HTML page (Note that you need to replace the YOUR_API_KEY with your google api key):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Prevent form submission when choosing a place from google places autocomplete searchbox</title>
</head>
<body>
<form action="" method="">
<input type="text" name="place" id="google-places-searchbox" placeholder="Enter place name"><br><br>
<input type="text" name="field-1" placeholder="Field 1"><br><br>
<input type="text" name="field-2" placeholder="Field 2"><br><br>
<button type="submit">Submit</button>
</form>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Google Maps -->
<!-- Note that you need to replace the next YOUR_API_KEY with your api key -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"
async defer></script>
<script>
var input = document.getElementById("google-places-searchbox");
var searchBox = new google.maps.places.SearchBox(input);
var placesSearchbox = $("#google-places-searchbox");
placesSearchbox.on("focus blur", function() {
$(this).closest("form").toggleClass('prevent_submit');
});
placesSearchbox.closest("form").on("submit", function(e) {
if (placesSearchbox.closest("form").hasClass('prevent_submit')) {
e.preventDefault();
return false;
}
});
</script>
</body>
</html>
$("#myinput").on("keydown", function(e) {
if (e.which == 13) {
if($(".pac-item").length>0)
{
$(".pac-item-selected").trigger("click");
}
}
Use $('.pac-item:first').trigger('click'); if you want to select first result