Need to select text of selected dropdown using JavaScript - javascript

I have a dropdown with values. I have an array array with a list of values that will match the drop down values. If the value of text option of the dropdown exists in the array, it shouldn't show in the dropdown as an option. I am stuck on the approach I should use. This is what I have so far.
HTML
Car Plates:
<select title='car/id' id='car_x0020_Plate_x002f'>
<option selected="selected" value="0">none</option>
<option value="16">233-jj2</option>
<option value="10">934-zxy</option>
<option value="90">330-nbh</option>
<option value="11">930-orj</option>
</select>
JavaScript
var hideOption = ['233-jj2', '330-nbh']
var e = document.querySelector([id^='car']);
var strUser = e.value;
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
for (var x=0; x<hideOption.length; x++){
if (hideOption[x] === strUser){
//remove from dropdown
}
}

I made your idea in a very simple way, if you have any question please tell me
var hideOption = ['233-jj2', '330-nbh'],
select = document.getElementById("select");
for (let i = 0; i < hideOption.length; i = i + 1) {
for (let t = 1; t < select.options.length; t = t + 1) {
if (hideOption[i] == select.options[t].textContent) {
select.options[t].remove();
}
}
}
Car Plates:
<select title='car/id' id='select'>
<option selected="selected" value="0">none</option>
<option value="16">233-jj2</option>
<option value="10">934-zxy</option>
<option value="90">330-nbh</option>
<option value="11">930-orj</option>
</select>

// remove from dropdown
use this code to remove from dropdown
e.removeChild(e.options[e.selectedIndex])
you can use this also
e.selectedOptions[0].remove()

var hideOption = ['233-jj2', '330-nbh']
var e = document.querySelector("[id^='car']");
var selTextArr = Array.from(e.options).map(option => option.text)
for (var x=0; x<selTextArr.length; x++){
if (hideOption.includes(selTextArr[x])){
e.remove(x)
}
}
Car Plates:
<select title='car/id' id='car_x0020_Plate_x002f'>
<option selected="selected" value="0">none</option>
<option value="16">233-jj2</option>
<option value="10">934-zxy</option>
<option value="90">330-nbh</option>
<option value="11">930-orj</option>
</select>

var options = document.querySelector("[id^='car']").children;
var hideOption = ['233-jj2', '330-nbh']
for (var i = 0; i < options.length; i++){
if(hideOption.indexOf(options[i].text) > -1){
options[i].remove();
}
}

Related

Append options to select box depend on extracted part from array

I have 4 selectboxs moduleName, submoduleName, ProgrameName and last selectbox has all data for username, module, submodule and programe name merged and splited with ";" between each other, I need: when user select module name from moduleName Selectbox it filters values in all data selectbox and splites submoduleNames under this moduleName and append it as options to submoduleName Selectbox, also the same when user select from submoduleName selectbox it filters programeNames under this module and subModuleNames and append it as options in programeName selectbox. I tried to splite each line in allData selectbox but i failed to continue. here what i tried but it is not working.
Thank you for your help.
$(document).ready(function(){
function check(){
var lines = $('#splitedOptions').val().split(/\n/);
var texts = [];
for (var i=1; i < lines.length; i++) {
texts.push(lines[i]);
}
for (var i=0; i < texts.length; i++) {
var extractedPart = texts[i].split(';'),
ModuleNameVal = $("#moduleName option:selected").val();
if(extractedPart[1] == ModuleNameVal){
var newOption = "<option value='"+extractedPart[2]+"'>"+extractedPart[2]+"</option>";
$('#SubModuleName').append(newOption);
}
}
}
function c1() {
var optionsCount = $('#allData').find('option').size();
var textArea ="";
for (var i = 1; i <= optionsCount; i++) {
if(i!=1){
textArea += '\n';
}
var xItem = $('#allData').find('option:nth-child(' + (i) + ')').text();
textArea += xItem ;
}
$('#splitedOptions').val('');
$('#splitedOptions').val(textArea);
check();
}
$('#moduleName').change(function(){
c1()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions" ></textarea>
One way to achieve above is to filter the options from allData select-box and get only those option which has the value which user has selected using value*="yourvalue".
Then , onces you get the options you need to know which select-box has been change so that we can get required value only when we do split and pass required index .
Lastly , we need to loop through the options which we have got from filtering select-box .Suppose user select Master so there are Master in many places so to avoid getting data from all option i have check the value of select with the first select-box as well if matches apppend only those options.
Demo Code :
$('select').change(function() {
//get value
var name = $(this).val();
//filter option and get only option which has the value which user has slected
var s = $("#allData").find('option').filter('[value*=' + name + ']').each(function(ele) {
return $(this).val();
});
var module_namess;
var index;
//check the id of select-box
if ($(this).attr("id") == "moduleName") {
module_namess = "SubModuleName";
index = 2;//set index
} else if ($(this).attr("id") == "SubModuleName") {
name = $("#moduleName").val()
module_namess = "programeName"
index = 3
}
$("#" + module_namess).empty()
$('#' + module_namess).append("<option >Select one</option>")
var valuess = ''
//loop through options
for (var i = 0; i < s.length; i++) {
valuess += $(s[i]).val()
//if first value is same
if ($(s[i]).val().split(";")[1] == name) {
var sub_value = $(s[i]).val().split(";")[index]//get the value
var newOption = "<option value='" + sub_value + "'>" + sub_value + "</option>";
$('#' + module_namess).append(newOption);//append
}
}
$('#splitedOptions').val(valuess);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions"></textarea>

Array Having null values

I need to copy all the drop down selected items to another drop down.
I don't know why it also copies a white space after every city name.
Please tell me why.
//var values;
// function to copy all the selected city name to //another drop box
function copy_city_name(city) {
var x = document.getElementById("new_list");
//copy array values to any another variable(city_list)
var city_list = city;
//document.write(city);
//ittration to copy all the name to another drop down
for (var i = 0; i <= city_list.length; i++) {
var opt = city_list[i];
var e1 = document.createElement("option");
e1.textContent = opt;
e1.value = opt;
//alert(e1);
//console.log(e1);
x.add(e1);
}
}
// function to select all the selected city name in a array.
function get_city_name() {
// body...
var fld = document.getElementById('city_name');
// ittration to get names of all the selected city name.
for (var i = 0; i < fld.options.length; i++) {
var values = [];
if (fld.options[i].selected) {
values.push(fld.options[i].value);
copy_city_name(values); // passed all values to function
}
}
}
<form>
<select multiple="multiple" name="city" id="city_name">
<option value="a">A</option>
<option value="b"> B </option>
<option value="c"> C</option>
<option value="d"> D</option>
</select>
<button type="button" onclick="get_city_name()">select multiple</button>
<select multiple="multiple" name="get" id="new_list">
</select>
</form>
i <= city_list.length should be i < city_list.length
you can shorten this using querySelector:
// function to copy all the selected city name to another select
function copy_city_name() {
var newList = document.getElementById("new_list"),
opts = document.querySelectorAll('#city_name option:checked');
// iteration to get names of all the selected city names.
for (var i = 0; i < opts.length; i++) {
var opt = document.createElement("option");
opt.textContent = opts[i].textContent;
opt.value = opts[i].value;
newList.add(opt);
}
}
<form>
<select multiple="multiple" name="city" id="city_name">
<option value="a">A</option>
<option value="b"> B </option>
<option value="c"> C</option>
<option value="d"> D</option>
</select>
<button type="button" onclick="copy_city_name()">select multiple</button>
<select multiple="multiple" name="get" id="new_list">
</select>
</form>
If you want to move them, it is even shorter
for (var i = 0; i < opts.length; i++) {
newList.add(opts[i]);
}
In your copy_city_name function loop it must be i < city_list.length; not i <= city_list.length;
And in your get_city_name move values array outside of the loop to collect all selected options
function copy_city_name(cities) {
var list = document.getElementById("new_list");
for (var i = 0; i < cities.length; i++) {
var city = cities[i];
var option = document.createElement("option");
option.textContent = city;
option.value = city;
list.add(option);
}
}
function get_city_name() {
var fld = document.getElementById('city_name');
var values = [];
for (var i = 0; i < fld.options.length; i++) {
if (fld.options[i].selected) {
values.push(fld.options[i].value);
}
}
copy_city_name(values);
}
<form>
<select multiple="multiple" name="city" id="city_name">
<option value="a">A</option>
<option value="b"> B </option>
<option value="c"> C</option>
<option value="d"> D</option>
</select>
<button type="button" onclick="get_city_name()">select multiple</button>
<select multiple="multiple" name="get" id="new_list">
</select>
</form>

How do I remove old options in Jquery when parent select box is changed?

I have 3 chained select boxes using jquery and json.
Depending on first 2 values I filter third one my code actually works but the problem is when I change values of first 2 select boxes third select recieves new datas while keeping old ones.
I've tried to empty my array but it didn't work.
$(document).ready(function() {
var json = JSON.parse(jsonString);
var makesArray = [];
var selectedyear;
var selectedcourse;
var $yearDropDown = $("#DropDown_Year");
var $course_type = $("#course_type");
$yearDropDown.change(function() {
selectedyear = this.value;
//filter based on selected year.
});
$course_type.change(function(){
selectedcourse = this.value;
makesArray = jQuery.grep(json, function(course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
for(var i = 0, l = makesArray.length; i < l; i++){
var option = makesArray[i];
selectBox.options.add( new Option(option.course_code, option.course_code, option.course_code) );
}
makesArray= []; //makesArray.empty();
});
});
<div id="DrpDwn">
Year:
<select id="DropDown_Year">
<option>Yıl</option>
<option value="15">2015-2016</option>
<option value="16">2016-2017</option>
</select>
<select class="form-control" id="course_type" name="course_type" required>
<option value="" selected> Choose</option>
<option value="Yos">YÖS</option>
<option value="SatMatGeo">SAT (MAT)</option>
<option value="SatCriRea">SAT (ENG)</option>
<option value="TomerABC">TÖMER (ABC)</option>
<option value="TomerAB">TÖMER (AB)</option>
<option value="TomerBC">TÖMER (BC)</option>
<option value="TomerA1A2">TÖMER (A)</option>
<option value="TomerB1B2">TÖMER (B)</option>
<option value="TomerC1C2">TÖMER (C)</option>
</select>
Make:
<select id="DropDown_Make">
<option>None</option>
</select>
</div>
and this is JSFIDDLE
https://jsfiddle.net/rw7cb8c5/25/
Make DropDown_Make empty using selectBox.innerHTML = "" in $course_type.change() like following.
$course_type.change(function () {
selectedcourse = this.value;
makesArray = jQuery.grep(json, function (course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
selectBox.innerHTML = ""; //added this line
for (var i = 0, l = makesArray.length; i < l; i++) {
var option = makesArray[i];
selectBox.options.add(new Option(option.course_code, option.course_code, option.course_code));
}
makesArray.empty();
});
UPDATED FIDDLE

Select Index not working as expected

DOM:
<select name="statusId">
<option value="">Choose a status</option>
<option value="12856801">Not a Fit</option>
<option value="12882961">Contacted </option>
<option value="13071711">No Contact Info</option>
I found this code and tried it:
var textToFind = 'Contacted';
var dd = document.getElementsByName('statusId')[0];
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectIndex = i;
break;
}
}
It's not setting the value, it's just returning 2
What am I doing wrong?
selectedIndex not selectIndex
I can't read.

Creating multiple Select options from an Object

Im stack on creating multiple select options
I have an Object with multi objects inside and want create select options in condition of the previous select option , i provide js fiddle for better understanding .
my objectif is
first select category ----(then)---> select sex -----(then)---> select kind---(then)-->then select size
by this order from that Object.
i could do the select sex and it works but not kind and size.
this is my html
<form name="myform">
<div>
<select name="category_group" id="category_group" >
<option value="0">choose category</option>
<option value='401' > clothes </option>
<option value='403' > shoes </option>
</select>
</div>
<br>
<div>
<select id="clothing_sex" name="clothing_sex" onChange="showclothesKind(this.value,this.form.clothing_kind)">
<option value="0">choose Type»</option>
</select>
<select id="clothing_kind" name="clothing_kind">
<option value="0">choose clothes</option>
</select>
<select id="clothing_size" name="clothing_size">
<option value="0">choose size</option>
</select>
</div>
</form>
and js in the fiddle.
much appreciate your help.
This was kind of fun to play around with. Thanks for posting. I used the following:
var optionTemplate = "<option class='newOption'>sampleText</option>";
$(document).ready(function() {
var removeFromNextSelects = function(firstSelector) {
var selNum = sels.indexOf(firstSelector);
for (var i = selNum; i < sels.length; i++)
{
$(sels[i]).find('.option').remove();
}
};
var populateNextSelect = function(neededObject, targetSelector) {
removeFromNextSelects(targetSelector);
for (var key in neededObject)
{
var name;
neededObject[key].name ? name = neededObject[key].name : name = neededObject[key];
$(targetSelector).append(optionTemplate);
$('.newOption').val(key).html(name).removeClass('newOption').addClass('option');
}
};
var obj1 = {}, obj2 = {}, obj3 = {};
var sels = ["#clothing_sex", "#clothing_kind", "#clothing_size"];
$('#category_group').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[0]);
return;
}
obj1 = {};
var selection = $(this).val();
obj1 = clothes[selection];
populateNextSelect(obj1, sels[0]);
});
$('#clothing_sex').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[1]);
return;
}
obj2 = {};
var selection = $(this).val();
obj2 = obj1[selection].types;
populateNextSelect(obj2, sels[1]);
});
$('#clothing_kind').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[2]);
return;
}
obj3 = {};
var selection = $(this).val();
var arr = obj2[selection].sizes;
for (var i = 0; i < arr.length; i++)
{
obj3[Object.keys(arr[i])[0]] = arr[i][Object.keys(arr[i])[0]];
}
populateNextSelect(obj3, sels[2]);
});
});
Here's the fiddle

Categories

Resources