I have a drop down list in an MVC application. When an item in the drop down list is selected (including the same one), I want to trigger a function. However, the first item in the list can't trigger the function and it should be disabled. I have some code below which works initially but after clicking a valid option and then clicking --Select-- again, it still fires the code. How do I fix this?
MVC Control
#Html.DropDownList("ddlCountries", (IEnumerable<SelectListItem>)ViewBag.Countries, "--Select--", new { #class = "form-control" })
jQuery to trigger the DDL click event
$('#ddlCountries option:not(:first)').click(function () {
runCode()
});
jQuery to disable the first option
jQuery('#ddlCountries option:contains("--Select--")').attr('disabled', 'disabled');
Get the index of the selected option and check to see if it's greater than 0 on event fire. Indexes are 0 based.
$('#ddlcountries').on('change', function() {
var index = $(this).find('option:selected').index();
if (index > 0) {
alert('yay');
runCode();
} else {
alert('nay');
return;
}
})
I deleted the code to disable the first option because I couldn't get it to stay disabled after the first change. I modified the jQuery to trigger the event to:
jQuery('#ddlCountries').find('option:gt(0)').click(function () {
runCode()
});
Then I added styling to the --Select-- box to make it gray. You can still click on it but it won't do anything. Not exactly what I was trying to do but close enough
Related
My HTML page has a Button and a Select Drop-Down (Combo Box). Drop-Down change event is like this:
$('#DDL_ID').on('change', function (e) {
// Some Code Here
});
When I click the button, I am setting some value to Drop-Down and it is working fine.
$('#BTN_ID').on('click', function (e) {
$('#DDL_ID').val('123');
});
When I click the button, Drop-Down value is getting changed but Drop-Down change event is not firing. Can anyone help me on this?
Please note this is not a duplicate question.
Setting the val() through jquery will not automatically trigger the event on the item... so you need to manually trigger() it...
$('#BTN_ID').on('click', function (e) {
$('#DDL_ID').val('123').trigger('change');
});
Not to sure how to attack the following scenario.
I have a form with a row which is drag and drop-able and this is working perfectly. The issue I have is that I want to disable some buttons when the rows do not match page load and re-enable when they do.
I have the below jQuery code so far:
var $form = $('form'),
origForm = $form.serialize();
// Drag & drop for existing rules
$(function () {
$("#sortableRows").sortable();
$("#sortableRows").disableSelection();
});
// Check to see if form defaults have changed
$('form :input').change(function () {
if ($form.serialize() !== origForm) {
addDisable();
} else {
removeDisable();
}
});
// Added the disabled attribute when form changes
var addDisable = function () {
$("button[name='addButton'], button[name='modifyButton'], button[name='deleteButton'], button[name='activeButton'], button[name='inactiveButton'], input[name='searchDialPlanBox']").attr('disabled', true);
}
// Removes the disabled attribute
var removeDisable = function () {
$("button[name='addButton'], button[name='modifyButton'], button[name='deleteButton'], button[name='activeButton'], button[name='inactiveButton'], input[name='searchDialPlanBox']").removeAttr('disabled');
}
As I said the drag and drop and the disable/enable functions are working fine of everything else e.g. I disable the listed buttons when an input is changed but no sure on on how to do this when the div row is moved.
Got part of it working but stuck on when moving other divs as the first on works fine but other always fall into the Else
Drag & Drop Does Not Disable Buttons As Doesn't Fall Into Correct IF Statement
You can also give callback function like below for sortable
$( ".selector" ).sortable({
change: function( event, ui ) {}
});
Where is the code responsible for drag and drop handling?
For now Ill assume that is done by .sortable(). Then you would have to look into the docs of this function and search for events which are triggered on drag/drop and attach an listener which then calls disable/enable button.
Something like:
/*...*/.sortable({
dragStart: addDisable,
dragEnd: removeDisable
})
If you want to enable/disable depending on certain conditions then of course you have to implement that in the event handler too.
I have a table and I use select menu in each row for different actions for that specific row.
For example:
$(document).on('change', '.lead-action', function() {
// Do stuff
}
this method gets the value of the selected option. Based on the selected value, I display different popups. When the user leaves the page, the select menu retains the previously selected option.
Sometimes users click on the same option in the select menu. When they do, the above code doesn't work.
Is there a way to invoke the code block above if the same option in the select menu is selected?
I'm gathering that you just want the dropdown to fire anytime a selection is made. If so, check out the answer to Fire event each time a DropDownList item is selected with jQuery.
See my updated answer below:
You can use this small extension:
$.fn.selected = function(fn) {
return this.each(function() {
var clicknum = 0;
$(this).click(function() {
clicknum++;
if (clicknum == 2) {
clicknum = 0;
fn(this);
}
});
});
}
Then call like this:
$(".lead-action").selected(function(e) {
alert('You selected ' + $(e).val());
});
Update:
I'm actually rather unhappy with the original script. It will break in a lot of situations, and any solution that relies on checking the click count twice will be very fickle.
Some scenarios to consider:
If you click on, then off, then back on, it will count both clicks and fire.
In firefox, you can open the menu with a single mouse click and drag to the chosen option without ever lifting up your mouse.
If you use any combination of keyboard strokes you are likely to get the click counter out of sync or miss the change event altogether.
You can open the dropdown with Alt+↕ (or the Spacebar in Chrome and Opera).
When the dropdown has focus, any of the arrow keys will change the selection
When the dropdown menu is open, clicking Tab or Enter will make a selection
Here's a more comprehensive extension I just came up with:
The most robust way to see if an option was selected is to use the change event, which you can handle with jQuery's .change() handler.
The only remaining thing to do is determine if the original element was selected again.
This has been asked a lot (one, two, three) without a great answer in any situation.
The simplest thing to do would be to check to see if there was a click or keyup event on the option:selected element BUT Chrome, IE, and Safari don't seem to support events on option elements, even though they are referenced in the w3c recommendation
Inside the Select element is a black box. If you listen to events on it, you can't even tell on which element the event occurred or whether the list was open or not.
The next best thing is to handle the blur event. This will indicate that the user has focused on the dropdown (perhaps seen the list, perhaps not) and made a decision that they would like to stick with the original value. To continue handling changes right away we'll still subscribe to the change event. And to ensure we don't double count, we'll set a flag if the change event was raised so we don't fire back twice:
Updated example in jsFiddle
(function ($) {
$.fn.selected = function (fn) {
return this.each(function () {
var changed = false;
$(this).focus(function () {
changed = false;
}).change(function () {
changed = true;
fn(this);
}).blur(function (e) {
if (!changed) {
fn(this);
}
});
});
};
})(jQuery);
Instead of relying on change() for this use mouseup() -
$(document).on('mouseup', '.lead-action', function() {
// Do stuff
}
That way, if they re-select, you'll get an event you can handle.
http://jsfiddle.net/jayblanchard/Hgd5z/
I've got a base background image and two checkboxes. I need replace the background image (via toggle class) with the correct class depending on which checkbox is selected. If both checkboxes are selected I need it to show the black background.
http://jsfiddle.net/2k96D/6/
$('#ax_lab').change(function () {
if ($('#ax_ov').is(':checked')) {
$('.axial').toggleClass('axial_all');
} else{
$('.axial').toggleClass('axial_lab');
}
});
$('#ax_ov').change(function () {
if ($('#ax_lab').is(':checked')) {
$('.axial').toggleClass('axial_all');
} else{
$('.axial').toggleClass('axial_over');
}
});
My fiddle works perfectly when I select and deselect in the same order, however, if I de-select the checkboxes in a different order than the order I selected them in, it doesn't default back to the original class. I know there must be a flaw in my logic, I'm just having trouble finding it. Any thoughts?
You need to be more explicit with the logic. Here's what I did:
$(document).ready(function () {
function updateAxialStatus() {
var axOv = $('#ax_ov').prop('checked'),
axLab = $('#ax_lab').prop('checked');
$('.axial').removeClass('axial_all axial_lab axial_over');
if (axOv && axLab)
$('.axial').addClass('axial_all');
else if (axOv)
$('.axial').addClass('axial_over');
else if (axLab)
$('.axial').addClass('axial_lab');
}
$('#ax_lab, #ax_ov').change(updateAxialStatus);
});
That version just explicitly checks the status of the two checkboxes and updates the class to reflect the status. The same handler can be used for both checkboxes.
Note that old versions of IE may not fire the "change" event for checkboxes until the checkbox loses focus, but you can safely use "click" instead.
I have links that when clicked, select all the checkboxes or deselect them.
I also have a dropdown list that I want to be made visible only if at least one of the checkboxes are selected.
What is the best way to do this?
Should I write login inside the code that selects/deleselects them or is there a better way to do this?
I would have a function that sets the dropdown's visibility. I would call this function from the click handlers for each of the checkboxes and from the link's handlers -- I'm assuming that your link handlers don't merely fire a click event on each box, but set it's status. Unless you have other behavior to trigger firing the click event on each checkbox will be very expensive. In your function that set's visiblity, use a test to see if the number of checked boxes is greater than 0 as the new state for the visibility.
function setDDVisibility() {
var isVisible = $('.checkbox-class-selector:checked').length > 0;
if (isVisible) {
$('#ddl').show();
}
else {
$('#ddl').hide();
}
}
$('.checkbox-class').click( function() {
... do stuff ...
setDDVisibility();
return false;
});
$('.link-selector').click( function() {
...set up checkboxes...
setDDVisibility();
return false;
});