Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append To Select List If Option Isn't Already There

Tags:

jquery

I want to append to a select list only if the selected option is not already there. Currently, I have this:

$('#columnsAvailable').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");

Can someone help me insert a statement that checks if "$(this).val()" is already there or not, I don't want to insert duplicate values? Thanks!

like image 514
Camille Sévigny Avatar asked Mar 08 '13 15:03

Camille Sévigny


People also ask

Is it possible to add more options to select list field?

Basically it's bad idea of giving more options/space to all to add new values to select list field. you'll end up with many unwanted values. you can consider labels You can go with ScriptRunner's Custom listener. on your case listener for Issue created event

How to add options to a select element using jQuery?

- GeeksforGeeks How to add options to a select element using jQuery? An option can be added to a select element using 3 approaches in jQuery: The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append () method.

How to append the selected box in jQuery?

The select box is selected with the jQuery selector and this option is added with the append () method. The append () method inserts the specified content as the last child of the jQuery collection.

How do I add an option to a select box?

The Option () constructor is used to create a new option element. A new option is created with the text and the value of the option as the parameters. This element is then added to the select box with the append () method. A new jQuery DOM element is created with the option tag.


1 Answers

Something like

var optionExists = ($('#columnsAvailable option[value=' + $(this).val() + ']').length > 0);

if(!optionExists)
{
    $('#columnsAvailable').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
}

should do the trick.

like image 160
Rob Stevenson-Leggett Avatar answered Sep 28 '22 11:09

Rob Stevenson-Leggett