Removing duplicates from a dropdownlist - javascript

I have a dropdown that is returning duplicates. I don't know why it is returning duplicates.
Here is the control for my dropdown.
#Html.DropDownList("procDateId", Model.GetEmpHoursDateRange.EmphoursdateSelectList, Model.GetEmpHoursDateRange.selectedEmplhoursdate, new { id = "procDateId" })
I want to be able to remove the duplicates once the page load.
I tested the code below with an alert and am able to get to the document.ready
$(document).ready(function () {
alert("here you go !!!");
[].slice.call($('#procDateId').option)
.map(function (a) {
if (this[a.innerText]) {
$('#procDateId'.option).removeChild(a);
} else {
this[a.innerText] = 1;
}
}, {});
});
Here is the html that my dropdown is rendering.
<select id="procDateId" name="procDateId">
<option value>1/11/2017</option>
<option value>1/11/2017</option>
<option value>1/10/2017</option>
<option value>1/9/2017</option>
</select>
The duplicates are not been removed with my code above. No luck. Kindly assist.

Your jQuery selector for the option appears incorrect: $('#procDateId').option --> ('#procDateId option')
Additionally, you can call remove on the option directly
jsfiddle: https://jsfiddle.net/db9zczr0/

The reason for the double up is you're using an overload with the defaultOption = Model.GetEmpHoursDateRange.EmphoursdateSelectList. The value returned is the duplicate.
The default option appears at the start of the list and its value is
empty. A default option is used to communicate that no option is being
chosen from the list, such as when the drop-down control represents an
optional parameter.
From https://msdn.microsoft.com/en-us/library/gg548012(v=vs.111).aspx
So you will want to use a different overload, e.g.
HtmlHelper.DropDownList Method (String, IEnumerable,
Object)
Then to tell the View to show the selected option using the saved session value, in the controller loop over the IEnumerable<SelectListItem> and set Selected = true for the matching item.

Related

Select element returning value only when disabled

I have a select box as follows:
<select id="selectbox" class='info-entry-select' name="country">
<option value="1" selected="selected">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
This select box is in a hidden div that, when appearing, refreshes the select box options using ajax and a separate php file. Here's the javascript that updates the select box:
$("#changeselectoptions").on('click', function() {
$.ajax({
type: "GET",
url: "includes/selectoptions.php",
dataType: 'json',
success: function(result){
// Replace options of select box
var $el = $("#selectbox");
var newOptions = result['catsOrderList'];
// newOptions correctly returns an array in the form of {1: "One", 2: "Two", 3: "Three", 4: "Four"}
$el.empty(); // remove existing options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>").attr("value", key).text(value));
});
}
});
return false;
});
If I now call: $('#selectbox').val(); I get undefined and I'm not sure why? To make matters more confusing, if I disable #selectbox (using a toggle switch that adds .attr('disabled', 'disabled'); to #selectbox, then try $('#selectbox').val(); I get the expected val of 1, 2, 3, etc.
How can I get this value without disabling the box, or what have I overlooked?
Edit:
I've been asked where my $('#selectbox').val(); call is. It's not any more involved than I mentioned above, but to be thorough, it's called from a submit button in the same div as the select element as follows:
$("#submitbutton").on('click', function() {
var selectBoxVal = $('#selectbox').val();
console.log('value is: ' + selectBoxVal);
return false;
});
My only idea so far is that it may be a dom issue? I say that ignorantly as my knowledge doesn't quite know the full ins and outs but I've seen issues where elements are altered live by javascript and not retrieved correctly by later javascript calls - whereas they work fine if the elements being retrieved existed when the page loaded.
I don't assign a selected property to any of the options but I don't believe this should cause undefined to be returned. For example, if I disable the select box, the value is returned correctly from the same query (as mentioned above) yet it still doesn't have a selected property added manually. I digress, but is it required to add a selected property when creating a series of options in javascript? Which option is initially presented as selected is irrelevant to me from a usage point of view but I'd be happy to follow best procedures. I assumed that the browser interpreted the displayed option as selected if none were marked as such.
I believe that the "value" of the select will be the <option> that has the attribute "selected" within that selectbox. Otherwise, there is no indicated value for that input.

How to avoid subscriptions from firing on the initialization of data-bound dropdowns?

I want to find the best practice to avoid an observable subscription from firing on page startup.
The Problem:
When you have something like the example described below, the alert will be displayed on startup, which is unwanted:
foo.someProperty = ko.observable(null);
foo.someProperty.subscribe(function () { alert(foo.someProperty()); });
Inconvenient Solution:
Until now I've been using the following solution:
foo.someProperty.subscribe(function () {
if (TriggersEnabled()) { alert(foo.someProperty()) };
});
The TriggersEnabled check avoids the callback execution, but this solution demands the creation of the TriggersEnabled property. Also it must be set as false before startup and as true after the complete page load.
The Question
Can I avoid this? Is there any other methods to achieve the same result?
Based on the fiddle you provided the event is firing because the default value you have bound to the select element is not a value in the list. So when the select list displays it changes the value of the observable it's bound to to the first option.
A way to fix this is to make sure the default value of the observable you bind to the select element is a valid value.
Example:
var page = new PageVM();
function PageVM () {
var vm = this;
vm.someProperty = ko.observable(''); //Provide a default value that will be in the select list
vm.someProperty.subscribe(function () { alert(vm.someProperty()); });
};
ko.applyBindings(page);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
foo.someProperty
<select data-bind="value: someProperty">
<!-- make sure the first option matches the default value of someProperty -->
<option value="">Select...</option>
<option value="01">Option 01</option>
<option value="02">Option 02</option>
</select>

How to change data on select option dropdown

need a small help to change data from option selected.
The data is populated first to the dropdown option list from a JSON result, in the same JSON is the second data thta need to be changed on select the option from dropdown.
What i want os to change the price on select the store.
This is my javascript code:
$(function() {
var pricestore = [{"product_id":"1","store_id":"1","price":"120.00","sequence":"0","id":"1","parent_id":"0","name":"Store 1","email":"store1#store1.com"},{"product_id":"1","store_id":"2","price":"140.00","sequence":"0","id":"2","parent_id":"0","name":"Store 2","email":"store2#store2.com"}];
$.each(pricestore, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
}),
//Trying to populate the price on div id
$$('#price-store').each(function(el) {
el.innerHTML = pricestore;
});
})
This is the HTML to get the data
<select id="sel"></select>
<div id="price-store"></div>
Here is also an example on jsfiddle
http://jsfiddle.net/A386B
Any help is appreciated.
Check this:-
Demo
As per what i understood from your question you need to show the price in the div as the dropdown values are changed. You can use below method. You need to use use a change event on the dropdown.
This approach uses Index() of the option element selected and retrieves the corresponding record from JSON.
$('#sel').change(function () {
$('#price-store').text(
pricestore[$('option:selected', this).index()].price);
});
Another way is to use data-attributes on the option element to store the respective price and retrieve it on change of dropdown value.
Demo
$('#sel').append($('<option>',
{
"value" :option.id,
"data-price" :option.price
}).text(option.name));
}),
$('#sel').change(function () {
$('#price-store').text($('option:selected', this).data('price'));
});
You use $$ to select your div instead of $. $('#price-store')
The second parameter of the function passed to the .each() method is the element not the first. function(i, el) {
Why are you using .each() for one div?
You'll have to format the data in pricestore to display it in a div, otherwise all you'll get is [Object object],[Object object].
Or this one:
<div id="price-store"></div
<form>
<select id="price">
<option>120</option>
<option>140</option>
<option>160</option>
</select>
</form>
and:
$('#price').change(function() {
$('#price-store').text($('#price').find(":selected").text());
});
http://jsfiddle.net/XcSZL/8/

Resetting Select2 value in dropdown with reset button

What would be the best way to reset the selected item to default? I'm using Select2 library and when using a normal button type="reset", the value in the dropdown doesn't reset.
So when I press my button I want "All" to be shown again.
jQuery
$("#d").select2();
html
<select id="d" name="d">
<option selected disabled>All</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I'd try something like this:
$(function(){
$("#searchclear").click(function(){
$("#d").select2('val', 'All');
});
});
You can also reset select2 value using
$(function() {
$('#d').select2('data', null)
})
alternately you can pass 'allowClear': true when calling select2 and it will have an X button to reset its value.
version 4.0
$('#d').val('').trigger('change');
This is the correct solution from now on according to deprecated message thrown in debug mode:
"The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead"
According to the latest version (select2 3.4.5) documented here, it would be as simple as:
$("#my_select").select2("val", "");
you can used:
$("#d").val(null).trigger("change");
It's very simple and work right!
If use with reset button:
$('#btnReset').click(function() {
$("#d").val(null).trigger("change");
});
The best way of doing it is:
$('#e1.select2-offscreen').empty(); //#e1 : select 2 ID
$('#e1').append(new Option()); // to add the placeholder and the allow clear
I see three issues:
The display of the Select2 control is not refreshed when its value is changed due to a form reset.
The "All" option does not have a value attribute.
The "All" option is disabled.
First, I recommend that you use the setTimeout function to ensure that code is executed after the form reset is complete.
You could execute code when the button is clicked:
$('#searchclear').click(function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
Or when the form is reset:
$('form').on('reset', function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
As for what code to use:
Since the "All" option is disabled, the form reset does not make it the selected value. Therefore, you must explicitly set it to be the selected value. The way to do that is with the Select2 "val" function. And since the "All" option does not have a value attribute, its value is the same as its text, which is "All". Therefore, you should use the code given by thtsigma in the selected answer:
$("#d").select2('val', 'All');
If the attribute value="" were to be added to the "All" option, then you could use the code given by Daniel Dener:
$("#d").select2('val', '');
If the "All" option was not disabled, then you would just have to force the Select2 to refresh, in which case you could use:
$('#d').change();
Note: The following code by Lenart is a way to clear the selection, but it does not cause the "All" option to be selected:
$('#d').select2('data', null)
If you have a populated select widget, for example:
<select>
<option value="1">one</option>
<option value="2" selected="selected">two</option>
<option value="3">three</option>
...
you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:
$('button[type="reset"]').click(function(event) {
// Make sure we reset the native form first
event.preventDefault();
$(this).closest('form').get(0).reset();
// And then update select2 to match
$('#d').select2('val', $('#d').find(':selected').val());
}
Just to that :)
$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
$(this).change();
});
What I found works well is as follows:
if you have a placeholder option like 'All' or '-Select-' and its the first option and that's that you want to set the value to when you 'reset' you can use
$('#id').select2('val',0);
0 is essentially the option that you want to set it to on reset. If you want to set it to the last option then get the length of options and set it that length - 1. Basically use the index of whatever option you want to set the select2 value to on reset.
If you don't have a placeholder and just want no text to appear in the field use:
$('#id').select2('val','');
To achieve a generic solution, why not do this:
$(':reset').live('click', function(){
var $r = $(this);
setTimeout(function(){
$r.closest('form').find('.select2-offscreen').trigger('change');
}, 10);
});
This way:
You'll not have to make a new logic for each select2 on your application.
And, you don't have to know the default value (which, by the way, does not have to be "" or even the first option)
Finally, setting the value to :selected would not always achieve a true reset, since the current selected might well have been set programmatically on the client, whereas the default action of the form select is to return input element values to the server-sent ones.
EDIT:
Alternatively, considering the deprecated status of live, we could replace the first line with this:
$('form:has(:reset)').on('click', ':reset', function(){
or better still:
$('form:has(:reset)').on('reset', function(){
PS: I personally feel that resetting on reset, as well as triggering blur and focus events attached to the original select, are some of the most conspicuous "missing" features in select2!
Select2 uses a specific CSS class, so an easy way to reset it is:
$('.select2-container').select2('val', '');
And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.
Sometimes I want to reset Select2 but I can't without change() method. So my solution is :
function resetSelect2Wrapper(el, value){
$(el).val(value);
$(el).select2({
minimumResultsForSearch: -1,
language: "fr"
});
}
Using :
resetSelect2Wrapper("#mySelectId", "myValue");
For me it works only with any of these solutions
$(this).select2('val', null);
or
$(this).select2('val', '');
// Store default values
$('#filter_form [data-plugin="select2"]').each(function(i, el){
$(el).data("seldefault", $(el).find(":selected").val());
});
// Reset button action
$('#formresetbtn').on('click', function() {
$('#filter_form [data-plugin="select2"]').each(function(i, el){
$(el).val($(el).data("seldefault")).trigger('change');
});
});
If you want to reset forms in edit pages, you can add this button to forms
<button type="reset" class="btn btn-default" onclick="resetForm()">Reset</button>
and write your JS code like this:
function resetForm() {
setTimeout(function() {
$('.js-select2').each(function () {
$(this).change();
/* or use two lines below instead */
// var oldVal = $(this).val();
// $(this).select2({'val': oldVal});
});
}, 100);
}
Lots of great answers, but with the newest version none worked for me. If you want a generic solution for all select2 this is working perfectly.
Version 4.0.13 tested
$(document).ready(function() {
$('form').on('reset', function(){
console.log('triggered reset');
const $r = $(this);
setTimeout(function(){
$r.closest('form').find('.select2-hidden-accessible').trigger('change');
}, 10);
});
});
$(function(){
$("#btnReset").click(function(){
$("#d").select2({
val: "",
});
});
});
to remove all option value
$("#id").empty();

jQuery serialize remove empty Select

I have a big form, that will be serialized by a jQuery function.
The problem is that I need to remove from this form before being serialized all the empty values.
I found a way to successfully remove all the empty input text fields, but not the selections.
It does not work properly with select dropdowns.
Ceck below:
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$('#submForm').validate({
submitHandler: function(form) {
// Do cleanup first
$('input:text[value=\"\"]', '#submForm').remove();
$('select option:empty', '#submForm').remove();
var serialized = $('#submForm').serialize();
$.get('".$moduleURL."classes/DO_submission.php', serialized);
window.setTimeout('location.reload()', 8000);
return false;
form.submit();
}
})
});
It should completely remove the dropdown selections where the values are empty. Not only the options but the entire select box should not be included in the serialize function.
How do I achieve this?
$('select option:empty', '#submForm').remove();
This code is not working as it should..
First, a select can not have an empty value. It will default to the first option if the selected attribute is not set.
Second, $('select option:empty') selects the empty options. To do something, an option should have a value, so afaik the selector will never work.
What you need to do is check all selects to see if they have a different value than their default, and if it is not the case, remove them.
If with 'empty select' you mean that the user has not chosen a 'valid' option (for example the fist option of a select is <option value=''>Select your value</option> )why don't you iterate on the select and check their value?
$('select').each(function(){
if ($(this).val() === ''){//this assumes that your empty value is ''
$(this).remove();
}
});
EDIT - sorry for the error, i missed the last parenthesis, i tried it and it works for me
I would just instead of serlizing the the whole form I would use jquery Form and then all you have to do is call
$('#submForm').ajaxSubmit({/.../});
Try
$('select option:selected:empty').parent().remove();
Edited after reading Nicola's comment.

Categories

Resources