Populate Dropdown only if dropdown is clicked - javascript

I can't manage to find out how to initiate a click event by a user clicking on a dropdown. I want to populate the dropdown ONLY if the user clicks the dropdown which will be rare. In addition, it depends on several other values selected on the page. So basically, how do I fire off an event if a user just simply clicks on the dropdown to see the options.
I've tried, $('select').click but to no avail.
It works if you don't have any options. But if there are current options, no luck.

Try using the focus event instead, that way the select will be populated even when targeted using the keyboard.
$('select').on('focus', function() {
var $this = $(this);
if ($this.children().length == 1) {
$this.append('<option value="1">1</option><option value="2">2</option>');
}
});​
View simple demo.
UPDATE
Here is a new version that uses unbind to only fire the event handler once. This way you are able to use your alert without adding any option elements to change the outcome of the condition as the previous solution required.
$('select').on('focus', function() {
var $this = $(this);
// run your alert here if it´s necessary
alert('Focused for the first time :)');
// add the new option elements
$this.append('<option value="1">1</option><option value="2">2</option>');
// unbind the event to prevent it from being triggered again
$this.unbind('focus');
});​
Hope that is what you are looking for.

It should work. Here I've done it and its working.
$("select").on("click", function() {
$(this).append("<option>1</option><option>2</option>");
});
Updated: http://jsfiddle.net/paska/bGTug/2/
New code:
var loaded = false;
$("select").on("click", function() {
if (loaded)
return;
$(this).append("<option>1</option><option>2</option>");
loaded = true;
});

Getting the dropdown to automatically open after the click is trickier:
// Mousedown is used so IE works
$('#select_id').on('focus mousedown', function (e) {
var data;
$(this).off('focus mousedown');
$.ajax({async: false,
type: 'GET',
url: 'url that returns the options',
success: function (d) { data = d; }
});
$(this).find('option').remove().end().append(data);
// Prevent IE hang by waiting awhile
var t = new Date().getTime(); while(new Date().getTime() < t + 200) {}
return true;
});

Related

How to set on change as a default on page load jquery?

I have created a on change method for a select box of my project. On selecting particular option it is basically showing and hiding a div which is perfectly working fine. Now, my problem is when first time page is loading this show and hide not working for first default section of form. Can I make this onchange function also working when page load first time.
$('.contact-form').on('change', (e) => {
var selectedId = $(e.currentTarget).val();
var listofforms = $("#discount").data("display-for").split(",");
if (listofforms.indexOf(selectedId) !== -1) {
$("#discount").collapse('show');
}
else {
$("#discount").collapse('hide');
}
});
Here you go with a solution
function changeMethod(selectedId) {
var listofforms = $("#discount").data("display-for").split(",");
if (listofforms.indexOf(selectedId) !== -1) {
$("#discount").collapse('show');
}
else {
$("#discount").collapse('hide');
}
}
changeMethod($('.contact-form').val())
$('.contact-form').on('change', (e) => {
changeMethod($(e.currentTarget).val());
});
You need to move your code outside the change event, so I have kept your existing code within a method changeMethod.
Then call the method from to places
From you change event method
OnLoad of the JS file
Is it possible can I make my on change trigger on page load
Yes, you will just need to change your on change event from e.currentTarget to this as on page load e.currentTarget will be null, but this always points to the current element like:
$('.contact-form').on('change', function() {
var selectedId = $(this).val();
// Your other logic here
});
and to trigger this change event on page load, simply add .change() at last like:
$('.contact-form').on('change', function() {
var selectedId = $(this).val();
// Your other logic here
}).change(); //<---- here

How to get onclick event for jQuery Chosen drodpown listbox?

Hi I am developing one jquery application. I ghave one dropdownbox with jquery choosen.
$(function () {
$(".limitedNumbSelect").chosen();
});
This is my dropdown and binding values from database.
<b>Awarded To:</b> <asp:ListBox ID="ddlvendorss" runat="server" SelectionMode="Multiple" class="limitedNumbSelect"></asp:ListBox>
I am trying to get click event for the above dropdown. As soon as i click on the dropodwn i want to fire a alert before loading any options.
$('#ddlvendorss').click(function (e) {
alert("I am going crazy");
});
In the below code checkedValues arrays contains some values(values present in dropdownlistbox). As soon as i click on the drodpown i ant to hide those values. But below code doesnt work.
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
$(".limitedNumbSelect option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
Above code does not work. May I get some advise on this? Any help would be appreciated. Thank you.
Chosen hides the select element, thus you are not actually clicking the element. However you can use chosen:showing_dropdown event
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
alert('No need to go crazy');;
});
Fiddle
If you want to hide options, You can use
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
//Find options and hide
$(this).find('option:lt(3)').hide();
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
Fiddle
As per OP's code
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
//Get all options
var options = $(this).find('option');
//Show all
options.show();
//Hide based on condtion
options.filter(function () {
return checkedValues.indexOf($(this).val()) === -1;
});
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));

Change behavior of button using AJAX

I'm trying to figure out how to change behaviour of a button using AJAX.
When the button is clicked, it means that user confirmed order recently created. AJAX calls /confirm-order/<id> and if the order has been confirmed, I want to change the button to redirect to /my-orders/ after next click on it. The problem is that it calls again the same JQuery function. I've tried already to remove class="confirm-button" attribute to avoid JQuery again but it does not work. What should I do?
It would be enough, if the button has been removed and replaced by text "Confirmed", but this.html() changes only inner html which is a text of the button.
$(document).ready(function () {
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
var id = this.value;
var url = '/confirm-order/'+id;
$.ajax({
type: 'get',
url: url,
success: function (data) {
$this.empty();
$this.attr('href','/my-orders/');
$this.parent().attr("action", "/my-orders/");
$this.html('Confirmed');
}
})
});
});
The event handler will be still attached to the button, so this will run again:
b.preventDefault();
which will prevent the default, which is opening the href. You need to remove the event handler on success. You use the jQuery #off() method:
$(".confirm-button").off('click');
or more shortly:
$this.off('click');
You can add to your success function something like: $this.data('isConfirmed', true);
And then in your click handler start by checking for it. If it's true, redirect the user to the next page.
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
if ($this.data('isConfirmed')) {
... redirect code ...
}
else {
... your regular code ...
}
}
You need to use .on() rather than .click() to catch events after the document is ready, because the "new" button appears later.
See http://api.jquery.com/on/
$(document).ready(function() {
$('.js-confirm').click(function(){
alert('Confirmed!');
$(this).off('click').removeClass('js-confirm').addClass('js-redirect').html('Redirect');
});
$(document).on('click', '.js-redirect', function(){
alert('Redirecting');
});
});
<button class="js-confirm">Confirm</button>

Jquery disabled an event, and re activate it later

1 - I've gat an html tag with data-needlogged attribute.
2 - I would like to disable all click events on it.
3 - When the user click on my element, I want to display the authentification popin.
4 - When the user will be logged, I would like to launch the event than I disabled before.
I try something like the following code but it miss the "...?" part.
Play
<script>
// 1 - some click events has been plug on the tag.
jQuery('[data-btnplay]').on('click', function() {
alert('play');
return false;
});
// 2 - disabled all click events
jQuery('[data-needlogged]').off('click');
// 3 - Add the click event to display the identification popin
var previousElementClicked = false;
jQuery('body').on('click.needlogged', '[data-needlogged]="true"', function() {
previousElementClicked = jQuery(this);
alert('show the identification popin');
return false;
});
jQuery(document).on('loginSuccess', function() {
// 4 - on loginSuccess, I need to remove the "the show the identification popin" event. So, set the data-needlogged to false
jQuery('[data-needlogged]')
.data('needlogged', 'false')
.attr('data-needlogged', 'false');
// 4 - enable the the initial clicks event than we disabled before (see point 2) and execute then.
// ...?
jQuery('[data-needlogged]').on('click'); // It doesn't work
if (previousElementClicked) {
previousElementClicked.get(0).click();
}
});
</script>
Thanks for your help
Thank for your answer.
It doesn't answer to my problem.
I will try to explain better.
When I declare the click event on needlogged element, I don't know if there is already others click event on it. So, in your example how you replace the alert('play'); by the initial event ?
I need to find a way to
1 - disable all click events on an element.
2 - add a click event on the same element
3 - and when a trigger is launch, execute the events than I disabled before.
So, I found the solution on this stackoverflow
In my case, I don't realy need to disable and enable some event but I need to set a click event before the other.
Play
<script>
// 1 - some click events has been plug on the tag.
jQuery('[data-btnplay]').on('click', function() {
alert('play');
return false;
});
// [name] is the name of the event "click", "mouseover", ..
// same as you'd pass it to bind()
// [fn] is the handler function
jQuery.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.on(name, fn);
// Thanks to a comment by #Martin, adding support for
// namespaced events too.
this.each(function() {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
});
};
var previousElementClicked = false;
// set the needlogged as first click event
jQuery('[data-needlogged]').bindFirst('click', function(event) {
//if the user is logged, execute the other click event
if (userIsConnected()) {
return true;
}
//save the click element into a variable to execute it after login success
previousElementClicked = jQuery(this);
//show sreenset
jQuery(document).trigger('show-identification-popin');
//stop all other event
event.stopImmediatePropagation();
return false;
});
jQuery(document).on('loginSuccess', function() {
if (userIsConnected() && lastClickedElement && lastClickedElement.get(0)) {
// if the user has connected with success, execute the click on the element who has been save before
lastClickedElement.get(0).click();
}
});

codeschool jQuery Return Flight 5.10 on click handler failing

I am running into an odd issue with codeschools jquery course where my on click handler is not working. The question we are trying to solve in 5.10 is:
For starters create an event handler using on, that targets the
.see-photos link within each .tour. When this is clicked, run a
function that will add a class of is-showing-photofy to the tour.
You'll probably want to save a reference to this outside of your event
handler, and use that in the click event handler.
My current code attempt is:
$.fn.photofy = function() {
this.each(function() {
var tour = $(this)
tour.on('click.see-photos', 'button', function() {
$(this).addClass('is-showing-photofy');
});
});
}
$(document).ready(function() {
$('.tour').photofy();
});
and the error message I am getting is:
Your `on` `click` handler should watch for clicks on the `.see-photos` element within the current tour
Can anyone point me in the right direction?
I was missing the following:
prevent default
var tour = $(This)
Final Code:
$.fn.photofy = function() {
this.each(function() {
var tour = $(this);
tour.on('click.photofy', '.see-photos', function(event) {
event.preventDefault();
tour.addClass('is-showing-photofy');
});
});
}
$(document).ready(function() {
$('.tour').photofy();
});

Categories