Select Index not working as expected - javascript

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.

Related

Need to select text of selected dropdown using 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();
}
}

Sorting selectbox with Javascript

I'm Setup a <select> dropdown list and I trying to make options sorting in numerical order (Ascending) :
HTML
<select id="singleSelector">
<option value="/single?id=544">1</option>
<option value="/single?id=598">4</option>
<option value="/single?id=605">6</option>
<option value="/single?id=604">3</option>
<option value="/single?id=603">7</option>
<option value="/single?id=602">5</option>
<option value="/single?id=601">2</option>
</select>
Edit :
When using the following JS by #Sanjay, the order is not correct :
JavaScript :
$(function() {
// choose target dropdown
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
// to change to descending order switch "<" for ">"
return $(x).text() > $(y).text() ? 1 : -1;
}));
});
Output :
It's possible to make order 1,2,3,4,5 instead of 1,10,11...,2,20,21 ?
Here is working example.
$(function() {
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
var num1 = parseInt($(x).text());
var num2 = parseInt($(y).text());
return num1> num2 ? 1 : -1;
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="wrapper">
<select>
<option selected>Choose a number</option>
<option value="3">3</option>
<option value="1">1</option>
<option value="0">0</option>
<option value="2">2</option>
<option value="8">8</option>
</select>
</div>
try THIS
var target = document.getElementById('singleSelector');
function sortIt(target ) {
var tmp = new Array();
for (var i=0;i<target.options.length;i++) {
tmp[i] = new Array();
tmp[i][0] = target.options[i].text;
tmpA[i][1] = target.options[i].value;
}
tmp.sort();
while (target.options.length > 0) {
target.options[0] = null;
}
for (var i=0;i<tmp.length;i++) {
var op = new Option(tmp[i][0], tmp[i][1]);
target.options[i] = op;
}
return;

Select values not correctly increasing/decreasing total number in js

I thought I had solved this javascript 'for' loop to sum up the numeric choices of several select fields to a number, each time one of them is changed.
But, modifying a choice in any of the selected fields is adding the number again, instead of replacing the initial choice number - which is what I want.
Example: a user chooses from 3 fields, these values: +15, -5, +1.
The total should be "11"
If the user modifies their first select to +10 instead of #+15, the total value should be "6". Instead, it's ADDING the modified number to everything. So the number becomes "21" - not what I want.
Note: I want to increase the number incrementally with each select choice - NOT a total of all of them when the user is done with the fields
Here's what I've got:
<form action="/cgi-bin/dropdown.cgi" method="post">
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
</form>
<div id="tally" style="">0</div>
<script>
var sum = 0;
document.addEventListener("DOMContentLoaded", function(event) {
var gg1 = new JustGage({
id: "gg1",
value: 0,
textRenderer: customValue
});
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
fieldvalue = userSelection[i].value;
fieldname = userSelection[i].id;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
});
</script>
This happens because inside the callback function of the change listener you're not considering the values of the other dropdowns. Grab them using a second for-loop and recalculate the sum.
Here's your modified callback function:
for (let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
sum = 0;
for (var b = 0; b < userSelection.length; b++) {
fieldvalue = userSelection[b].value;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
Whenever any of the select values is changed, you should re-compute the entire sum. Something like this:
onload = function {
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
var sum= computeSum();
//whatever you want to do with sum
})
}
function computeSum() {
var sum = 0;
for(const select in userSelection) {
sum += select.value;
}
return sum;
}
}
Like others have mentioned, you need to recalculate the total every time any of select control value changes. Here's a demo (un-optimized):
document.querySelectorAll('select').forEach(select => select.addEventListener('change', (event) => {
if (allValid()) {
document.querySelector('#tally').innerHTML = calcTotal();
}
}))
const allValid = () => {
let status = true;
document.querySelectorAll('select').forEach(select => {
if (select.selectedIndex === 0) status = false;
})
return status;
}
const calcTotal = () => {
let total = 0;
document.querySelectorAll('select').forEach(select => {
total += parseInt(select.value);
})
return total;
}
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
<div id="tally" style="">0</div>

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

Categories

Resources