Jqgrid and Custom button with dynamic values - php

I have a small problem that maybe you guys can help me. I want to add a button to the grid that changes value depending on the line ie:
onSelectRow: function(id)
{
jQuery('#organismos').jqGrid('navButtonAdd', '#pager1',{caption: "", buttonicon: "ui-icon-image", title: "AO",onClickButton: function() {window.open('Hierarquia/tree_objetivos.php?idorg=' + id, '_blank');
}
Problem is that it will keep adding buttons. And what I wanted was for him to change value so each time you select a row. Have googled and asked for help in the forum and nobody helped me jqgrid. Someone can help me?

I would suggest adding button only once (after initializing the grid) and getting the selected row id from jqGrid options:
jQuery('#organismos').jqGrid('navButtonAdd', '#pager1', {
caption: '',
buttonicon: 'ui-icon-image',
title: 'AO',
onClickButton: function() {
var selectedRowId = jQuery('#organismos').jqGrid('getGridParam', 'selrow');
if (selectedRowId) {
window.open('Hierarquia/tree_objetivos.php?idorg=' + encodeURIComponent(selectedRowId), '_blank');
} else {
alert('You need to select a row first!');
}
}
});

Related

custom search textfield position datatables

I am working on a project that is almost done in my office, there are several pages that use plug-in datatable and use accordion, in this case the problem is that the searchbox I created is irregular. how to fix this?
Datatables Display so far
All processes are normal, but my production manager has asked to change the position of the searchbox to the right
here my Datatables code :
$current_script = '
$(".accordion-toggle").on("click", function () {
var table_key = $(this).data("index");
var table_tbody = $("#asset-"+table_key+" tbody");
console.log(table_tbody);
if(table_tbody[0].childElementCount == 0){
var table_aset = $("#asset-"+table_key).dataTable({
"pagingType":"simple_numbers",
"searching": true,
"AutoWidth":true,
"scrollY": "400px",
"ajax":{"url":"'.site_url($this->current_page.'/get/?get=1&lokasi=').'"+table_key,
"type":"post"}
});
//table_aset.ajax.url("'.site_url($this->current_page.'/get/?get=1&lokasi=').'"+table_key).load();
$.get("'.site_url($this->current_page.'/get/').'",{
get : 2,
lokasi : table_key
},
function(data){
$(".tot_perolehan-"+table_key).html(data.total_perolehan);
},"json");
}
});
';

Cannot populate database column in dropdown

This issue is reminiscent of a question I asked a few years ago:
jQuery dropdown option:first selected
Here is the jQuery function that successfully populates the dropdown id #namelist:
$('#edituserModal').on('show.bs.modal', function (e) {
initializeSelect($('#namelist'), 'assets/process/getNames.php', function (item) {
return {
value: item.name,
text: item.name
}
});
});
The code directly above successfully populates the HTML dropdown select here:
<select id="namelist">
</select>
Here is the code that creates the datatable:
$('#datatable').DataTable({
"searching": true,
"paging": true,
"serverSide": false,
"type": "POST",
"ajax": {
"url": "assets/process/getusers.php",
"dataSrc": ""
},
"columns":
[
{ "data": "null",
"render": function ( data, type, row, meta )
{
return "<i class='far fa-edit editUser'
title='Edit User' data-editdeptrepname='"+row.name+"'></i>";
}
},
{"data": "username"},
// few more columns
]
});
The user clicks on the icon with the class .editUser. That onClick event is here:
$('#datatable').on('click', 'tr > td > .editUser', function(e){
e.preventDefault();
var $dataTable = $('#datatable').DataTable();
var tr = $(this).closest('tr');
var rowData = $dataTable.row(tr).data();
var name = $(this).attr('data-name');
$('#namelist').val(name);
// $('#namelist').val(rowData.name); // <-- I tried this
// $('#namelist').val(rowData.name).text(rowData.name); // <-- also tried this
// $('#namelist option:first').val(rowData.name).text(rowData.name); // <-- this too
// $('#namelist option:first').val(name); // <-- this as well
$('#edituserModal').modal('show');
});
As stated above, the dropdown list is populated with a list of names. When a user opens the modal, the first name that should appear in the dropdown should be whatever the name is saved in the db.
Problem is, in the modal, the dropdown list doesn't initially display the name saved in the database. The dropdown does still display all of the selectable name options, but it's the name saved in the database that should initially be displayed.
As you will see in the last piece of code, I've tried several methods to make it work, all to no avail.
Here is a pic of the dropdown after the modal opens. It should initially read the name currently saved in the database. I can click on the dropdown and it shows a whole list of names. But I need it to initially display the saved name:
What on Earth am I missing? I've done this a hundred times, and it has never failed me until now.
Here it is:
$('#datatable').on('click', 'tr > td > .editUser', function(e){
e.preventDefault();
// Here is where sould go your initializeSelect call
initializeSelect($('#namelist'), 'assets/process/getNames.php', function (item) {
return {
value: item.name,
text: item.name
}
});
var row = $(this).parent().parent();
name = row[0].cells[0].innerText;
$('#namelist option:first').val(name).text(name);
$('#edituserModal').modal('show');
});
By doing this, you dont need your modal show event listener anymore.
Hope this helped.

How to reload - update de DOM after AJAX code injection?

I thought the easiest way would be to explain it with an image of what I have.
Summary -
I have a form to submit posts (pretty much like what you would find in twitter). Within each post there is an <ol> where comments to that post will reside.
Problem -
When I submit the first comment (button submit 2 in the picture), it doesn't call the ajax and just goes to a page where it presents me the php output of the comment. It seems it is not reloading or aplying DOM events to that portion of code. If I go back, the comment is presented (because it refreshs the page) and when adding the 2nd comment, everything goes normal, as expected. The problem is just the first comment.
Flow -
1) insert new post
2) click the textarea, put some text and press submit
3) Jumps to a page where php output for comment is presented
3a) no ajax call is done. It never enters the code
Could you please help me out understand what is going on? Thanks in advance.
In case you need more of the code just tell me.
JS (post_comment.js - associated with submit 2 in picture. I use ajaxForm - jquery form plugin - though I also tried with the standard .ajax call and the result is the same)
$(function () {
var options = {
success: function (html) {
var arrHTML = html.split(',');
var postId = $.trim(arrHTML[0]);
var html_code = arrHTML[1];
$('ol#post_comment_list' + postId).load(html_code);
//$('ol#post_comment_list'+postId 'li:first').slideDown('slow');
$('.footer-post').hide();
$('.comments-feed').delay(2000).slideUp({
duration: 1000,
queue: true
});
$('.small-textarea-main-feed').removeClass('set-large');
resetForm($('.footer-comment'));
},
error: function () {
alert('ERROR: unable to upload files');
},
complete: function () {
},
};
$(".footer-comment").ajaxForm(options);
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
});

Cakephp form input with autocomplete

I am using CakePhp 2.2.1 and I am having some problems to implement what I just asked in the title, I found several tutorials but most of them are for cakephp 1.3 and the others are not what I want to do. I have a "events" table which contains a "player_id" thus a Player has many Events and an Event belongs to a Player.
In my Event add form I proceed as the cookbook says and I get a dropdown list of players to choose from, however what I want is to just write the names of the players and select the one I want from the autocomplete results. Also these players must be from the team that I select before that. Any ideas?
Thanks in advance.
Special thanks to Andrew for pointing out this api.jqueryui.com/autocomplete. However there is not a real guide to use this one. So i found this post, which explains what Abhishek's second link says but I could understand it better. So here is my solution if anyone is interested:
1 - Download from the autocomplete page the .js you need. Save it in app/webroot/js
2 - Either in your app/View/Layouts/default.ctp or in the view you want to use the autocomplete add:
echo $this->Html->script('jquery-1.9.1.js');
echo $this->Html->script('jquery-ui-1.10.3.custom.js');
echo $this->fetch('script');
3 - In your view add (mine was add_goal.ctp):
<script>
$(document).ready(function(){
var myselect = document.getElementById("EventTeam"); //I needed to know which team I was looking players from.
var team = myselect.options[myselect.selectedIndex].value; //"EventTeam" was a dropdown list so I had to get the selected value this way.
$("#EventPlayer").autocomplete({
source: "/events/autoComplete/" + team,
minLength: 2, //This is the min ammount of chars before autocomplete kicks in
autoFocus: true
});
$("input:submit").button();
$("#EventPlayerId").autocomplete({
select: function(event, ui) {
selected_id = ui.item.id;
$('#EventAddGoalForm').append('<input id="EventPlayerId" type="hidden" name="data[Event][player_id]" value="' + selected_id + '" />');
}
});
$("#EventPlayerId").autocomplete({
open: function(event, ui) {
$('#EventPlayerId').remove();
}
});
});
</script>
4 - In your Controller (mina was EventController.php):
public function autoComplete($team = null){
Configure::write('debug', 0);
$this->autoRender=false;
$this->layout = 'ajax';
$query = $_GET['term'];
$players = $this->Event->Player->find('all', array(
'conditions' => array('Player.team_id' => $team, 'Player.name LIKE' => '%' . $query . '%'),
'fields' => array('name', 'id')));
$i=0;
foreach($players as $player){
$response[$i]['id']=$player['Player']['id'];
$response[$i]['label']=$player['Player']['name'];
$response[$i]['value']=$player['Player']['name'];
$i++;
}
echo json_encode($response);
}
visit below link ,this might help you as the ajax helper is no more in cake2.X versions core all related functionality moved to JS helper class.(here third one link for AJAX helper for contributed by user may help you)
http://bakery.cakephp.org/articles/matt_1/2011/08/07/yet_another_jquery_autocomplete_helper_2
or
http://nuts-and-bolts-of-cakephp.com/2013/08/27/cakephp-and-jquery-auto-complete-revisited/
or
http://bakery.cakephp.org/articles/jozek000/2011/11/23/ajax_helper_with_jquery_for_cakephp_2_x
You need to use ajax because your autocomplete-results depends on the team you have selected.
Something like this in jquery:
var team = $('#teamdropdown').find(":selected").text();
$.ajax({
type: "POST",
url: 'http://domain.com/playersdata',
data: {'team':team},
success: function(data){
console.log(data);
//put data in for example in li list for autocomplete or in an array for the autocomplete plugin
},
});
And in cake on playersdata page (Controller or model) something like this.
if( $this->request->is('ajax') ) {
$arr_players = $this->Players->find('all', array('conditions'=>array('team'=>$this->request->data('team')))); //pr($this->request->data) to get all the ajax response
echo json_encode($arr_players);
}
Also set headers to a json respons and $this->layout = null; to remove the layout tpl.
Another solution would be to use json_encode in your php and pass it to js-code like
<script>var players = <?php echo json_encode($array_players_with_teams); ?>; </script>
This solution is only interesting for a small amount of data, if you have a big database with teams and players I wouldn't recommend this, because why load all this data if you only need just a bit of it...
I didn't test the code but it should help you to go on...
Good luck!

Remove "Search" text on input and only apply to one search box, not all

I am working on a site right now and have discovered that the jquery/javascript that I have implemented for the Search applies the same effect to all search boxes on the page when I click in the input field. By default, it removes the "Search" text and clears it out so that you can type your search term. I only want it to perform this function on the search box that is clicked within, not all search boxes on the page. However, if you look at this example, you'll notice that when you click into the search field at the top of the page, it clears the text out of both. I think I could fix it with .parent() or something, but am a jQuery novice. Any help would be appreciated.
Also don't know quite why the border is showing up around my icon, but I'll fix that.
Here's the search function jQuery:
$(document).ready(function(){
$('.search-box').textdefault({'text':'Search'});
});
(function($){
$.fn.textdefault = function(settings){
var Elements = this;
var settings = $.extend({}, $.fn.textdefault.defaults, settings);
return Elements.each(function(){
if($(Elements).is("input")){ TextDefault( $(Elements) ); }
});
function TextDefault(Input){
if (Input.val().length==0) Input.val(settings.text);
Input.focus(function () {
if (Input.val()==settings.text) Input.val('');
});
Input.blur(function () {
if (Input.val().length==0) Input.val(settings.text);
});
}
};
$.fn.textdefault.defaults = {
text: 'Search'
};
})(jQuery);
Thanks!
Taylor
plugin example
here is the correction.
Elements contains all the elements that are 'passed' to this plugin.
var Elements = this;
By using $(Elements) instead of $(this) in the each function, you
used all inputs as one
return Elements.each(function() {
if ($(this).is("input")) {
TextDefault($(this));
}
});
This line of code should be called to initialize the plugin. So it should be put somewhere outside of the plugin, in a $(document).ready() {} code block for example, since you need the plugin initialized for the inputs on the load of the page.
$('.search-box').textdefault({
'text': 'Search'
});
Use a different selector. Instead of all inputs with a class of "search-box" try giving it a unique ID or class.
$("#search_default").textdefault({'text':'Search'});
or
$(".search-box.defaulttext").textdefault({'text':'Search'});
The HTML would then be
<input type="text" class="search-box defaulttext" ...
or
<input type="text" id="search_default" ...
This is the method that I use, which could also be helpful for you. It won't fire for both objects since it uses $(this) to control just the object being focused/blurred.
$(".search-box").live("focus", function(){
if ( $(this).val() == $(this).attr("rel") ){
$(this).val('');
}
}).live("blur", function(){
if ( $(this).val() == '' ) {
$(this).val( $(this).attr("rel") );
}
}).each( function(){
$(this).attr("rel", $(this).val() );
});
I would try to use a more "jQuery" way to do this. jsFiddle
$('input').focus(function(){
$(this).data('text', $(this).val()).val('');
});
$('input').blur(function(){
if( $(this).val() === "" ) $(this).val( $(this).data('text') );
});

Categories