function is not defined when I click on a button - javascript

I generate modal forms using function function makeModalEnroll(name, description, i, id)
And in one of my lines there is a string
modal += '<button type="button" id="enroll' + i + '" class="btn btn-success" data-dismiss="modal" onclick="send(this.id);"> Enroll <span class="glyphicon glyphicon-arrow-right"></span> </button>';
I've got function send and for now I submit form with id = 0
function send(id) {
alert(id);
var c = id.charAt(id.length - 1);
alert(c);
$('#enrollForm0').ajaxSubmit({url: 'enroll.html', type: 'post'});
};
But browser says that ReferenceError: send is not defined.
I tried to put function send before and after function makeModalEnroll but this error is always occurs.
How to solve this problem?

May be you don't expose your function to the global scope, try this:
window.send = function(id) {
alert(id);
var c = id.charAt(id.length - 1);
alert(c);
$('#enrollForm0').ajaxSubmit({url: 'enroll.html', type: 'post'});
};

Related

Find and Click button with JS

I'm trying to use a chrome extension (shortkeys) to create shortcut keys that can press buttons within our warehouse management system (so they can be matched to barcodes).
One of the buttons has no ID, and once it has been clicked the button innertext changes. Ideally I'd like the shortcut to work on either version of the button
It is either
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
or
<a class="btn btn-success" href="/Order/OrderDocumentP/15467" target="_blank">Print Label</a>
I then have another button to be assigned to a different shortcut key
<a class="btn btn-success" href="/Picking/DespatchOrder?OrderId=13413">Despatch</a>
But I'm sure once I've figured out the first one the next will be easier :)
Any help greatly appreciated, I've been through a number of other questions that are similar but not quite what I'm after and my JS knowledge is pretty rubbish
Learn CSS a bit and use https://developer.mozilla.org/ru/docs/Web/API/Document/querySelector
Your extensions probaply supports that
// cuz I don't like to type long "document.querySelector"
q = sel => document.querySelector(sel)
qq = sel => document.querySelectorAll(sel)
function clickOnly(sel) {
let list = qq(sel);
if (list.length == 1) list[0].click();
else alert('element "'+sel+'" is not unique!');
}
// handles *any* keypress
onkeypress = function (event) {
if (event.target.tagName == "INPUT") return; // noop on input focused
if (event.target.tagName == "TEXTAREA") return; // noop on input focused
console.log(event.code); // to see what the key is
let rawCode = event.code; // keyboard key, `KeyM` for M, `Digit7` for 7, `Slash` for /
let code = rawCode; // make CtrlAltShiftKeyM
if (event.shiftKey) code = 'Shift' + code;
if (event.altKey) code = 'Alt' + code;
if (event.ctrlKey) code = 'Ctrl' + code;
if (!kds[event.code]) return;
event.preventDefault(); // prevent CtrlKeyM browser handler for bookmarks or whatever
kds[event.code](event);
}
kds = {}
// it's a function so starts with `() => `
kds.KeyM = () => alert('it works!')
// a is for <a>, [href^=] is for href starts with
kds.ShiftKeyM = () => clickOnly('a[href^="/Order/OrderDocumentP/]')
// , is for one of multiple selectors
kds.CtrlKeyM = () => clickOnly('input[value="Create Shipment"], a[href^="/Order/OrderDocumentP/]')
This is a simple script on getting a button by class name and clicking it. I think this is what you are looking for, if not let me know I will rewrite it.
EDIT: I added a loop that will click all buttons or links found with the class name btn-success
I've inserted a second function so people looking for a solution by classname can also still find the first one. AutoClickBtnByValue() will click the button with inner text "click me now".
function AutoClickBtn() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
button[i].click();
console.log('Success! Clicked button' + i);
}
}
setInterval(AutoClickBtn, 2000);
/* Click button by innerHTML text */
function AutoClickBtnByValue() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
if (button[i].innerHTML.indexOf('click me now') > -1) {
button[i].click();
console.log('Success! Clicked button' + i + ' with value: "click me now" ');
}
}
}
setInterval(AutoClickBtnByValue, 2000);
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
<a class="btn btn-success" href="#" target="_blank">Print Label</a>
<a class="btn btn-success" href="#">Despatch</a>
<button class="btn-success">click me now</button>

Bootstrap Confirmation data-on-confirm not executing function

I'm trying to make a delete confirmation execute a function that deletes the current id data.
I am getting this error:
Uncaught TypeError: Cannot read property 'call' of undefined
in this part of the bootstrap-confirmation.js
return function() {
context[func].call(this);
};
this is my button code
<button class="btn btn-danger" data-toggle="confirmation"
data- btn-ok- class="btn-danger" data-btn-cancel-icon="glyphicon
glyphicon-ban-circle" data-btn-cancel-class="btn-default"
data-popout="true" data-singleton="true" data-on-confirm="goDel(id)">
Eliminar</button>
this is my Javascript
<script type="text/javascript">
function goDel(id)
{
location.href="./delete/" + id;
}
</script>
this is my delete controller
public function delete($id) {
$clientes = new Clientes();
$codcta = new Codcta();
$this -> codcta = $codcta -> find();
$codciu = new Codciu();
$this -> codciu = $codciu -> find();
$clientes = new clientes();
if ($clientes->delete((int)$id)) {
Flash::valid('El registro se ha eliminado correctamente');
}else{
Flash::error('Falló Operación');
}
return Redirect::to();
}
Change this in your button:
data-on-confirm="goDel"
and add this:
data-id="YOUR-ID-HERE"
in your javascript function:
function goDel()
{
var id = $(this)[0].getAttribute('data-id');
location.href="./delete/" + id;
}
Good Luck!
The button code in HTML will be:
<button class="btn btn-danger" data-toggle="confirmation" data-title="Title here" data-content="Content here" data-btn-cancel-icon="glyphicon
glyphicon-ban-circle" data-btn-cancel-class="btn-default"
data-popout="true" data-singleton="true" data-on-confirm="deleteMethodName" data-id="your-deleted-id-here">Eliminar</button>
The javascript function code will be:
function deleteMethodName()
{
var id = $(this)[0].getAttribute('data-id');
//Now you will get ID from above and use it as you like
}

Declare function inside scope and call it later

Calling the callService function fails. Instead none of my console messages are showing in the console except for 'making a controller....'. I'm using the directive ng-click="callService()" to make the call from an HTML button. I'm new to angular, can someone point me in the right direction? Code is below.
(function() {
console.log('making a controller....');
'use strict';
angular.module('myModule').controller('myController', myController);
myController.$inject = ['$scope','$http'];
function myController($scope, $http) {
console.log("controller initialized...");
$scope.callService = function(){
console.log("callService called...");
var urlSearchService = 'http://domain/proj/rs/stuff/moreStuff';
var skuVal = $scope.skuField;
var mVenVal = $scope.mVendorField;
//need to somehow specifiy that xml is a #FormParam
var xmlItemSearchRequest = "<ItemSearchRequest>"
+"<skuid>" + skuVal + "</skuid>"
+"<mvendor>" + mVenVal + "</mvendor>"
+"</ItemSearchRequest>";
console.log('calling: ' + urlSearchService + 'sending xml: ' + xmlItemSearchRequest);
$http.post(urlSearchService, xmlItemSearchRequest).
success(function(data){
$scope.searchResults = data;
console.log('call to ' + urlSearchService + ", was a success.");
}).error(function(data, status) {
console.error('Calling error', status, data);
});
};
};
})();
You are declaring the callService function inside the scope of the controller function, so it won't be accessible from the $scope. You need to add it to the $scope in order to be able to use it in your templates.
Instead of:
var callService = function(){
Do:
$scope.callService = function(){
As per your latest comment, you are not binding correctly the controller.
This:
<div data-ng-controller="inventorySearchController"><input type="button" class="btn btn-primary btn-lg" ng-click="callService()" value="Search" /></div> –
Should be:
<div data-ng-controller="myController"><input type="button" class="btn btn-primary btn-lg" ng-click="callService()" value="Search" /></div> –

JQuery Button Data Returning As Null?

I have a button and when I click it, I want the html object (aka button) to be passed as a parameter to another javascript function. I want the javascript function to print the data-hi from the element in the button.
HTML BUTTON
<button type = "button" onclick = "whoIsRdns(this)" class="dns-information btn btn-xs btn-info pull-right" data-toggle="modal" data-target = "#whois_rdns_modal" data-path="{{ path( '_who_is_rdns', { 'peer': peer.number, 'ip': peer.mac } ) }}" data-hi = "hi2">
<i class="icon-search"></i>
</button>
JS FUNCTION(W/ JQUERY)
function whoIsRdns(thisButton){
//Enable jQuery properties from the param of the HTML object
var btn = $(thisButton);
var test = btn.data('hi');
console.log('Value is ' + test);
}
Why would test return as null?
Shouldn't var btn = $("thisButton"); be var btn = $(thisButton); (without quotes)
Just a typo
$("thisButton") !== $(thisButton);
drop the quotes so you are not looking for an element with a tag name thisButton
var btn = $("thisButton");
needs to be
var btn = $(thisButton);

How to get file selection complete event in angularJS

Currently this is How brand list page looks like.
when user clicks on Pick Image button, i set updateMode=1, making delete and upload button visible.
Problem is sometime user does not select a image after clicking upload button, instead press cancel in file selection window. that time also delete and upload button becomes visible. I want to avoid that.
Also when user clicks on delete i want input text to become empty.
This is my HTML code.
<tr ng-repeat="b in Brands | filter:SearchText |orderBy:'name'">
<td>
<span data-ng-hide="editMode">{{b.name}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="b.name" data-ng-required />
<input type="text" data-ng-show="editMode" data-ng-model="b.image" data-ng-required />
<br><br>
<input type="text" ng-model="b.files[0].name" readonly="readonly">
<button ngf-select ng-model="b.files" class="btn btn-success btn-sm" ng-click="uploadMode=1">
<span class="glyphicon glyphicon-picture"></span> Pick Image
</button>
<button data-ng-hide="!uploadMode" class="btn btn-danger btn-sm" ng-click="uploadMode=0">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
<button data-ng-hide="!uploadMode" class="btn btn-info btn-sm" ng-click="upload(b.files, b.image)">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
</td>
<td><img src="http://localhost/{{ b.image }}" alt="" border=3 height=75 width=75><br><br>
</td>
and this is file upload code.
$scope.upload = function (files, path) {
//alert ('upload');
//alert (path);
//alert (files);
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
Upload.upload({
url: '/cgi-bin/upload.pl',
fields: {
'FilePath': path
},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$scope.log = 'progress: ' + progressPercentage + '% ' +
evt.config.file.name + '\n' + $scope.log;
}).success(function (data, status, headers, config) {
$timeout(function() {
$scope.log = 'file: ' + config.file.name + ', Response: ' + JSON.stringify(data) + '\n' + $scope.log;
});
})
.error(function (data, status, headers, config) {
alert ('Error');
});
}
}
};
what changes i should made to get above said functionality.
please help.
You'll need to use ngf-change available in ng-file-upload plugin
Instead of the ng-click , change it to the ngf-change in the HTML markup
<button ngf-select ng-model="b.files" ngf-change="fileSelected($files, $event, b)">
<span class="glyphicon glyphicon-picture"></span> Pick Image
</button>
Pass along the ng-repeat object as the 3rd parameter to the fileSelected function , and in the controller defined it as
$scope.fileSelected = function(files, events, b) {
if (files.length) {
b.uploadMode = true;
} else {
b.uploadMode = false;
}
};
Here we check whether files object is empty or not (Note: ngf-change gets called when the file selection dialog opens and on successful file selection) and set the uploadMode parameter as true or false.
For the delete file functionality , create a function which gets called on the click of Delete button and pass along the ng-repeat object
<button ng-if="b.uploadMode" ng-click="removefile(b)">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
In the controller , defined the removefile function , where you delete the files object
$scope.removefile = function(b) {
delete b.files;
b.uploadMode = false;
};
See working demo at http://plnkr.co/edit/zmZwiqJOLVILaCmc4uBQ?p=preview

Categories

Resources