I have a simple jQuery function as such:
$(function() {
$('div.dropdown-menu').click(function() {
var $this = $(this);
$this.toggleClass('active');
$('.menu').toggle();
});
});
this works excellent, showing and hiding the dropdown .menu which is currently just a unordered list with list buttons.
However I want to add a login form to the dropdown menu on some page, yet clicking on the input fields in such form will cause the menu to close(hide).
How do I change my code to prevent this behavious
You can use event.target to refer to the clicked element and check if it's a form field with the is() method:
$(function() {
$('div.dropdown-menu').click(function(event) {
if ($(event.target).is(":input")) {
return;
}
$(this).toggleClass('active');
$('.menu').toggle();
});
});
You could use .stopPropagation() event.stopPropagation() on the input fields, which prevents the click from bubbling up to parent elements.
Try this:
$('#input_field').click(function(){ return false; })
Try this
$(function() {
$('div.dropdown-menu').click(function(e) {
if ($(e.target).is(":input")) {
return false;
}
$(this).toggleClass('active');
$('.menu').toggle();
});
});
Related
I've build a little function which should change the content of a span, which lies in a <td> together with a button to the value of the button on the first push of the button. When the button is pushed again, it should replace the content with four asterisks.
Unfortunately, it only works one-way
$(".pw_show").click(function () {
$(this).parent('td').children('span').html($(this).attr('value'));
$(this).toggleClass('pw_hide pw_show');
});
$(".pw_hide").click(function () {
$(this).parent('td').children('span').html("****");
$(this).toggleClass('pw_hide pw_show');
});
Fiddle down here: http://jsfiddle.net/kXNk8/218/
You toggle the classes so you need to use dynamic event binding with .on() instead of .click():
$('table').on('click',".pw_show", function () {
$(this).parent('td').children('span').html($(this).attr('value'));
$(this).toggleClass('pw_hide pw_show');
});
$('table').on('click',".pw_hide", function () {
$(this).parent('td').children('span').html("****");
$(this).toggleClass('pw_hide pw_show');
});
jsFiddle example
After the first click, .pw_show no longer exists on the element which causes your issue.
Delegating to a static element using .on() will make it work or you should change it totally.
$(document).on("click", ".pw_show", function () {
$(this).parent('td').children('span').html($(this).attr('value'));
$(this).toggleClass('pw_hide pw_show');
});
$(document).on("click", ".pw_hide", function () {
$(this).parent('td').children('span').html("****");
$(this).toggleClass('pw_hide pw_show');
});
Fiddle: http://jsfiddle.net/4atrmks3/
You should really just toggle the attribute for type between password and text not use a placeholder.
var password = false;
$('a').click(function(){
if (!password){
password = true;
$('input').attr('type', 'password');
} else {
password = false;
$('input').attr('type', 'text');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
Click to toggle password / text
I am making a todo list using jquery. I have problem when submit the form the appended li appears and disappears immediately. Can anyone help me Please?
Here's my Jquery code so far:
$(function(){
$('input:checkbox').click(function(){
if ($(this).is(':checked')) {
$(this).parent().addClass('completed');
}
else {
$(this).parent().removeClass('completed');
}
});
$('#clearComp').click(function(){
$('.completed').fadeOut();
});
$('#todo_from').submit( function(e) {
e.preventDefault();
return false;
});
});
function addTodo(){
var itemToAdd = $('#txtBox').val();
if ( itemToAdd ) {
$('#todoList').append('<li class="todoBlk"><input type="checkbox" class"checkbox">'+itemToAdd+'</li>');
}
$('#txtBox').val('').focus();
}
JS Bin
That is because upon pressing the Enter key, the form is submitting itself and forcing the page to refresh. So you should use .preventDefault() from preventing this from happening:
$('form').on('submit', function(e) {
var itemToAdd = $('#txtBox').val();
if ( itemToAdd ) {
$('#todoList').append('<li class="todoBlk"><input type="checkbox" class"checkbox">'+itemToAdd+'</li>');
}
$('#txtBox').val('').focus();
e.preventDefault();
});
This code also allows you to remove the inline JS for the onsubmit attribute.
Update: I also noticed a problem with your example is that your button fails to clear checked items that are dynamically added. This is because when jQuery is first executed on the page, the click listener is only bound to pre-existing elements. Do consider using .on() to bind the click event to dynamically added list items. Here's the fixed version: http://jsbin.com/hiyuqikura/1/edit?html,js,output
$(function(){
// On submit, prevent default form action and add item if input is not empty
$('form').on('submit', function(e) {
var itemToAdd = $('#txtBox').val();
if ( itemToAdd ) {
$('#todoList').append('<li class="todoBlk"><input type="checkbox" class="checkbox">'+itemToAdd+'</li>');
}
$('#txtBox').val('').focus();
e.preventDefault();
});
// Listen to click event on dynamically added elements
$(document).on('click', 'input.checkbox', function(){
if ($(this).is(':checked')) {
$(this).parent().addClass('completed');
}
else {
$(this).parent().removeClass('completed');
}
});
$('#clearComp').click(function(){
$('.completed').fadeOut();
});
});
comment out the $('#todo_from').submit() function and change the form tag to this
<form id="todo_form" onsubmit="addTodo(); return false;">
You've got the wrong id here $('#todo_from').submit. Should be #todo_form
I have the following code that run's when a radio button is clicked on. However I am trying to change it so it only runs if the radio button that is being clicked is NOT disabled.
Could anyone help me with this?
$('#divName').on('click', 'input[type="radio"]', function(event) { }
One way would be the use of :not()
$('#divName').on('click', 'input[type="radio"]:not([disabled])', function(event) { }
another would be to exit the function immediately if it is inactive..
$('#divName').on('click', 'input[type="radio"]', function(event) {
if (this.disabled) return;
});
You could use the :enabled selector:
$('#divName').on('click', 'input[type="radio"]:enabled', function(event) { }
But depending on what exactly you want to do, you might want to use the change event instead:
$('#divName').on('change', 'input[type="radio"]', function(event) { }
how about (not tested):
$('#divName').on('click', 'input[type="radio"]:enabled', function(event) { }
I have the following function to open an overlay menu:
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
});
To hide the menu, I would like the user to be able to click on any area outside ".context-switch-menu"
I am trying with :not() but with no success..
$('body').click(function(e) {
if ($(e.target).hasClass('context-switch')) {
return;
}
$(".context-switch-menu").hide();
});
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
return false;
});
The reason this can be difficult is because of event bubbling.
You can try something like this:
$('.context-switch').click(function(e) {
e.stopPropagation();
$(".context-switch-menu").toggle();
});
$(".context-switch-menu").click(function(e){
e.stopPropagation();
});
$("body").click(function(e){
$(".context-switch-menu").hide();
});
The e.stopPropagation() prevents the click event from bubbling to the body handlers. Without it, any click to .context-switch or .context-switch-menu would also trigger the body event handler, which you don't want, as it would nullify the effect of the .context-switch click half the time. (ie, if the state is hidden, and then you click to show, the event would bubble and trigger the body handler that would then hide the .context-switch-menu again.)
Without testing, would something like this work?:
$('.context-switch').click(function() {
$(".context-switch-menu").show();
});
$(document).click(function() {
$(".context-switch-menu").hide();
});
Instead of using document, 'html' or 'body' may work as well.
$(document).on('click', function(e) {
if (e.target.className !='context-switch-menu') {
$(".context-switch-menu").hide();
}
});
Just an idea here, based on what what others have suggested in the past:
$(document).click(function(e){
//this should give you the clicked element's id attribute
var elem = $(e.target).attr('classname');
if(elem !== 'context-switch-menu'){
$('.context-switch-menu').slideUp('slow');
//or however you want to hide it
}
});
try this, we don't want to call a function when you clicked on the element itself, and not when we click inside the element. That's why we need 2 checks.
You want to use e.target which is the element you clicked.
$("html").click(function(e){
if( !$(e.target).is(".context-switch-menu") &&
$(e.target).closest(".context-switch-menu").length == 0
)
{
alert("CLICKED OUTSIDE");
}
});
Live fiddle: http://jsfiddle.net/Xc25K/1/
I tried to use focus for first input field on the form. but
it doesn't work. When I call attr("id") for that input it worked. When I call focus for the same input, I didn't see any
result. I also tried to use native Javascript. Does anyone know how to
fix that?
You are all misunderstanding the question. When Colorbox opens you can't focus an input field?
...unless you add your focus to the Colobox onComplete key e.g.
$('#mydiv a').colorbox({ onComplete:function(){ $('form input:first').focus(); }});
You could also bind the focus to an event hook:
$('#mydiv a').bind('cbox_complete', function(){
$('form input:first').focus();
});
That should be enough to get started.
use
$(document).ready(function() {
// focus on the first text input field in the first field on the page
$("input[type='text']:first", document.forms[0]).focus();
});
It may be happening that when your colorbox is opened its focus goes onto the highest element i.e. body of page. use document.activeElement to find that focus went to which element. Then find iframe or id of your colorbox and then set focus on it
Try the first selector,
$("form input:first").focus();
http://jsfiddle.net/erick/mMuFc/
I've just stumbled on this problem.
I think it's best to have a single $.colorbox opener like this:
function showActionForColorBox(
_url,
_forFocus
) {
$.colorbox(
{
scrolling: false,
href: _url,
onComplete: function () {
idColorboxAjaxIndect1.appendTo($('#cboxOverlay'));
idColorboxAjaxIndect2.appendTo($('#cboxOverlay'));
idColorboxAjaxIndect3.appendTo($('#cboxOverlay'));
idColorboxAjaxIndect4.appendTo($('#cboxOverlay'));
// --> Possible element's ID for focus
if (_forFocus) {
$('#' + _forFocus).focus();
}
return;
},
onCleanup: function () {
// TODO: ?
return;
},
onClosed: function () {
if (shouldReloadPageAfterColorBoxAction) {
// --> Should we reload whole page?
shouldReloadPageAfterColorBoxAction = false; // NOTE: To be sure: Reset.
window.location.reload(false);
}
else if (cbEBillsActionReloadPopup) {
// --> Should we reload colorbox
cbEBillsActionReloadPopup = false;
showActionForColorBox(_url);
}
else if (cbShouldLoadAnotherContentAfterClosed) {
// --> Should we reload colorbox with custom content?
cbShouldLoadAnotherContentAfterClosed = false;
$.colorbox({ html: setupContentForcbShouldLoadAnotherContentAfterClosed });
setupContentForcbShouldLoadAnotherContentAfterClosed = '';
}
return;
}
}
);
return;
}
You can also use
$.colorbox({
...,
trapFocus: false
});
to disable focus inside colorbox