Remove option from selected list based of index? - javascript

I have two select lists and based off the selected index of either one I need to remove the option at that index from both lists.
I have seen example of doing this for the currently selected option using the remove() function but that would only work for one list as the other list might have a different option selected or none at all.
Knowing just the index value is it possible to do this with JavaScript / jQuery? I already have the code that figures out which list to pull the index from and get that index value. I just have not found a way to specify an index value for the removal.
Code developed based off comment:
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOptionIndex;
if (codeType == "Project")
{
selectedOptionIndex = $("#SelectedProjects :selected").index();
}
else
{
selectedOptionIndex = $("#SelectedTasks :selected").index();
}
alert(selectedOptionIndex);
selectedProjectsField.eq(selectedOptionIndex).remove();
selectedTasksField.eq(selectedOptionIndex).remove();
}

Using The :eq() Selector
You could use the :eq() selector to target a specific element by it's index and then call remove() to remove it from the DOM :
// Syntax Example: This will remove then (index)th option element
$('select option:eq(index)').remove();
So in your case, you would simply want to concatenate your selectedOptionIndex into the selector to target selector using one of the following :
// Remove a specific option of your SelectedProjects element
$('#SelectedProjects option:eq(' + selectedOptionIndex + ')').remove();
Example
You can see an interactive example here and demonstrated below :

This code should work:
$('#SelectedProjects option')[index].remove();
$('#SelectedTasks option')[index].remove();
or
selectedProjectsField.find('option')[selectedOptionIndex].remove();
selectedTasksField.find('option')[selectedOptionIndex].remove();

Related

Kendo dropdownliast select element containing a substring

I have a Kendo DropDownList what I have to select an element by the text containing 8. I can select element by the full string, I only need to select it by a substring.
The partly working code looks like:
var ddlist = $("#HibaTipusKod_" + munkatargyaId).data("kendoDropDownList");
console.log(ddlist);
ddlist.value("8/a");
ddlist.trigger("change");
My need is:
ddlist.value(*startswith/contains*"8");
ddlist.trigger("change");
At the logging I can see it right.
You could try this:
var options = ddlist.dataSource.options.data;
$.each(options, function(i, item) {
if (item.text.indexOf('8') !== -1) {
dropdownlist.select(i);
return false;
}
});
Demo
Bare in mind that using indexOf to search for the sub-string will be case sensitive, there are lots of alternative methods that could better suit your needs in this question.

JavaScript - Find ID that matches data attribute value

I have a variable that finds the data attribute of an element that is clicked on in a callback function:
var dropdown = document.getElementsByClassName('js-dropdown');
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", callBack (dropdown[i]));
}
function callBack (i) {
return function () {
var thisDropdown = i.getAttribute('data-dropdown');
//rest of the code here
}
}
I am basically trying to do this
$('#' + thisDropdown ).toggleClass('is-active');
...but in vanilla JS.
This works fine using jQuery however I would like a vanilla version.
So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class.
I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for.
I've been trying to do something along the lines of
var idValue = document.getElementById(thisDropdown);
Then
var findId= idValue + thisDropdown;
findId.toggleClass('is-active');
Obviously that does not work the same way the jQuery statement works... any ideas?
Ignore the toggleClass method! Some of you may find this contradictory as I want vanilla JS.
To replace $('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList. Like this:
const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");
I like #kamyl's answer, but you might need backward compatibility. For that, see if you can find a polyfill.
If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; add if not, remove if so...then array.join(" ") and replace the class attribute with it.

Removing all dynamic 'data attributes' of an Element [duplicate]

This question already has answers here:
Remove multiple html5 data-attributes with jquery
(7 answers)
Closed 8 years ago.
I have a div where dynamic data- attributes get added on some tags.
(name of data- attributes to be generated dynamically by script, so there is no way my script will know the NAME of data-attribute)
<div data-1223="some data" data-209329="some data" data-dog="some value"> </div>
Now, I want to write a code in which it resets the div by removing all the data attributes and their values.
I can use
$('div').attr('data-209329',"")
but the problem is I don't know the name of data-attribute that will be added.
the data-attribute that will be added is dynamic and I don't have control of it.
removing div and reinserting div is not an option.
Pls help.
thanks in advance
YOu can use like this
var data = $("div").data();
var keys = $.map(data, function (value, key) {
return key;
});
for (i = 0; i < keys.length; i++) {
$("div").removeAttr("data-" + keys[i]);
}
Fiddle
Edit
Suggested by #Mottie
$.each($('div').data(), function (i) {
$("div").removeAttr("data-" + i);
});
Demo
You can use this code :
var data = $('div').data();
for(var i in data){
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
}
The $('div').data(); prepare a list of all data attributes in var data variable.
Then you can work with it.
This is fiddle of this solution.
UPDATE
Suggested by #Mottie
$.each($('div').data(), function (i) {
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
});
I think that the removeData() function is what you are looking for here. This will remove all data information stored on the element.
The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value; when called with no arguments, all values are removed. Removing data from jQuery's internal .data() cache does not affect any HTML5 data- attributes in a document; use .removeAttr() to remove those.
It will not however remove the actual attributes from the elements. In order to remove the actual attributes, you'll need to extract a list of the existing attributes. You could do this by inspecting the data() function of an element (before running removeData).
The data() function will return an object of key => value pairs that you can then use to remove the actual attributes from the element using removeAttr().

Javascript dropdownlist

How can I get the previous selected index on change event of dropdown list using Javascript.
No, it is not possible, but you can use a variable inside onchange event that tracks the previous selection
Example:
var previousSelected;
function track(d){
if(typeof previousSelected != 'undefined'){
alert("Previous selected value " + previousSelected );
}
previousSelected = d.selectedIndex;
alert("selected value " + d.selectedIndex);
}
Place a meta variable in the ul or ol object that is the index of the last selected item so that when you goto the item again you can just ask for that property again and, presto, you know the index of the last selected item.
A common way of placing a meta variable inside an object is by adding a class to the last item that was selected with javascript and then finding the list item with that class when you want to see which one was selected. I see JQuery users doing this alot (btw you should be using JQuery to help with all of your javascript).
For example, to mark the last item as selected:
$('ul li:last').addClass('selected');
Then to find it again:
$('ul li.selected')
Its actually a pretty easy way of tracking this kind of code.
You could have a javascript global variable which will track this value. So when the change event is trigerred you would have the new value and the old one. Then you would update the global variable with the new value.
Here's an example pseudo code:
var selectedValue = '';
document.getElementById('someId').onchange = function() {
var newValue = this.value;
// TODO: compare with the old value
selectedValue = newValue;
};

determining if a field exists on a form

I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
You're using document.getElementById, but form elements have a name.
Try f.elements.namedItem("exclusions") instead of exclusions != null
Multiple elements in the same page cannot share an id attribute (ie. id must be unique or unset). As well, though some (older) browsers erroneously collect elements whose name matches the ID being looked for with getElementById, this is invalid and will not work cross-browser.
If you want to get a group of elements, you can give them all the same name attribute, and use document.getElementsByName to get the group. Note that the result of that will be a NodeList which is kind of like an array in that it can be iterated over.
Do all the checkboxes have the same id == exclusions?
If yes, then you must first correct that.
Before you do so, did you try checking the first checkbox and see if the if condition goes through?
if you have more than one element with the id "exclusions" it will screw up the functionality of getElementById. I would remove the duplicate "exclusions" ids from all of your elements and use getElementByName() instead, and give your group of checkboxes the name="exclusions" instead.
Edit:
But there is a much simpler way using jQuery, and it gives you some cross browser compability guarrantee. To do the same thing with jQuery do this:
var checkBoxesExist = $('[name=exclusions]').count() > 0;
Or if you have given your elements unique ID's then you can do this:
var checkbox1exists = $('#checkBox1').count() > 0;
Each element must have a unique ID.
Then, you can check just like this:
if (document.getElementById('exclusions1')) {
//field exists
}
Or if you need to loop through a bunch of them:
for (x=0; x<10; x++) {
if (document.getElementById('exclusions' + x)) {
//field X exists
}
}

Categories