Close Select2 Dropdown after clicking on X to Clear - javascript

I'm trying to get a Select2 Dropdown to close after clicking on X to clear it because it stays open. I'm currently using the .on('select2:unselect') function to trigger it when the button is clicked to clear the selections but I either get an error or it just doesn't do anything.
Error
TypeError: Cannot read properties of null (reading 'query')
Select2 HTML
<select class="softwareReleaseItem" name="softwareReleaseItem" id="softwareReleaseItem" data-control="select2">
<option></option>
<?php
asort($softwaredb);
foreach ($softwareDB as $software) {
echo "<option value=\"" . $software['Guid'] . "\">" . strtoupper($software['Name']) . "</option>";
}
?>
</select>
<div id="sRI"></div>
Javascript
$('.softwareReleaseItem').on('select2:select', function(e) {
var sri_data = e.params.data;
var sri_callType = 'softwareReleaseItem';
//console.log(sri_data);
$("#sRI").show();
$.ajax({
type: "POST",
url: "dist/php/ajax/ajax_getItemsByName.php",
data: {
sri_id: sri_data['id'],
sri_text: sri_data['text'],
sri_call: sri_callType
},
success: function(data) {
$('#sRI').html(data);
}
});
}).on('select2:unselect', function(e) {
$("#sRI").hide();
closeSelect();
});
All my attempts to close it ->
function closeSelect() {
//$('.softwareReleaseItem').trigger('select2:close');
//$(".softwareReleaseItem").focusout();
$(".softwareReleaseItem").select2().trigger('close');
//$("#softwareReleaseItem").select2("select2:close");
//$("#select2-drop-mask").click();
//$(document.body).trigger('mousedown');
//$('body').trigger('mousedown');
//$('.select2-hidden-accessible').select2('select2:close');
//$(".softwareReleaseItem").select2("select2:close");
};
UPDATE:
So far this is the only working solution I have come up with that works
I just simulate a mouseclick on a hidden div.
.on('select2:unselect', function(e) {
$("#sRI").hide();
$(".softwareReleaseItem").trigger("reset").trigger("change")
document.getElementById('#sRI')
.dispatchEvent(new MouseEvent('click', {
shiftKey: true
}))
});

Related

Checkbox not refreshing in jquery

I am facing an issue as below.
I have two drop-down, first one is single drop down select, second one is multi select drop-down checkbox. Second one shows the result based on the first drop-down value.
While select the first drop-down, I get the values for second drop-down to show(Values Show in Inspect element) but not in drop down.
Please find the below code for further reference.
abc.html
<select name="list_usergroup[]" multiple id="list_usergroup" >
<option value=""> Select User Group </option>
</select>
mg.js
org_uuid = $('#list_organization').val();
$.ajax({
url: appGetSecureURL("/api/web/getorgug/" + org_uuid),
type: "GET",
dataType: "json",
jsonpCallback: 'jsonCallback',
beforeSend : function(){
loaderOn();
},
success: function(data) {
// Display Usergroups
if (0 == data.ug_total) {
$("#list_usergroup").html('<option value="">No Usergroup.</option>');
}
else {
$("#list_usergroup").html("");
$("#list_usergroup").html('<option value="">Select Usergroup</option>');
for (rowData in data.usergroups)
{
var optionData = '<option data = "'+ data.usergroups[rowData] +'" value="'+ rowData+'">' + data.usergroups[rowData]+'</option>';
$('#list_usergroup').val("");
$('#list_usergroup').multiselect('refresh');
$('#list_usergroup').multiselect('reset');
$("#list_usergroup").append(optionData);
}
//$('#list_usergroup').multiselect('reset');
$("#list_usergroup").multiselect({
columns: 1,
placeholder: 'Select Usergroups',
search: true,
selectAll: true,
onLoad: function() {
}
});
$("#list_usergroup").val(Value);
}
loaderOff();
},
error: function(data, b, c) {
appLog.debug("Display Usergroup error Status " + data.status + ": " + data.statusText)
}
})
I am using https://github.com/nobleclem/jQuery-MultiSelect plugin
Thanks in advance.
To Enable Multiselect with refresh data. you have to re-initialise Multiselect.
$('#list_usergroup').multiselect('destroy'); // tell widget to clear itself
$('#list_usergroup').multiselect(); // re-initialize the widget

Reload a portion of the webpage using ajax?

Controller (called for loading a specific board):
public function getBoard()
{
$role = $this->session->userdata('role');
$user_id = $this->session->userdata('user_id');
$board_id = $this->input->post('board_id');
if ($this->session->flashdata('first_board_id') !== null)
{
$board_id = $this->session->flashdata('first_board_id');
}
$data['board_id'] = $board_id;
$data['board_name'] = $this->Board_model->getBoardName($board_id);
$data['columnData'] = $this->Column_model->getColumns($board_id);
$data['rowData'] = $this->Row_model->getRows($board_id);
$data['tasks'] = $this->Task_model->getTasks($board_id);
$data['pendingSubtasks'] = $this->Task_model->countPendingSubtasks($data['tasks']);
$data['finishedSubtasks'] = $this->Task_model->countFinishedSubtasks($data['tasks']);
$data['boards'] = $this->Board_model->getBoards($role, $user_id);
$this->load->view('templates/header',$data);
$this->load->view('main_kanban', $data);
$this->load->view('templates/footer',$data);
}
From templates/header.php
<li class="custom-holder select-board">
<label class="boostrap-select-label">BOARD:</label>
<select class="selectpicker" title="CHOOSE BOARD" id='board_selection'>
<?php
if (count($boards) > 0) {
foreach ($boards as $b) {?>
<option value="<?php echo $b->id; ?>"><?php echo $b->name; ?></option>
<?php
}
}
?>
</select>
</li>
From func_board.js (Loaded in the footer; called when dropdown selection is changed)
$('.select-board').on('change', '#board_selection', function() {
console.log('Changed board selection.');
var selected_board = $('#board_selection option:selected').val();
$.ajax({
type: 'POST',
url: base_url + 'home', //configured this in routes.php
data: { 'board_id' : selected_board },
success: function(msg) {
if (msg != 'failed')
{
console.log('Loading board success!');
$('.mainboard').load(base_url + 'home', {
'board_id' : selected_board
}); //mainboard is the parent div in main_kanban
//that basically contains all the elements for the board
}
else
{
console.log('Error >> ' + msg);
}
},
error: function(xhr, error, errorThrown) {
console.log(xhr.responseText);
console.log(error);
}
});
});
I have a select or dropdown menu from which you can choose which board to view. However, as hinted by my code above, I'm using templates. Basically, when you click on a different board from the dropdown, it's supposed to load that board. The html for the board is in main_kanban. I don't think I can use redirect since there is data that I need to pass with the view.
I've tried jQuery's load() but I'm having problems with it. (There's a New Task button in each <td> as I'm using a table for the boards. When that New Task modal opens there is an option to select the To Date and From Date. When I use load() the date time picker doesn't show up. I'm using several scripts for the customization which are loaded in the templates/footer.php I have other select menus in the modal too. When ajax is finished those menus are empty.)
How can I achieve this?
Use the completion callback of load() to initialize plugins like date pickers
var loadData = {'board_id' : selected_board};
$('.mainboard').load(base_url + 'home', loadData , function(){
// new html exists now .. initialize plugins or event listeners
$(this).find('.datepickerClass').datepicker({ /* options */})
});

How do I clear data shown on mouseenter with onmouseout

When the user hovers over an image an information box comes up about that image, the information them changes inside the box as I move over another image but when I am over no images the information box stays. I can't close the information box (i.e. tooltips).
JS :
var id;
$(document).ready(function () {
$('a').mouseenter(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
});
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
});
How can I get the information box to disappear on mouse out?
I have tried multiple tests but the box doesn't even appear with them, the last one I tried is in the code above.
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
I am only starting out with javascript, jquery etc. in the last year.
Thank you in advance!!
Here is the php.
<div class="thumbnails">
<?php
$query = mysqli_query($connection, "select * from portfolio");
print "<ul>";
while ($row = mysqli_fetch_assoc($query)) {print "<li><img onClick=preview.src=" . $row['image'] . "name=" . $row['folio_id'] . "src={$row['image']}></td></li>";
}
print "</ul>";
?>
</div>
<!--Folio Information-->
<div id="fillFolio">Project Information</div>
I'm not sure, but try to use :
$('a').onmouseleave(function () {
$("#fillFolio").empty();
}
Hope this helps.
$("a").hover(function(){
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
}, function(){
//im not sure u want to hide or want to just clear your question not clear
$("#fillFolio").empty();
$("#fillFolio").hide();
});
Why not use jQuery hover = (mouseenter + mouseleave)
<script type="text/javascript">
var id;
$(document).ready(function () {
$('a').hover(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
,function () {
id = $(this).empty();
});
</script>

Creating textarea and buttons dynamically

I am facing issues with creating a dynamic textarea and 'Add' and 'Edit' buttons for every new paragraph.
DEMO of what I have managed so far:
The 'Add' button is for creating new paragraphs. The user should see a textarea where they enter the content for new paragraph. The first time they click 'Add' button, the text on the button will change to 'Save', the second time they click 'Save' it should append the paragraph to the div and assign it a unique id, which will be used to reference it with the new 'Add' and 'Edit' buttons.
The 'Edit' button is for editing the paragraph from which the 'Edit' button was clicked. To make the paragraph editable I'm using jquery editable (jeditable). Below are appropriate links to jeditable plugin:
plugin documentation
jeditable live demo
All the paragraph load from the back-end. Using PHP to load paragraphs:
<div class="paragraphs">
<?php
foreach($notes['children'] as $overview) :
if ($overview['type'] == 'Paragraph') :
?>
<div id="block1">
<p class='edit1'><?php echo $overview['content']; ?></p>
<p>
<?php if (isset($subject) && $subject==true) : ?>
<div id="para1">
<p><textarea cols="40" rows="2" id="textarea1"></textarea></p>
<button id="add1" class="add1 success tiny">Add</button>
<button id="startEdit1" class="canEdit1 tiny">Edit</button>
</div>
<?php endif; ?>
</p>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
The 'Add' and 'Edit' button functionality:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/teachers/js/jquery.jeditable.min.js"></script>
<script>
var $subject_id = "<?php echo $subject_id ?>";
var $teacher_id = "<?php echo $teacher_id ?>";
// Define our elements
var $lock = false;
//Make the elements editable
function makeThingsEditable() {
$editables.editable({
emptyMessage : '<em>Please write something...</em>',
callback : function( data ) {
$info.hide();
$info.eq(0).show();
}
});
}
function ajaxRequest(data, method_url, request_type) {
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('HTTP/1.1', '200');
}
});
var eurl = "<?php echo base_url(); ?>edit_flow/" + method_url;
var params = 'inputJson=' + data;
var post = $.ajax({
type: request_type,
url: eurl,
data: params,
success: function(result) {
console.log('result: '+result);
console.log('data: '+params);
},
async: false
});
//alert(post.responseText);
return post.responseText;
console.log(post.responseText);
}
// Edit paragraph button
// Button that toggles the editable feature
var i = 1;
var $editables = $('.edit'+i);
$('.canEdit'+i).click(function() {
if( $editables.is(':editable') ) {
//need to call save action here and pass in updated JSON
if ($(this).text() == 'Save changes')
{
var text = $(".edit"+i).text();
// ajax request
var datum = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
ajaxRequest(datum, 'editNotes', 'POST'); // POST request on editNotes
ajaxRequest(datum, 'loadNotes', 'GET'); // GET request on loadNotes
// jquery request
$.get( "<?php echo base_url(); ?>edit_flow/loadNotes", function( data ) {
var data = '{"subject_id":'+$subject_id+', "teacher_id":'+$teacher_id+', "editedContent":"'+text+'"}';
//console.log(data);
alert( data );
});
}
$editables.editable('destroy');
this.innerHTML = 'Edit';
i++;
} else {
makeThingsEditable();
this.innerHTML = 'Save changes';
// TODO h4kl0rd: make $editables selectable
}
});
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
$('#add'+i).click(function(){
if ( $(this).text() == "Add" ) {
$('#textarea'+i).show();
$(this).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $(this).text() == "Save" ) {
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$(this).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
Any help is appreciated.
change these:
$('.canEdit'+i).click(function() {
$('#add'+i).click(function(){
to these:
$(document).on('click', '.canEdit'+i, function() {
$(document).on('click', '#add'+i, function() {
What seemed to me is your buttons are dynamic and they can't take direct event binding. So instead you have to delegate the event to the closest static parent which is $('.paragraphs') or to $(document) itself because it is always available.
So if you are using closest static parent then you have to put your event handlers inside doc ready and if you are using $(document) then its not needed.
$(function(){
var i = 1;
var $editables = $('.edit'+i);
$('.paragraphs').on('click', '.canEdit'+i, function() {
// all your edit stuff
});
$('.paragraphs').on('click', '#add'+i, function() {
// all your addstuff
});
});

How to create/find right ID in multiple Form elements of same type $ajax function with jQuery Mobile?

I have a collapsible part of my jQuery Mobile page that are generated from PHP output from a MS Sql databas and content render as I like it to so that part is ok.
in each section I create a form with 3 buttons and they are supposed to have unique Id:s.
All forms are also created to have a unique id created in runtime.
actions.php (renders out my elements into mobilepage i a DIV)
$counter=0; reset counter for ID:s
while (odbc_fetch_row($rs)){
// data output from Db to make like 10 collapsible with different data
$html = "";
$html = "<div data-role='collapsible-set' data-mini='true'>";
$html.="<div data-role='collapsible' data-mini='true'>";
$html.="<h3><span style=float:left;><img src='../_pic/$image' alt='$imageText' /> ".substr($Time,0,16)." $Area</span><span style='float:right;' class='ui-btn-up-c ui-btn-corner-all' cnt> $data </span></h3>";
$html.="<p>ID: $ID $Id $Status<br />$Status $Description)</p>";
$html.="<form method='post' action=''>";
$html.="<button value='action1' id='action1$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action2' id='action2$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action3' id='action3$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<input type='hidden' id='id$counter' name='id' value='$dataName' />";
$html.="</form>";
$html.="</div>";
$html.="</div>";
echo utf8_encode($html);
$counter++; //upcount to make Id:s unique
} //end While
Then I have this function that listens for a button that submit:
$(':submit').live('click', function() {
var button = $(this).val();
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+$('#id').val(),
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
I cant seem to get another id than the first one since i need to make all ID:s unique in my forms and all I do now is to check: &id='+$('#id').val(). what I would like to have done is to link the button pressed-id number to my hidden field id-number so i get the right data out from it. As of now I only get the first form:s id evaluated...
If someone could point me in the right direction how to make that happen i´d be greatful.
functions.php (a switch statement is pre-testing for submit:ed action
function actions1(){
try {
if(isset($_GET['id'])){
do stuff with 'id'
}else{
do other stuff with 'id'
}
} catch(Exception $e) {
show error
}
}
If some part is unclear or if you feel I missed posting somepart - let me know. /thanks
Within event handlers this referes to the element
$(':submit').live('click', function(){
var id= this.id;
var button = $(this).val();
/* traverse within form to set hidden input, no need to worry about using ID's for them*/
$(this).closest('form').find('input[name=id]').val(id);
/* then in ajax */
data: 'button=' +button+'&id='+id,
})
Not full code....I left some of your code out for simplicity
You can use jQuery .attr() function to get an id or any other attribute value of an element.
$(':submit').live('click', function() {
var button = $(this).val();
var id = $(this).attr("id");
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+ id,
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
The solution was to go by attributes name of my hidden input.
var id = $(this).closest("form").find(':hidden').val();

Categories

Resources