How to close dropdown box with Jquery when clicking outside - javascript

So I have this dropdown box, I would like to close it when clicking outside of it, how can I get it?
$(document).ready(function(){
jQuery('ul.nav li.dropdown').click(function() {
jQuery(this).find('.dropdown-menu').fadeIn();
$("#actionStatus").html("");
});
$("body:not(ul.nav li.dropdown)").hover(function(){
$("ul.nav li.dropdown").find('.dropdown-menu').fadeOut();
});
$("#btnSendOption").click(function(){
var data = $("#frmUserOption").serialize();
$.ajax({
url: "/users.php",
data: data,
success: function( data ) {
$("#actionStatus").html("");
$("input[type='radio']").attr('checked', false);
$('.dropdown-menu').delay(1000).fadeOut();
},
error: function(data) {
$("#actionStatus").html("<div class='alertMsg alertMsg-danger'>Error, try again later</div>");
}
});
});
});
Any help is very appreciated. Thank you in advance.

You can use this:
$("body:not(ul.nav li.dropdown)").hover(function(){
$("ul.nav li.dropdown").find('.dropdown-menu').fadeOut();
})

maybe something like this: (didnt test it)
$(document).ready(function(){
$('ul.nav li.dropdown').click(function() {
var $this = $(this);
$("body").one("click",":not('ul.nav li.dropdown')", function(){
$this.find('.dropdown-menu').fadeOut();
});
$this.find('.dropdown-menu').fadeIn();
$("#actionStatus").html("");
});
});

I created a simple jsbin for you with an example of what I think you need. I added some simple html as reference just guessing what you needed...
http://jsbin.com/bodoxixa/1/edit?html,js,output

Related

javascript works in console but not on page even after adding $(document).ready(function ()

I just can't get this to work. It works fine in the console of Google Chrome. I added $(document).ready(function (). Still no luck. Any help is greatly appreciated. update: I'm trying to get the value of the first cell when the row is selected on a dynamically created html table
Script
<script type="text/javascript">
$.ajax({
url: '#Url.Action("VisitList")',
method: 'post',
dataType: "json",
contentType: 'application/json;charset=utf-8',
data: "{id: 112601}",
success: function (data) {
//alert("success");
$('#divData').removeClass('hidden');
$('#tblBody').empty();
$.each(data, function (index, value) {
var row = $('<tr><td>' + value.JobID + '</td><td>'
+ value.VisitID + '</td><td>'
+ value.VisitDate + '</td><td>'
+ value.VisitInfo + '</td><td>'
+ value.Engineer + '</td></tr>');
$('#tblData').append(row);
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
$(document).ready(function () {
$("#tblBody tr").click(function (rowElement) {
//alert("hello");
var value = $(this).find('td:first').html();
alert(value);
})
});
</script>
As you are adding rows dynamically, you need to use jQuery.on
$("#tblBody").on("click", "tr", function (rowElement) {
var value = $(this).find('td:first').html();
alert(value);
});
You probably forgot to add a jQuery to the head of your HTML. See the example:
$(document).ready(function(){
alert("Hello World!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
What is the error?
Try putting this at the start of that Script:
console.log($().jquery);
It should print out the jQuery version so you know jQ is available at that point.
Also, the document might be ready but could it be that you add elements to it later dynamically?
$("#tblBody tr")
Maybe target for this is missing? Not loaded or you targeted poorly?
In any case, if above does not fix the problem, do include error, relevant HTML structure and any additional code that might change HTML in the question to make it a complete one.
PRO TIP: Questions that have plunker or similar available are solved way faster and do attract more people.
You could use .on click event on document something like this:
$(document).on('click', '#tblBody tr', function () {
var value = $(this).find('td:first').text();
alert(value);
});
If you add any data dynamically at that time you should use jquery .on() method.Like this:
$("#tblBody").on("click", "tr", function (rowElement) {
var value = $(this).find('td:first').html();
alert(value);
});

jQuery .bind('show') not working appropriately when element is shown via jQuery

I have a snippet in my project similar to the one seen below:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$('#this_container').fadeIn();
}
});
The above snippet is working. When thisCondition evaluates to true, the container does fade in. However, I also have the snippet below that is not functioning as expected. It binds to show so that when the container fades in an event will be triggered:
$('#this_container').bind('show', function() {
$.ajax({
...
});
});
Shouldn't the snippet above react to line 5 in the change event handler? Why is the bind method not triggering?
Confirmed that show is not a valid nor jQuery-triggered event.
But you can trigger it yourself!
Try something like this :
$('#this_container').fadeIn("slow", function() {
$(this).trigger("show");
});
The show is not a valid event, neither is triggered by jQuery. You need to construct your script in a different way altogether:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$.ajax({
success: function () {
$('#this_container').fadeIn();
}
});
}
});
So, you can try to bring the AJAX content, and upon a successful request, you can show the container.
try to use :
$('#this_container').fadeIn( "slow", function() {
// Animation complete
$.ajax({
...
});
});

Calling a function on click via JavaScript/jQuery on button clicks

Here's my JavaScript:
function privacy(current)
{
var $this = $(current),
$scope = $this.closest('.uk-button-group'),
value = $this.val();
$.ajax({
type: 'post',
url: '/privacy.php',
data: {key: value },
success: function () {
}
});
}
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy($this);
alert('A button has been clicked!');
});
});
And here's my HTML:
<div class="uk-button-group">
<button class="uk-button" id="privacy1" value="1">Public</button>
<button class="uk-button" id="privacy2" value="2">Protected</button>
<button class="uk-button" id="privacy3" value="3">Private</button>
</div>
When I click on one of the buttons, it should call the privacy function and alert me that a button has been clicked but it doesn't. Can anyone help me and show me what's wrong with my code? Much appreciated thank you!
You do not have any identifier $this, you probably need to change $this with $(this) or simply this to pass the event source object
privacy(this);
OR
privacy($(this));
Replace this :-
privacy(this);
Try here: http://jsfiddle.net/pqdgT/
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy($(this));
alert('A button has been clicked!');
});
});
Here is your working code
And here is the refined code
function privacy(current)
{
var btn = $(current),
scope = $(btn).closest('.uk-button-group'),
value = $(btn).val();
$.ajax({
type: 'post',
url: '/privacy.php',
data: {key: value },
success: function () {
}
});
}
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy(this);
alert('A button has been clicked!');
});
});
Please avoid reserved keywords while naming variables - Here is the list of reserved words
And be careful with your syntax and feel free to use the browser console.

jquery autocomplete running ajax but not displaying results

I have jquery and jquery ui installed on my site, I have
$(document).ready(function(){
//alert('it ran');
$('.global_search').autocomplete({ source: "global_search.php", select: function( event, ui){ window.open( ui.item.url ); } });
});
and when I look in the network tab in chrome I see the result
global_search.php?term=54650 ( Note I searched for 54650 )
The response I get from that is
{"150000":{"name":"Event: TestRod08.28.2012","value":"Event: TestRod08.28.2012","link":"event_profile.php?event_id=2939"}}
Which should display "Event: TestRod08.28.2012" and on click should go to event_profile.php?event_id=2939 but the list never show's up? I have other jquery autocomplete's working on the same page and there list's are showing just fine. Any Idea's?
Try
$('#test').autocomplete({
source : function(request, callback) {
$.ajax({
url : "data.json",
datatype: 'json'
}).done(function(data) {
var results = []
$.each(data, function(key, value) {
results.push({
id : key,
label : value.name,
url: value.link
});
});
callback(results);
});
},
select : function(event, ui) {
window.open(ui.item.url);
}
});
Demo: Plunker
var options, a;
jQuery(function(){
options = { serviceUrl:'global_search.php'};
a = $('.global_search').autocomplete(options);
});
You can try that.
Found out that my global_search.php was returning a json object instead of a json array ( I had keyed values ) when I removed the key's it works just fine
Thank you everyone for your help

Default select issue for JQuery UI 'selectable'

Below is my JS. When the page loads, I want it to automatically run the function as if its being clicked on. The default selection makes it started selected, but doesn't initiate the function. Any idea on how to make that work?
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var pagego;
if(! pagego){
var page = 0;
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
url: 'updatefilters',
dataType: 'json',
data: { filters: filters, page: page },
success: function(data){
html = "Do Something";
$('#board').html(html);
}
});
}
$('#lets').addClass('ui-selected')
});
Thanks!
Just call the function after declaring it:
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
...
}
$('#lets').addClass('ui-selected');
// none of your params are consumed in the function anyways, so you don't need to pass anything
updatefilters();
});
Try to run function in the body tag
<body onload="name_of_function()">

Categories