How to change Selected Index when I only have the name? - javascript

I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.

Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.

I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>​
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");

Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>

Related

Copy selected multiple values to the text box

I have drop down list as below.
<select id="checkOwner" multiple="multiple" onchange="copyValue()">
<option value="FIRSTNAME">First Name</option>
<option value="LASTNAME">Last Name</option>
</select>
I used Below javascript to add checkbox
$(function() {
$('#checkOwner').multiselect({
});
});
I used below javascript to copy selected value to text field.
function copyValue() {
var dropboxvalue = document.getElementById('checkOwner').value;
document.getElementById('mytextbox').value = dropboxvalue;
}
But the problem is, this copy only one value. I want to copy all the selected values. How can I do this?
Loop through the option and put selected values in a string and then output the string on the textbox
function copyValue() {
var str = "";
for (var option of document.getElementById('checkOwner').options) {
if (option.selected) {
str+= option.value+" ";
}
document.getElementById('mytextbox').value = str;
}
}
my approach is loop on the options then check the condition if isSelected
html
<select name="checkOwner" multiple="multiple" onchange="copyValue(this)">
js
const copyValue = me => {
let y = Array.from(document.querySelectorAll('select option')).map(x => x.selected ? x.value : '')
document.getElementById('mytextbox').value = y.join(' ');
}

Find string length from select form field with multiple values with javascript

I have tried several methods only to discover that the usual str.length code is not reading the entire form field contents
Html:
<select id="states1" name="states[]" multiple="multiple">
<option value="AL">AL</option>
<option value="AK">AK</option>
<option value="CA">CA</option>
</option>
No matter how many states I select, the javascript only reads the first state selected. For example, if I have selected all 3 states, the only validation checks that work are found below:
<script>
var slen = document.forms[0].elements['states1'];
function invoice_() {
if(slen.value == "AL"){
alert('true');
return false;
} }
</script>
And to check the length
<script>
var slen = document.forms[0].elements['states1'];
function invoice_() {
if(slen.value.length == 2){
alert('true');
return false;
} }
</script>
In other words, even if the actual length of the form field contents is 6, the only way I have found to check the string length in javascript only returns 2, in my example, because it only reads the first selected state but not the others
I have tried
slen.value.options.length
slen.options.length
To get the right number, but those methods don't work.
How do I get the code to read the entire form field contents to count the length when it is a select multiple option field with multiple options selected?
You can use the .selectedOptions property to get the selected options in the multiple select. Then convert it to an Array, and do a .map().reduce() to total up the values.
var totalLen = Array.from(document.forms[0].states1.selectedOptions)
.map(v => v.value.length)
.reduce((sum, n) => sum + n, 0);
console.log(totalLen);
<form>
<select id="states1" name="states[]" multiple="multiple">
<option value="AL" selected>AL</option>
<option value="AK">AK</option>
<option value="CA" selected>CA</option>
</select>
</form>
If you wanted all the options instead of just the selected ones, then use the .options property instead.
var totalLen = Array.from(document.forms[0].states1.options)
.map(v => v.value.length)
.reduce((sum, n) => sum + n, 0);
console.log(totalLen);
<form>
<select id="states1" name="states[]" multiple="multiple">
<option value="AL" selected>AL</option>
<option value="AK">AK</option>
<option value="CA" selected>CA</option>
</select>
</form>
This was the best solution for someone who might need it:
let uvs = document.forms[0].elements['states1'];
function invoice_() {
var result = [];
var options = uvs && uvs.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
var nst = (result.push(opt.value || opt.text)) - 1;
if(nst > 3){
alert('');
return false;
}
For some reason the raw count of 'result.push(opt.value || opt.text' is +1, so I just added a little math to make the count accurate. I was initially looking to count the number of characters, but finding the number of states selected was even better. Instead of a result of 10 for 5 states I get 5 for 5 states.
The other character count code above was too unstable. Might be a browser issue, hard to say.

How to use selected option is variable select list

For my code i need 2 selects, the first select is static (4 options that dont change) and the second select is dependant on what is selected in the first select.
Then depending on what is chosen in de the second list a function is executed.
i found some example code one W3schools that allow me to make the whole list thing:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_options3
So this works really well but now i dont know how to attach a function to the selected options in the second select since there is no where in the html to do something like an onchange.
Each option from the second select should have a function (in my code the selected option will display an image corresponding with the chosen option)
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>

Get all select/option lists start by something

In an HTML page i have severals list.
<select name="salut-1358937506000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
<select name="salut-1358937582000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
...
In javascript, I want to get all select/option list which started by "salut-".
For theses list, i want to compare his name and his selected value.
I know it is possible in jQuery but can't use jquery, only javascript (JSNI with GWT exactly).
Have you an idea?
Thanks!
var selects = document.getElementsByTagName('select');
var sel;
var relevantSelects = [];
for(var z=0; z<selects.length; z++){
sel = selects[z];
if(sel.name.indexOf('salut-') === 0){
relevantSelects.push(sel);
}
}
console.log(relevantSelects);
You can use the getElementsByTagName function to get each SELECT name, for example:
var e = document.getElementsByTagName("select");
for (var i = 0; i < e.length; i++){
var name = e[i].getAttribute("name");
}
Then you can use the following code to get each OPTION for the SELECT, to do any necessary comparisons:
var options = e[i].getElementsByTagName("option")

How do I programmatically set the value of a select box element using JavaScript?

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

Categories

Resources