Jquery remove select options based on text input - javascript

I'm trying to do the following:
I have an input <input type="text" value="red,yellow,blue" id="colors" />
and a dropdown list
<select name="colors_dropdown" id="colors_dropdown">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
I want to remove the select options that are in the text input. For example if text input value=red,blue the dropdown should have just option yellow.
I was able to make arrays of the comma separated values in the text input and values in dropdown options.
var selected_colors = $('#colors').val().split(","); //array of colors from text input
var all_colors = $.map($("#colors_dropdown")[0].options, function(option)
{
return option.value; //array of all colors from dropdown
});
Based on that, I'm looking for a way to populate the dropdown list with all colors except those in the selected_colors arrays.

var selected_colors = $('#colors').val().split(","); //array of colors from text input
jQuery.each(selected_colors, function() {
$("#colors_dropdown option:[value='" + this + "']").remove();
//Or use text attribute:
//$("#colors_dropdown option:[text='" + this + "']").remove();
});
Working Demo: http://jsfiddle.net/83Vg9/2/

This will remove the exact matching colors. Using contains could be remove all matching options for e.g. if the text box contains only e it will remove yellow, blue, red, green everything...
// make an array
var selected_colors = $('#colors').val().split(",");
// iterate each color
$.each(selected_colors, function(index, color) {
// iterate over each option & remove if necessary
$('#colors_dropdown option').each(function(){
if (this.value == color) {
$("#colors_dropdown option:[value='" + color + "']").remove();
}
})
});
EDIT
Just realized that you don't need to use two each() as shown above. Try this -
// make an array
var selected_colors = $('#colors').val().split(",");
// iterate over each color and remove it from the dropdown
$.each(selected_colors, function(index, color) {
$("#colors_dropdown option:[value='" + color + "']").remove();
});

Related

select drop down option based on associated text

I have a drop down with a value and associated text as such:
echo '<option value="'.$row['company_id'].'">'.$row['company_name'].'</option>';
Eventually, the output of the selected option is put into a table, row by row. By each row, there is an edit button to edit that particular row and select a new drop down option. I'm trying to use JavaScript to select the text and when they hit the edit button, the option that is currently set will be the default choice.
So for instance, if the row says the company_name is: ABC Company, when they hit the edit button, the drop down will populate with that option. Since the value and text are different, I need to choose the drop down option based on text. I have tried these 2 options so far with no luck.
To get the row text:
var d = document.getElementById("itable").rows[id].cells[3].innerText;
I have tried the following to pass back the text of the row, and to select the drop down by text.
document.querySelector('#editinsurancepolicymodal select[name=editicompanydropdown]').value = d;
This option just populates the drop down, but no choice is selected.
document.querySelector('#editinsurancepolicymodal').find('option[text="InsuranceB"]').val;
This option selects the first option in the drop down, but doesn't change based on what the 'text' is.
Thank you for your help in advance.
One way will be to iterate over the option elements, selecting the one that has the same text as the text from the row, and un-selecting all the others. This is illustrated in the snippet below (I have inserted a 3 second timeout, so that you can see that the initially selected option (Two) is changed to the option with the text "Three" from the JavaScript code.
window.setTimeout(function () {
var sampleWord = "Three";
var options = document.querySelectorAll("option");
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === sampleWord) {
option.selected = true;
} else {
option.selected = false;
}
}
}, 3000);
<select id="selector">
<option id="option-1" value="1">One</option>
<option id="option-2" value="2" selected>Two</option>
<option id="option-3" value="3">Three</option>
<option id="option-4" value="4">Four</option>
</select>
Alternately, you could store the id for the company as a data-attr attribute on the row. For example (in PHP):
echo "<td data-attr-company-id=".$row['company_id'].">".$row['company_name']."</td>"
Then, you can read the attribute from the table row, and query for the option that has the same value as your attribute value.
var options = document.querySelectorAll("option");
This will select all options from the page. If you want to get the options for a specific drop down, use the following:
var options = document.querySelector('#specificform select[name=specific_drop_down_in_the_specific_form]');
To select the option based on the text and not the value, use this loop:
for (var i=0; i<options.length; i++){
var option = options[i];
if (option.innerText === d){
option.selected = true;
}
}

Jquery detect bootstrap multiple option dropdown being unselected

I have a dynamic bootstrap multiple drop down selector.
I would like to run some code when a user un-selects a option.
<select id="selectOptions" multiple>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
<option>Test4</option>
<option>Test5</option>
<option>Test6</option>
</select>
I am thinking to do this by jquery however I have an option which already runs on selecting an option, how would I do this when a user clicks to un-select the option.
Thanks
What you can do is to add a change listener to the select element and keep an array of all the items that were selected last time this listener was triggered. This way you can compare the array of items that are currently selected to the array of previously selected items to determine which ones were unselected.
Here is an example:
var prevSelected = [];
$("#selectOptions").change(function(){
var selected = $(this).val() || [];
var unselected = prevSelected.filter(function(v){
return selected.indexOf(v) === -1;
});
if(unselected.length){
console.log("value(s) " + unselected + " were/was unselected");
}
prevSelected = selected;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectOptions" multiple>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
<option>Test4</option>
<option>Test5</option>
<option>Test6</option>
</select>
Per this post you can check for selected values like so
var select = document.getElementById("selectOptions");
$('#selectOptions').change(function(){
for (index in select){
if ( $("#selectOptions").val() === "" )
{
//some code
}
}
});

Manipulate Json array on select change

I am new to JQuery and I am wondering if his is possible.
I have a PHP controller that sends a json encoded array to a view,
this is the json array:
{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}
Now on the view I have a the following:
<select id="selector">
<option value="">Select one</option>
<option value="1">blue</option>
<option value="8">green</option>
<option value="14">red</option>
</select>
<div id="description">
</div>
What I want to do is first populate the select list from the json array, then if I select green from the dropdown list the description for green should appear on the div, if I change my selection the appropriate description should appear on the div.
And the option I select should no longer appear on the select list like if I choose green, only red and blue should appear on the available option, if the I select another color let say blue then red and green should be available for another select.
I am currently doing it running a new query onchange of the select but I want to do it without another query and page refresh, I imagine it is possible since I already send the JSON array to the browser.
Hope I am clear on my problem and thank you for your help!
var data = [{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}];
var selector = $('#selector');
data.forEach(function(obj){
// create option
var option = $('<option>');
// set its value
option.val(obj.id);
// set its text
option.text(obj.text);
// append it to select element
selector.append(option);
}
selector.change(function(){
var value = this.value;
// show all options
selector.find('option').show();
// hide the selected
$(value).hide();
// find the selected object
var selected = data.filter(function(obj){
return obj.id == value;
});
// if returns exactly one show its description
if (selected.length == 1)
$('#description').text(selected[0].description);
});
Firstly you Jsonmust be like this :
[{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}]
this is some code i have tried i think it will be help you :
$(document).ready(function(e){
$("#selector").on('change',function(){
var dataL= $("#selector option:selected").val();
$.post("Page_json.php",{myVal:dataL},function(data,message,xhr){
if(message==='success'){
$.each(data, function(k,v){
if(v.id == dataL){
$("#description").text(v.description);
return false;
}
});
}
},'json');
});
});

display:block not working on option tag

UPDATE : I test my code on firefox and everything was alright but on chrome :|
I have two different selecting drop lists . one for Province and another for cities.
I want to let users first select their Province then i show them cities selection list which is only containing cities of selected Province . my idea was to achieve it this way :
HTML
<select id="Province">
<option value = "1">Province1</option>
<option value = "2">Province2</option>
</select>
<select id = "CityList">
<option value = "1">city1</option>
<option value = "1">city2</option>
<option value = "2">city3</option>
</select>
cities with value one are inside Province with value one
jquery
$("#Province").change(function(){
$("#CityList option").css({'display':'none'});
var id = "#CityList option[value = " + $("#Province option:selected").val() + "]" ;
$(id).css({'display':'block'});
})
But the problem is none of the options will get visible again :|
And i checked if i'm selecting correct option by changing font color of it
I don't know why display : block is not working on them
If you just want to hide the options and then selectivly show them, hide and show are better options.
$("#Province").change(function(){
$("#CityList option").hide();
var id = "#CityList option[value = " + $("#Province option:selected").val() + "]" ;
$(id).show();
})

Append Select Option to Text Field

I have a Select Box and a Text Field input box. Currently when the User selects a value from the Select Box, then the selected value is inputted into the Text Field input box.
<select name="nSupervisor" id="iSupervisor" onchange="PopulateUserName()">
<option value="fff">fff</option>
<option value="test1">test1</option>
<option value="dd">dd</option>
</select>
<input id="iSupervisorUserName" name="OBKey_WF_Manger_Supervisor_1" type="text" />
function PopulateUserName() {
var dropdown = document.getElementById("iSupervisor");
var field = document.getElementById("iSupervisorUserName");
field.value = dropdown.value;
}
Jsfiddle
http://jsfiddle.net/Hx6J5/1/
Currently it only takes one input.
I would like it to append inputs so the field will accept more than one select value, so if the User selects "fff", "fff" will get inputted into the field.
If the User then selects "dd", the field.value should become "fff/dd" with the "/" being the separator.
function PopulateUserName() {
var dropdown = document.getElementById("iSupervisor");
var field = document.getElementById("iSupervisorUserName");
$('field').val($('field').val() + dropdown.value);
}
I have tried this but it doesn't append.
You need to give field without quotes. If field is given in quotes jQuery will try to find elements with tag name field.
Live Demo
$(field).val($(field).val() + dropdown.value);
Using pure JS:
function PopulateUserName() {
var dropdown = document.getElementById("iSupervisor");
var field = document.getElementById("iSupervisorUserName");
if ( field.value == "" ){
field.value = dropdown.value;
}else{
field.value += "/" + dropdown.value;
}
}
See the working code at:
JSFiddle
I suggest to use multi select jquery plugin:
http://harvesthq.github.io/chosen/

Categories