Removing an option based on text instead of value - javascript

I want to remove an option from an select based on the text of the option.
I tried using this line of code:
$('#list_' + id + ' option[text="' + alias + '"]').remove();
Sadly this doesn't work for me, as it removes nothing. If I use value instead of text it works, but I was wondering how I can do this using text.
// Removing based on text doesnt work.
$('.removeByText').click(function() {
$('#list option[text="Option2"]').remove();
});
// Removing based on value works.
$('.removeByValue').click(function() {
$('#list option[value="2"]').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='list'>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
<option value='3'>Option3</option>
<option value='4'>Option4</option>
</select>
<button class='removeByText'>removeByText</button>
<button class='removeByValue'>removeByValue</button>

option elements don't have a text attribute. If you want to do it this way, you could use :contains:
$("#list_" + id + " option:contains(" + alias + ")").remove();
...but that does a substring match. Probably you'll want to filter:
$("#list_" + id + " option")
.filter(function() {
return this.textContent === alias;
})
.remove();
Live Example using filter:
setTimeout(() => {
const id = "example";
const alias = "B";
console.log(`Removing '${alias}'...`);
$("#list_" + id + " option")
.filter(function() {
return this.textContent === alias;
})
.remove();
}, 800);
<select id="list_example" size="3">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Delete item from dropdown menu with jQuery doesn't work

I found several topics here about removing items from a dropdown HTML element. However, when I try it, it fails from a script, but works in the console in browser.
The rest of the script works fine, and no errors are returned. First I have a variable with the item text, I let jQuery grab the corresponding value, and with that value I remove the item.
var topicToDelete = "topic3";
console.log(topicToDelete); //returns "topic3"
var dropdownValue = $('#pick_topic option').filter(function() {
return $(this).html() == topicToDelete;
}).val();
console.log(dropdownValue); //returns nothing
$('#pick_topic').find('option[value=' + dropdownValue + ']').remove(); //doesn't do anything
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic">
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>
Executing the code directly doesn't work either:
$('#pick_topic option').filter(function () { return $(this).html() == topicToDelete; }).remove(); // nothing
However, when I enter the lines in the browser console line by line it works and the item is removed from the dropdown menu. How can this be?
I have also looked into this answer.
The issue is because you've put a # in the value of the id attribute, as a result your jQuery selector isn't matching anything. This should be removed.
var topicToDelete = "topic3";
//console.log(topicToDelete); //returns "topic3"
var dropdownValue = $('#pick_topic option').filter(function() {
return $(this).html() == topicToDelete;
}).val();
//console.log(dropdownValue); //returns nothing
$('#pick_topic').find('option[value=' + dropdownValue + ']').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic"> <!-- note: no # here -->
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>
That being said, you're over-complicating the solution. filter() returns a jQuery object which you can remove directly. There's no need to get the value from that object, to then create another jQuery object pointing to the Element you already have access to. Try this:
var topicToDelete = "topic3";
$('#pick_topic option').filter(function() {
return $(this).html() == topicToDelete;
}).remove();
// alternative, using :contains which is a greedy match:
// $('#pick_topic option:contains(' + topicToDelete + ')').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic">
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>
Your code was good but remove # from id="pick_topic"
var topicToDelete = "topic3";
console.log(topicToDelete); //returns "topic3"
var dropdownValue = $('#pick_topic option').filter(function () { return $(this).html() == topicToDelete; }).val();
console.log(dropdownValue); //returns nothing
$('#pick_topic').find('option[value=' + dropdownValue + ']').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pick_topic">
<option value="1">topic1</option>
<option value="2">topic2</option>
<option value="3">topic3</option>
</select>

Using selector to replace all dropdownlist (select) with label

I'm trying to replace all the drop down lists with a p element or a label that have only the selected option, reason is I want to prepare this for printing without showing the down arrow that is in dropdownlist.
I need to use type selector as the select element have different classes name and no IDs. Problem is I can't seem to get the complete select element when I'm using $("select").
I notice when I use $("select") I got different results than using the ID selector in console
$("#id") //return
init {context: document, selector: "#2"}
var allInputs = $("select"); //return
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
allInputs[key].replaceWith("<p>" + text+ "</p>") //so this doesn't work
Here's a copy of the JS code
var allInputs = $("select");
if($("#2")==allInputs[0])
{alert("True");}
$.each( allInputs, function(key, value ) {
var text=value.find("option:selected").text() ;
allInputs[key].replaceWith("<p>" + text+ "</p>");
});
Jsfiddle here:
https://jsfiddle.net/abahrani/fzhv41s7/4/
how about use mapping (I did it with an unordered list but you get the idea) run the snippet below
$('#mybutton').click(function() {
$("select").map(function() {
return $(this)
}).get()
.forEach(function(element) {
$('#container').append(
`<ul><li>
${element.val()}<ul>${getOptions(element)}</ul>
</li></ul>`)
});
function getOptions(element) {
let html = ''
element.find('option').map(function() {
return $(this).val();
}).get()
.forEach(function(option) {
html += `<li>${option}</li>`
});
return html;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file">
<input type="text">
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
<select>
<option>selector</option>
<option>Option3</option>
</select>
</br>
<button type="button" id="mybutton">
print all options
</button>
</form>
<div id="container">
</div>
As per thmsdnnr comment, I found out the reason
allInputs[key].replaceWith("<p>" + text+ "</p>") // doesn't work
didn't work because I needed to use the $ sign, when $(allInputs[key]) used. everything worked.
$(allInputs[key]).replaceWith("<p>" + text+ "</p>") //works

Understanding the each jquery function - Unexpected output

I am trying to wrap my head around the each function. In this fiddle here
I would like to iterate through the selected elements of the list box one by one.
Essentially I was expecting an output like this
found itemA
found itemB
However I get an output like this
found itemA,itemB
I would like to know why that is happening and how I can fix it.
This is the code I am using
HTML
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>
JQuery
$( "#bid" ).click(function() {
$("#test").each(function () {
console.log("found " + $(this).val());
});
});
You are iterating over the select and not the options. The function you passed to each is getting called just once. Change your selector to #test > option and, like the comments on the question, change val() to text().
$( "#bid" ).click(function() {
$("#test > option").each(function () {
console.log("found " + $(this).text());
});
});
You have to specify the elements selector. Using only #test won't iterate over options because you didn't actually refer to it.
$("#bid").click(function() {
$("#test option").each(function() {
console.log("found " + $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>
You'll want to use
$.each($("#test").prop("options"), function () {
console.log("found " + this.value);
});
or
$("#test").children().each(function () {
console.log("found " + this.value);
});
Here is an example that might explain it more: https://jsfiddle.net/Twisty/dr1tay6f/6/
HTML
<select multiple="multiple" size="5" id="test">
<option value="a">Item A</option>
<option value="b">Item B</option>
</select>
<br>
<button type="button" id="bid">test</button>
JavaScript
$(function() {
$("#bid").click(function() {
$("#test option").each(function(ind, el) {
console.log("At Index " + ind +" found Option with Value: " + $(el).val() + " and Label of: " + $(el).html());
});
});
});
The $(selector).each(callback(index, element)); will iterate over each element in the selector, passing it's index and element to the function.

How to populate a dropdown select box by matching contained text?

I have created two identical dropdown select boxes as below:
HTML
<select id="ddl1" name="ddl1">
<option value="1">TEXT 1</option>
<option value="2">TEXT 2</option>
<option value="3">TEXT 3</option>
</select>
<select id="ddl2" name="ddl2">
<option value="1">TEXT 1</option>
<option value="2">TEXT 2</option>
<option value="3">TEXT 3</option>
</select>
Using jquery I have created code to update the value of one when the other changes and vice versa as below:
JQUERY
var a = ('#ddl1'),
b = ('#ddl2');
$(a + ',' + b).change(selectddl);
$(selectddl);
function selectddl() {
var val = $(this).val();
var text = $(this).text();
if (this.id === 'ddl1') {
$(b + ' option[value="' + val + '"]').prop('selected', true);
$(b).selectmenu('refresh');
} else if (this.id === 'ddl2') {
$(a + ' option[value="' + val + '"]').prop('selected', true);
$(a).selectmenu('refresh');
}
};
My requirements now are to update the select boxes based on their contained TEXT and not their value.
QUESTION
How to update a dropdown select box based on another select box contained TEXT?
After some research I have tried but failed to do this as below:
JQUERY
var a = ('#ddl1'),
b = ('#ddl2');
$(a + ',' + b).change(selectddl);
$(selectddl);
function selectddl() {
var val = $(this).val();
var text = $(this).text();
if (this.id === 'ddl1') {
$(b + ' option[value="' + val + '"]').prop('selected', true);
$(b).selectmenu('refresh');
} else if (this.id === 'ddl2') {
$(a + ' option:contains("' + text + '")').prop('selected', true);
$(a).selectmenu('refresh');
}
};
CLICK FOR DEMO
Can anyone explain how this can be achieved?
The correct answer to this question would NOT use contains due to the conflicts that could arise with text such as:
TEXT
TEXT1
You can use the .filter() function to achieve what you are requesting. You will basically need to select all of the options, then call .filter(), passing in a function that only accepts the option who's text is equal to what you expect.
For example, your else if statement might look like this:
else if (this.id === 'ddl2') {
$(a + ' option').filter(function() {
return this.text === text;
}).prop('selected', true);
$(a).selectmenu('refresh');
}
Also, it looks like you need to change your text variable as well. You should change it to something that will select the text of the currently selection option, like so:
var text = $(this).find(':selected').text();
Here's a working Fiddle.

Counting no. of dropdownlists inside a div

<div id="myDiv">
<select id="ddl1" name="31">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" selected="selected">Three</option>
</select>
<select id="ddl2" name=32>
<option value="1">A</option>
<option value="2" selected="selected">B</option>
<option value="3">C</option>
</select>
</div>
Thats my div. The number of dropdowns inside this div vary. What I want is this in a string:-
31,3||32,2
The above is name attribute value of dropdowns, 2nd number after comma is the "value" of the selected option and values of both dropdownlists are separated by pipe symbol. The dropdowns can be 3 and 4 in number too. How can I acheive this in jquery?
A little something like this:
var selects = [];
$("#myDiv select").each(function() {
selects.push(this.name + "," + $(this).val());
});
var output = selects.join("||");
Where the .each() method is used to iterate through all the select elements and push their name and current value into the selects array, then the array .join() method is used to turn the array into a string using "||" as the separator.
try this snippet:
var output = [];
$('#myDiv select').each(function() {
output.push([this.name, $(this).val()].join(','));
});
console.log(output.join('||'));
Try the following:
var values = [];
$('#myDiv select').each(function() {
values.push($(this).attr('name') + ',' + $(this).val());
});
var result = values.join('||');
var val = "";
$("select").each(function(){
val += $(this).attr("name") + "," + $("option:selected",this).val()+ "||";
})
if(val != "")
val = val.substring(0, val.length - 2);
console.log(val);

Categories

Resources