Making button action on click on select2 js - javascript

i'm really looking for any kind of direction or help, in my code below, what kind of way i can do to make an action when the button "Add new item" is clicked.
$('#my_select').select2({
placeholder: 'Name',
tags : true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append("<button class='add btn btn-secondary btn-sm ml-10'> + Add New Item</button>")
}
return $result;
},
});
thank's.

I see two approaches here:
You can assign pass onclick attribute to the button directly
Pass an id to the button, and attach a click event to the id using jQUery

Related

Using data attributes with jquery.confirm.js

I'm trying to utilise the jquery.confirm script. It's all firing as expected but I'm trying to use custom data attributes that are passed into a controller elsewhere on the site, but I'm getting the error of undefined.
<a class="confirmMemberDelete" data-title="Mr Goose" data-user="CON-000132456" data-username="Mr Goose" href="#">
$(".confirmMemberDelete").confirm({
text: "Are you sure that you wish to delete this user?",
confirm: function (button) {
var conNum = $(this).attr('data-user');
var conName = $(this).attr('data-username');
alert("You just confirmed.");
alert($(this).attr('data-user'));
},
cancel: function (button) {
alert("You aborted the operation.");
},
confirmButton: "Yes I am",
cancelButton: "No"
});
The two custom data attributes are data-user and data-username. data-title is used by the confirm script as a title for the confirmation box.
I can't find any documentation online so any help would be marvellous.
Still not fixed in version 3.3.4, but I'm able to extract the data attributes the following way.
<a class="confirmMemberDelete" data-title="Mr Goose" data-user="CON-000132456" data-username="Mr Goose" href="#">
$('.confirmMemberDelete').confirm({
title: 'Make this my profile picture',
buttons: {
ok: function () {
let user = $(this)[0].$target[0].dataset.user;
let username = $(this)[0].$target[0].dataset.username;
console.log(user, username);
},
cancel: function () {
}
}
});
Check out this fiddle

Bootstrap Dialog (nakupanda) getting form values [JSFiddle]

I've trouble getting values out of my form.
I'm using bootstrap dialog from nakupanda (http://nakupanda.github.io/bootstrap3-dialog/)
The dialog (it is in a fullcalendar select function)
http://arshaw.com/fullcalendar/docs/selection/select_callback/
var form = $('#createEventForm').html();
BootstrapDialog.show({
message: form,
buttons: [{
label: 'Enkel rooster event',
action: function(dialogItself){
console.log('enkel - create')
dialogItself.close();
}
},{
label: 'Herhalend rooster event (elke dag)',
action: function(dialogItself){
console.log('meer - create')
dialogItself.close();
}
},{
label: 'Close',
action: function(dialogItself){
console.log(dialogItself);
alert('The content of the dialog is: ' + dialogItself.getModal().html());
}
}]
});
The html form
<form id="createEventForm">
<label>Klantnaam</label>
<input type="text" id="titleDrop" />
<br/>
<label>Beschrijving</label>
<input type="text" id="descriptionDrop" />
</form>
I don't know how to retrieve the data from the forms input when someone clicks on a button. I've tried $(titleDrop).val()andgetElementById(titleDrop)
Sometimes the form can contain php.
I am not getting javascript errors. I just don't get anything back when clicking on the butotns and using $('titleDrop').val()
EDIT FIDDLE
http://jsfiddle.net/jochem4207/7DcHW/3
This code works:
var form = '<label>Klantnaam</label><input type="text" id="titleDrop"><br><label>Beschrijving</label><input type="text" id="descriptionDrop">';
BootstrapDialog.show({
message: form,
buttons: [{
id: 'submit1',
label: 'See what you got',
cssClass: 'btn-primary',
action: function(dialogRef){
var titleDropVal = $('#titleDrop').val();
console.log(titleDropVal);
}
}]
});
Still curious if it could work when I dont add the html in the JS section.
Edit: Question 2
I have a select list that gets filled from php
var select = $('<select id="selectVisibleUser"></select>');
<?php
$userList = array();
foreach($this->users as $user){
$jsUser = array(
'key' => $user->webuserId,
'value'=> $user->firstName.$user->preposition.$user->lastName
);
array_push($userList, $jsUser);
}
$list = Zend_Json::encode($userList);
?>
$.each(<?php echo $list?>, function(key, value) {
select.append($("<option/>", {
value: key,
text: value
}));
});
BootstrapDialog.show({
message: function (dialogItself){
var form = $('<form></form>');
dialogItself.setData('select-visible', select);
form.append('<label>Select</label>').append(select);
return form;
},
buttons: [{
id: 'submit1',
label: 'See what you got',
cssClass: 'btn-primary',
action: function(dialogItself){
alert(dialogItself.getData('select-visible').val());
}
}]
});
This shows me a empty select list and returns offcourse a null when I click the button.
Should I use your first fiddle in this case?
Tried the first fiddle ( http://jsfiddle.net/b8AJJ/1/ ) works perfectly in this case (except i've some trouble to get the id instead of the value)
Try this:
http://jsfiddle.net/b8AJJ/
If possible I would suggest this way:
http://jsfiddle.net/7DcHW/4/
BootstrapDialog.show({
message: function (dialogItself) {
var $form = $('<form></form>');
var $titleDrop = $('<input type="text" />');
dialogItself.setData('field-title-drop', $titleDrop); // Put it in dialog data's container then you can get it easier by using dialog.getData() later.
$form.append('<label>Title Drop</label>').append($titleDrop);
return $form;
},
buttons: [{
label: 'Get title drop value.',
action: function (dialogItself) {
alert(dialogItself.getData('field-title-drop').val());
}
}]
});
You're using element selector wrong.
Try $('#titleDrop').val() instead of $(titleDrop).val().
Bind submit event to your form. This way you can get the values of form inputs when the form is submitted. Look at the following example:
http://jsbin.com/xiruv/1/

Get selected value from dropdown in Jquery Context Menu item select change event

I am using JQuery Context Menu plugin to show custom context menu
Link Here
I am using select to show some options to filter in menu items as follows
var filterList={0:'title1',1:'title2',2:'title3'};
menuItems = {
"true": { name: "Sort Ascending", icon: "asc" },
"false": { name: "Sort Descending", icon: "desc" },
"sep1": "----------------",
"Clear": { name: "Clear filter on"+columnName, icon: "clear", disabled: false },
select: {
name: "Filter " + columnName, type: 'select', options: filterList,
events: {
change: function () {
**//I want selected option text value here but dont know how??**
}
}
}
};
how can i get value there on change function
function (e) {e.target.options[e.target.selectedIndex].value} or
$(e.target).find(":selected").val();
Next time, try to explain your question better.
I don't know a lot of jQuery Context Menu, but for what I know, you can do something like this:
function (e) {e.target.options[e.target.selectedIndex].value}
Comment here if this code doesn't work for you. I will try help.

Add Custom button at end of fields in Jquery - jTable Create/Update mode like submit button

At jquery- jTable we can have some fields and actions . I need Other button [possible at end of page] near by Jquery JTable button("Submit" button) that after on Click , run another function . so
this is my code :
$('#RequestSubmitDiv').jtable({
title: 'newRec',
paging: false,
sorting: false,
selecting:false;
selectingCheckBoxes:false,
selectOnRowClick:false,
jqueryuitheme:true,
formCreated:function(event,data){
data.form.validationEngine();
},
formSubmitting:function(event,data){
...
...
},
formClode: function(d,e){...} ,
actions: {
createAction: '/Adminsec/ManageAssets.aspx/CreateOrUpdate',
//---not need below
//listAction: '/Adminsec/ManageAssets.aspx/List',
//updateAction: '/Adminsec/ManageAssets.aspx/CreateOrUpdate',
//deleteAction: '/Adminsec/ManageAssets.aspx/Deletes'
//-!!---Other Button and Action Need ---!!
CustomAction:{
title:'RefreshNew',
sorting:false,
create:false,
edit:false ,
list:false ,
display:function(data){
return '<input type='button' id='MyBtn' onclick='Call_Mehod();>';
}
}
},
fields: {
ID {title:'pk',type:'textarea'} ,
RequestNO{type:'textarea'},
description{type:'textarea'}
}
});
How can i add some button to Jquery- Jtable and call function ?
these buttons don't repeat at rows or column , i mean it should be One instance after fields scope.
Maybe I misunderstood but if you want to add a button on each row, you can use display property of the field. I created a dummy field and added the display property. Somthing like this:
...
Other: {
title: 'Other',
display: function (data) {
return '<b>test</b>';
},
create: false,
edit: false
}
...
However, if you wanted to add a general feature (i.e. single button for the table) , you can take a look at the toolbar property.
I did as follow. The tag <button> and class="jtable-command-button" are always required. The next step is your class for icon and finally the event.
actions: {
title: 'Actions',
width: '1%',
sorting: false,
create: false,
edit: false,
list: true,
display: function (data) {
if (data.record) {
// This if you want a custom edit action.
return '<button title="Edit" class="jtable-command-button jtable-edit-command-button" onclick="alert(' + data.record.id + '); return false;"><span>Edit</span></button>';
}
}
}

Performing action a button click event, button being placed inside dojox.grid.DataGrid.

I have a dojox.grid.DataGrid. In this a set of values are being displayed along with last 2 columns being filled up with buttons which are created dynamically according to data being retrieved from database using formatter property in gridStruture. Now i am getting the my grid fine. Buttons are also coming up fine. What i need to do now is when i click on a particular button on that button click event i redirect it to a new URL with a particular value(A) being passes as a query string parameter in that URL. And i don't want my page to be refreshed. Its like when a button is clicked it performs action on some other JSP page and displays message alert("Action is being performed").
My java script code where i have coded for my data grid ::
<script type="text/javascript">
function getInfoFromServer(){
$.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp?random=" + new Date().getTime(), function (result) {
success:postToPage(result),
alert('Load was performed.');
},"json");
}
function postToPage(data){
alert(data);
var storedata = {
identifier:"ActID",
items: data
};
alert(storedata);
var store1 = new dojo.data.ItemFileWriteStore({data: storedata}) ;
var gridStructure =[[
{ field: "ActID",
name: "Activity ID",
classes:"firstName"
},
{
field: "Assigned To",
name: "Assigned To",
classes: "firstName"
},
{ field: "Activity Type",
name: "Activity Type",
classes:"firstName"
},
{
field: "Status",
name: "Status",
classes: "firstName"
},
{
field: "Assigned Date",
name: "Assigned Date",
classes: "firstName"
},
{
field: "Assigned Time",
name: "Assigned Time",
classes: "firstName"
},
{
field: "Email",
name: "Send Mail",
formatter: sendmail,
classes: "firstName"
},
{
field: "ActID",
name: "Delete",
formatter: deleteact,
classes: "firstName"
}
]
];
//var grid = dijit.byId("gridDiv");
//grid.setStore(store1);
var grid = new dojox.grid.DataGrid({
store: store1,
structure: gridStructure,
rowSelector: '30px',
selectionMode: "single",
autoHeight:true,
columnReordering:true
},'gridDiv');
grid.startup();
dojo.connect(grid, "onRowClick", grid, function(){
var items = grid.selection.getSelected();
dojo.forEach(items, function(item){
var v = grid.store.getValue(item, "ActID");
getdetailsfordialog(v);
function showDialog() {
dojo.require('dijit.Tooltip');
dijit.byId("terms").show();
}
showDialog();
}, grid);
});
}
function sendmail(item) {
alert(item);
return "<button onclick=http://localhost:8080/2_8_2012/jsp/SendMailReminder.jsp?Send Mail="+item+"'\">Send Mail</button>";
}
function deleteact(item) {
alert(item);
return "<button onclick=http://localhost:8080/2_8_2012/jsp/DeleteActivity.jsp?Activity ID="+item+"'\">Delete</button>";
}
</script>
I am getting grid data using $.get call. In the above code field Email and ActID are actually buttons being created when each time function sendmail and deleteact are being called up in formatter. Grid is displayed. Also the value of alert(item) in both functions are coming up right that is there respective values. Like for alert(item) in Delete i am getting ActID and alert(item) in sendmail getting "shan#gmail.com" Now i want that on a particular button click(button in Sendmail column) my page
http://localhost:8080/2_8_2012/jsp/SendMailReminder.jsp?Send Mail="+item+"'
and button click in Delete column this page
http://localhost:8080/2_8_2012/jsp/DeleteActivity.jsp?Activity ID="+item+"'\"
opens up with value of items being retrieved from database. I have applied a rowClick event also which is also causing problem as when i click u button my Rowclick event fires instead of button click event. How to do this. I thought of applying click event to each button on grid. But there ID i don't know. Please help me on this one. Thanks..
I think, what you need is adjusting your server-side code to handle ajax post requests for sending mail and use dojo.xhrPost method when user clicks button. Your JS code may look like this:
function sendMailHandler(evt, item) {
dojo.xhrPost({
url: "/2_8_2012/jsp/SendMailReminder.jsp",
content: {
'SendMail': item
},
error: function() {
alert("Sent failure");
},
load: function(result) {
alert("Email sent with result: " + result);
}
});
dojo.stopEvent(evt);
}
function sendmail(item) {
return "<button onclick='sendMailHandler(arguments[0], \"" + item + "\")'>Send Mail</button>";
}
Note that dojo.stopEvent(evt); in sendMailHandler is used to stop event bubbling and prevents RowClick raising.
There is also dojo.xhrGet with similar syntax to perform ajax GET requests, which you can use instead of jQuery's $.get. You can also use dojo.xhrGet instead of dojo.xhrPost in my example, because there is chance that it will work with your back-end without tweaking, but POST (or ajax form submission) would be more semantically correct.
And about "Tried to register an id="something", you should adjust your code to avoid IDs duplication. Or show your code causing errors.

Categories