How to trigger dropdownlist onchange when setting selected from DataController - javascript

I have an MVC View (https://mydomain/Data/MyChart) that contains a dropdownlist where the onchange event triggers an ajax call to get data to populate a chart. This is working perfectly.
I now want to add the functionality whereby I could call this view and pass the item to select via a querystring parameter.
https://mydomain/Data/MyChart?station=ChartA
When doing this, I can retrieve the querystring value, and successfully set the item selected in the dropdownlist, however the onchange event does not triggered so the chart is not generated.
What am I missing?
.NET Fiddle to demo selecting dropdown and getting value in change event
https://dotnetfiddle.net/uZi8LU
.NET Fiddle demonstrating setting a value (querystring) to set the selected item and onchange NOT triggered:
https://dotnetfiddle.net/kCJMC4

Your new functionality pre-loads the page with a selected value, so the element it is not changed after the document is ready (for the pre-loaded value). The new functionality requires a once-off ajax call immediately once the document is ready:
<script type="text/javascript">
$(document).ready(function () {
alert($("#StationGroup option:selected").text());
// StationId Dropdown change function
$("#StationGroup").change(function () {
alert($("#StationGroup option:selected").text());
});
});
</script>

Related

what is the best jsript event handler to use when data is change through other script for select? [duplicate]

The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
$(function() {
$(":input#single").change(function() {
/* Logic here does not execute when val() is used */
});
});
$("#single").val("Single2");
</script>
Because the change event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
I believe you can manually trigger the change event with trigger():
$("#single").val("Single2").trigger('change');
Though why it doesn't fire automatically, I have no idea.
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
As far as I can read in API's. The event is only fired when the user clicks on an option.
http://api.jquery.com/change/
For select boxes, checkboxes, and
radio buttons, the event is fired
immediately when the user makes a
selection with the mouse, but for the
other element types the event is
deferred until the element loses
focus.
To make it easier, add a custom function and call it whenever you want to change the value and also trigger a change:
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTrigger("NewValue");
Or you can override the val() function to always call the change when val() is called:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
In case you don't want to mix up with default change event you can provide your custom event
$('input.test').on('value_changed', function(e){
console.log('value changed to '+$(this).val());
});
to trigger the event on value set, you can do
$('input.test').val('I am a new value').trigger('value_changed');
If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:
window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);
I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.
So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below.
The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.
Here's the code i use:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
if (arguments.length >= 1) {
// setter invoked, do processing
return originalVal.call(this, value).trigger('change');
}
//getter invoked do processing
return originalVal.call(this);
};
})(jQuery);
$(":input#single").trigger('change');
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');
And the first event worked.
To change the value
$("#single").val("Single2");
Also to trigger a change event
$("#single").val("Single2").change();
this logic is instrumental when multiple select options are on a page.
one changes and other select options have to change but do not trigger a change event.

Select change event issue

My issue is that the change event will trigger whenever there is a change made in select element which also includes the page load when select element is populated with items and I don't want this.
I only want the change event (or some more proper event) to trigger ONLY when a selection is changed by the user via the mouse or keyboard.
In WPF this is resolved by having change and selectionchange events which correspond to the second scenario that I want.
<select id="filter_notification_byproductname" name="filter_notification_byproductname" asp-for="#Model.FilterByProductName" class="notification_list_list_filter_controll_input" asp-items="#Model.ProductDictionaryOfSelectListItemsForFiltering.Keys" multiple></select>
#section Scripts {
<script type="text/javascript">
$("#filter_notification_byproductname").bind("change", {
productChanged: true
}, SendIndexes);
function SendIndexes(productChanged) {
// SEND DATA TO THE SERVER
}
}
</script>
}

How Can I Triger Change Event For HTML Select (Dropdown)?

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');
});

When input box is filled through jquery, the ajax function should be called

I have a form which is populated according to the item selected from popup form. When the input box named "organization" is populated the ajax function should be called. Any idea is highly appreciated ?
If I understand correctly you want to call an ajax function when an input is filled. You can bind an event to your input with
$('#your_input_id').on('blur', function() {
//your ajax call
});
this way your ajax function will be called when the focus is lost on your input
You could also bind when the user presses return / use a timer function to call the ajax function when the user stops typing for X seconds
You want event handler which calls by name attribute so the following code will work :
$('input[name="Organization"]').on('blur', function() {
//your ajax call
});
You can use
focusout jquery method
$('#your_input_id').focusout(function() {
// do stuff here
// use constraint .. it field is not empty whatever is it require
})
More detail Official site

How to alternate 2 onchange() functions in mvc razor?

I have cascade drop down lists and I should to send form data to controller in every onchange() event. That is why I should to do 2 different operations on onchange() event of dropdownlist.
1) This sends data to controller in every onchange() event of dropdowlists:(It is my first dropdownlist)
#Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as IEnumerable<SelectListItem>, "-",
new { id = "CategoryDDL", onchange = "$('#MyForm').trigger('submit');" })
2)This is for cascade dropdownlists:
<script type="text/javascript">
$(function () {
$("#CategoryDDL").change(
function () {
loadLevelTwo(this);
});
loadLevelTwo($("#CategoryDDL"));
});
function loadLevelTwo(selectList) {
// my some code...
}
</script>
In this case when I change CategoryDDL drop down list, 2 operations mix. It tries to do 2 operation together.
I want to alternate them. Firstly cascading operation works, then data submit operation works.
How can I do this?
EDIT:
Without loadLevelTwo() function, everything works well: when I change dropdown list, request goes to the controller to filter products.
Then I added loadLevelTwo() for cascading dropdown list. Because I have 2 dropdownlist. I want when I change first dropdownlist, second dropdownlist updated automatically. My script does this. But, these events together works mixed. In the controller, I have actions for filtering an for cascading drop down:
public ActionResult FilterProducts(CriteriaModel model) {}
and
public ActionResult GetSubCategoryByCategoryId(int id) {}
These methods work in same time. One line works in any action, then gets into other action. then come backs first action, So, it is surrounded while actions return view.
I send form after loadLevelTwo() function, but it doesn't fix the issue:
loadLevelTwo($("#CategoryDDL"));
$('#MyForm').trigger('submit');
I'd get rid of the onchange on server side and do everything on clienside :
$(function () {
$("#CategoryDDL").change(
function () {
loadLevelTwo(this);
});
loadLevelTwo($("#CategoryDDL"));
$('#MyForm').trigger('submit');
});
It is still not clear what you are asking to do. If you simply want to submit the form and call loadLevelTwo, you can do that through a single binding in your script (and remove the onchange from razor):
$(function () {
$("#CategoryDDL").on('change', function() {
loadLevelTwo(this); // load the next level
$("#MyForm").submit(); // submit the form
});
});
This will complete both tasks in succession.

Categories