jquery change css on radio button and page load - javascript

I have the following jquery snippet which is showing or hiding items by css depending on which radio button is selected...
<script>
jQuery('input:radio[name="type"]').change(
function(){
if (jQuery(this).val() == 'value1') {
jQuery('.one').css({'display':'none'});
jQuery('.two').css({'display':'block'});
jQuery('.three').css({'display':'none'});
}
else if (jQuery(this).val() == 'value2') {
jQuery('.one').css({'display':'block'});
jQuery('.two').css({'display':'none'});
jQuery('.three').css({'display':'none'});
}
else if (jQuery(this).val() == 'value3') {
jQuery('.one').css({'display':'none'});
jQuery('.two').css({'display':'none'});
jQuery('.three').css({'display':'none'});
}
});
</script>
It is working great but what I want to do now is have this happen on page load as well instead of just when the radio button is changed.
Whats the simplest way to achieve this?

You could chain the .change() method after attaching the event listener.
In doing so, a change event is fired after the event listeners are attached (which will presumably happen when the page loads).
Example Here
$('input:radio[name="type"]').change(function () {
// ...
}).change(); // <---
You could also use .trigger('change') in place of .change() too:
Example Here
$('input:radio[name="type"]').change(function () {
// ...
}).trigger('change'); // <---
Depending on where the script is placed in your HTML document, you may need to make sure it is wrapped within a DOM ready handler too!
$(document).ready(function () {
$('input:radio[name="type"]').change(function () {
// ...
}).change();
});

Related

How to prevent more than one click on an Anchor tag button

I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .
I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.
When the button is clicked more than once it takes me to an empty page or an error page.
I want to prevent more than one click on the button.
I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?
My JS code:
$('.cancel-btn').on('click',function(evt){
//evt.preventDefault();
//My Code
});
jQuery one() method will perform click event only once:
$('.cancel-btn').one('click',function(evt){
// evt.preventDefault();
// code here
});
Also possible using jQuery on() method that may be more useful when the event should be removed conditionally:
let count = 0; // or may be a boolean flag
$('.cancel-btn').on('click', function(evt){
if (count == 0) {
count++;
// code here
} else {
return false;
// or evt.preventDefault();
}
});
Or like this:
$('.cancel-btn').on('click', function(evt) {
// code here
// then remove the event handler.
$(this).off('click');
});
Try using a boolean flag to make sure the function executes only once
var executeOnce = false;
$('.cancel-btn').on('click',function(evt){
if(!executeOnce){
//evt.preventDefault();
//My Code
executeOnce = true;
}
});
Here you go with one more way to do it using pointer-events as none
https://jsfiddle.net/w2wnuyv6/1/
$('a[value="cancel"]').click(function(){
$(this).css({
'pointer-events': 'none'
});
});
you can write a function like this:
function clickOnce (element ,listener){
element.addEventListener("click", function (event){
listener(event);
element.removeEventListener("click", arguments.callee);
});
}
jsfiddle
As you mentioned the event is written on that class, you can use this simple code to ensure that its clicked only once:
$('.cancel-btn').on('click', function(evt) {
// execue your code
$(this).removeClass('cancel-btn');
});
This code will remove the class from the DOM and hence the click event will never get fired.
Optionally, You can use off() to remove an event like so:
$(".cancel-button").off("click");
This will remove all click events bound to this element. In your code, it would be like:
$('.cancel-btn').on('click', function(evt) {
// execue your code
$(this).off("click");
});

automatic close function for selection

I have a button which creates a pulldown in which you can select several categories.
Now i want this to close automatically when i click outside the pulldown.
Something like a lightbox or modal popup which closes if you click anywhere else on the page.
Now i have to click the button again to close it. If i dont and go elsewhere on the page, the dropdown stays visible (until i click it)
This is the code of the button:
$(function(){
$('#browse-btn').click(function(){
$('#browse-content').toggle('1000');
$(this).toggleClass('active');
if ($(this).hasClass('active')) $(this).find('span').html('▲')
else $(this).find('span').html('▼')
});
$(".scroll-top").scrollToTop();
$("#category_id").selectbox();
});
Is this possible?
thanks
Using jquery this is the code I used for a similar case scenario sometime ago:
$(document).click(function(event) {
if(!$(event.target).closest('.pulldown').length) {
if($('.pulldown').is(":visible")) {
$('.pulldown').slideUp()
}
}
})
You can read more about this in the original post How to detect a click outside an element? submitted by Art.
I'm not exactly sure of the elements you want to hide as you don't have a demo, so I cannot provide a fully working code, however you should do something like this:
$("body").click(function(event) {
if (event.target.id != "browse-btn") {
// Do something when there's a click outside of #browse-btn
// and the element you want to hide is currently visible
}
});
You can attach a click event to all chidren of the body tag that removes that active class, but you would want to make sure to unbind that event so it doesn't run every time a click takes place that doesn't have some sort of prevent default on it. Something like this:
$(function(){
var hidePulldown = function(){
$('#browse-btn').removeClass('active');
$('body *').unbind("click", hidePulldown);
}
$('#browse-btn').click(function(){
$('#browse-content').toggle('1000');
$(this).toggleClass('active');
if ($(this).hasClass('active')) $(this).find('span').html('▲')
else {
$(this).find('span').html('▼');
$(document).on('click', 'body *', hidePulldown);
}
});
$(".scroll-top").scrollToTop();
$("#category_id").selectbox();
});
Also, the
$(document).on('click', element, function(){function body})
is the preferred way to attach click events i believe: $(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})
This is what worked flawlessly for me after reading some of the answers here:
$(document).click(function(event) {
if(!$(event.target).closest('#menucontainer').length &&
!$(event.target).is('#menucontainer')) {
if($('#menucontainer').is(":visible")) {
$('#menucontainer').hide();
}
}
})
Thanks for pointing me in the right way!

jquery toggle works only once

my intention is to write code that toggles back and forth when any of the two buttons are clicked , its simple code but not working as expected:
$('#pup_container').load('plst_main_f/login_form.php').hide();
$('#login_activate').click(function (e) {
e.preventDefault();
$('#pup_container').fadeIn(950);
});
$('#button_img').click(function () {
$('#login_wrapper_background').slideToggle(755);
});
works fine the first time around, but isn't TOGGLING like its supposed to, the toggle happens once and its probably because they are triggered with different buttons but i'm not quite sure, please help
code here is part of the ready function.
Since the button_img is loaded dynamically, you need to bind the handler after the element is loaded dynamically
$('#pup_container').load('plst_main_f/login_form.php', function () {
$('#button_img').click(function () {
$('#login_wrapper_background').slideToggle(755);
});
}).hide();
$('#login_activate').click(function (e) {
e.preventDefault();
$('#login_wrapper_background').toggle(950, function () {});
});
Or use event delegation

JQuery .on("click", function() ) doesn't work

I am trying to fire JQuery when I checkbox is checked. At first I realized my JQuery only works for static elements. I read through a couple posts and found out that I need .on("click, function()) in order to fire that same piece of javascript for dynamically added elements.
However, this method still doesn't work for me. Can anyone help? Thank you.
$(document).ready(function(){
$("input[name='todo']").on('click', function(){
var isChecked = this.checked
if (isChecked == true){
$(this).next().remove();
$(this).remove();
}
if (isChecked == false)
{
alert("checkbox is NOT checked");
}
});
});
My example app: http://jsfiddle.net/JSFoo/7sK7T/8/
You need delegation:
$('#ToDoList').on('click', "input[name='todo']", function() { ... });
http://jsfiddle.net/7sK7T/9/
Documentation: http://api.jquery.com/on/#direct-and-delegated-events
PS: the important note - you need to specify the element you're binding your handler to as close to the target elements as possible. In your case it's #ToDoList, not body or document as other answers advice.
For dynamic elements you would want to do something like this
$(document).ready(function () {
$(document).on('click', "input[name='todo']", function () {
var isChecked = this.checked
if (isChecked == true) {
$(this).next().remove();
$(this).remove();
}
if (isChecked == false) {
alert("checkbox is NOT checked");
}
});
});
if you use it like you were before on('click') is basically the same as click(); because you are still selecting the elements required and applying the event to those elements, the way the above example works is it is only applies the event to the document then checking the selector when the event is fired.
You can also change document to a close container of the elements to be clicked if you wish.
This is called Event Delegation
jQuery Learn Event Delegation
The below is what you needed. It is slightly different syntax
$(document).on('click', "input[name='todo']", function(){
You bind the elements on document ready, it's before they're created.
You have to bind AFTER their creation.
Alternatively you can bind their container on document.ready:
$("#containerDiv").on('click', "input[name='todo']", function(){
// .... your code
});
"containerDiv" should be the parent element of those checkboxes, it should be in the page on document ready!

How to set the focus for a particular field in a Bootstrap modal, once it appears

I've seen a couple of questions in regards to bootstrap modals, but none exactly like this, so I'll go ahead.
I have a modal that I call onclick like so...
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
});
This works fine, but when I show the modal I want to focus on the first input element... In may case the first input element has an id of #photo_name.
So I tried
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
$("input#photo_name").focus();
});
But this was to no avail. Lastly, I tried binding to the 'show' event but even so, the input won't focus. Lastly just for testing, as I had a suspiscion this is about the js loading order, I put in a setTimeout just to see if I delay a second, will the focus work, and yes, it works! But this method is obviously crap. Is there some way to have the same effect as below without using a setTimeout?
$("#modal-content").on('show', function(event){
window.setTimeout(function(){
$(event.currentTarget).find('input#photo_name').first().focus()
}, 0500);
});
Try this
Here is the old DEMO:
EDIT:
(Here is a working DEMO with Bootstrap 3 and jQuery 1.8.3)
$(document).ready(function() {
$('#modal-content').modal('show');
$('#modal-content').on('shown', function() {
$("#txtname").focus();
})
});
Starting bootstrap 3 need to use shown.bs.modal event:
$('#modal-content').on('shown.bs.modal', function() {
$("#txtname").focus();
})
Just wanted to say that Bootstrap 3 handles this a bit differently. The event name is "shown.bs.modal".
$('#themodal').on('shown.bs.modal', function () {
$("#txtname").focus();
});
or put the focus on the first visible input like this:
.modal('show').on('shown.bs.modal', function ()
{
$('input:visible:first').focus();
})
http://getbootstrap.com/javascript/#modals
I am using this in my layout to capture all modals and focus on the first input
$('.modal').on('shown', function() {
$(this).find('input').focus();
});
I had the same problem with bootstrap 3, focus when i click the link, but not when trigger the event with javascript.
The solution:
$('#myModal').on('shown.bs.modal', function () {
setTimeout(function(){
$('#inputId').focus();
}, 100);
});
Probably it´s something about the animation!
I had problem to catch "shown.bs.modal" event.. And this is my solution which works perfect..
Instead simple on():
$('#modal').on 'shown.bs.modal', ->
Use on() with delegated element:
$('body').on 'shown.bs.modal', '#modal', ->
Seems it is because modal animation is enabled (fade in class of the dialog), after calling .modal('show'), the dialog is not immediately visible, so it can't get focus at this time.
I can think of two ways to solve this problem:
Remove fade from class, so the dialog is immediately visible after calling .modal('show'). You can see http://codebins.com/bin/4ldqp7x/4 for demo. (Sorry #keyur, I mistakenly edited and saved as new version of your example)
Call focus() in shown event like what #keyur wrote.
I've created a dynamic way to call each event automatically. It perfect to focus a field, because it call the event just once, removing it after use.
function modalEvents() {
var modal = $('#modal');
var events = ['show', 'shown', 'hide', 'hidden'];
$(events).each(function (index, event) {
modal.on(event + '.bs.modal', function (e) {
var callback = modal.data(event + '-callback');
if (typeof callback != 'undefined') {
callback.call();
modal.removeData(event + '-callback');
}
});
});
}
You just need to call modalEvents() on document ready.
Use:
$('#modal').data('show-callback', function() {
$("input#photo_name").focus();
});
So, you can use the same modal to load what you want without worry about remove events every time.
I had the same problem with the bootstrap 3 and solved like this:
$('#myModal').on('shown.bs.modal', function (e) {
$(this).find('input[type=text]:visible:first').focus();
})
$('#myModal').modal('show').trigger('shown');
Bootstrap has added a loaded event.
https://getbootstrap.com/docs/3.3/javascript/#modals
capture the 'loaded.bs.modal' event on the modal
$('#mymodal').on('loaded.bs.modal', function(e) {
// do cool stuff here all day… no need to change bootstrap
})
Bootstrap modal show event
$('#modal-content').on('show.bs.modal', function() {
$("#txtname").focus();
})
A little cleaner and more modular solution might be:
$(document).ready(function(){
$('.modal').success(function() {
$('input:text:visible:first').focus();
});
});
Or using your ID as an example instead:
$(document).ready(function(){
$('#modal-content').modal('show').success(function() {
$('input:text:visible:first').focus();
});
});
Hope that helps..

Categories

Resources