Javascript to Select item from listbox by value number - javascript

I have a listbox on a page:
<select id="user_list" name="user_list" size="21" style="width:200px;">
<option value=1>User 1</option>
<option value=2>User 2</option>
<option value=3>User 3</option>
<option value=5>User 5</option>
<option value=6>User 6</option>
</select>
And if I select a item I can get the current value by using the following code:
var el = document.getElementById("user_list");
var val = el[el.selectedIndex].value;
alert(val);
However, the problem I am having is that I want to be able to search the user_list (start from 1) for the next avaliable number (in my example above it will alert 4, as that is missing)
But I have tried using:
var el = document.getElementById("user_list");
var val = el[4].value;
alert(val);
but it doesn't work, does anyone know what I am doing wrong?
My guess is that var val = el[4].value; is wrong.. ?

it works well.
http://jsfiddle.net/ubpn7/

Related

How to get JS array value from nth value of form dropdown?

I have the following dropdown option in a form:
<select id="candidates">
<option value="select">Pick one</option>
<option value="Candidate 1">Candidate 1</option>
<option value="Candidate 2">Candidate 2</option>
<option value="Candidate 3">Candidate 3</option>
</select>
And I also have the following array defined:
const selectedcandidate = ["/image1.png", "/image2.png", "/image3.png"];
I'm trying to declare a variable that will contain the image file of the corresponding candidate that was selected from the dropdown:
finalselectedcandidate = selectedcandidate[candidates[n]];
However, the code above doesn't work. What would be the best way to accomplish this?
I'm not completely sure, but maybe this what you are looking for?
<select id="candidates" onchange="myFunction()">
<option value="select">Pick one</option>
<option value="0">Candidate 1</option>
<option value="1">Candidate 2</option>
<option value="2">Candidate 3</option>
</select>
With this function should do the trick
function myFunction(){
const selectedcandidate = ["/image1.png", "/image2.png", "/image3.png"];
let e = document.getElementById("candidates");
let value = e.value;
if(selectedcandidate[value] !== undefined){
alert(selectedcandidate[value]);
}
};
One possible way to solve this is to use the onChange event. Also you will need some way to relate the candidates to the pictures. One way to do that is to use a JS object with the select values as keys.
const candidates = {
"Candidate 1": "image1.png",
"Candidate 2": "image2.png",
"Candidate 3": "image3.png"
}
function handleOnChange(selectElement){
const selectedCandidate = selectElement.value;
const selectedImage = candidates[selectedCandidate];
console.log(`Selected image: ${selectedImage ?? "No image selected"}`);
}
<select id="candidates" onchange="handleOnChange(this)">
<option value="select">Pick one</option>
<option value="Candidate 1">Candidate 1</option>
<option value="Candidate 2">Candidate 2</option>
<option value="Candidate 3">Candidate 3</option>
</select>
You can build it into your app as follows:
const selectedcandidate = ["/image1.png", "/image2.png", "/image3.png"];
$('#candidates').on('change', function() {
const val = this.value,
suffix = val !== 'select' ? +val.split(' ')[1] : null,
index = suffix ? suffix - 1 : suffix,
img = suffix ? selectedcandidate[index] : index;
console.log( val, suffix, index, img );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="candidates">
<option value="select">Pick one</option>
<option value="Candidate 1">Candidate 1</option>
<option value="Candidate 2">Candidate 2</option>
<option value="Candidate 3">Candidate 3</option>
</select>

Change option values of select 2 if select 1 has a value with jquery

I require a bit of jQuery to do the following:
A user can currently select Program and/or a region.
If a user selects Program AND a Region I require the option values of the region dropdown to change to "?region=1" and "?region=2"
<select class="program" id="program">
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Greatly appreciate the assist.
My attempt at JQuery:
$('#program').on('change', function () { if($(this).val() !="0") { } else { // no option is selected } })
You need to further extend the change event for #program and include a similar one for #region.
var programSelected = null;
var regionSelected = null;
$('#program').on('change', function(element) {
programSelected = $('#program option:selected').text();
updateRegionOptions();
});
$('#region').on('change', function(element) {
regionSelected = $('#region option:selected').text();
updateRegionOptions();
});
function updateRegionOptions() {
if(programSelected != null && regionSelected != null) {
$('#region option').each(function() {
var modifiedString = '?';
modifiedString += $(this).val().replace(/\d+/,'');
modifiedString = modifiedString.replace('.html','');
modifiedString += '=';
modifiedString += $(this).val().match(/\d+/);
$(this).val(modifiedString);
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="program" id="program">
<option value="" selected disabled>Select Program</option>
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="" selected disabled>Select Region</option>
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Explanation of the logic above:
on('change' event for both #region and #program
Set the relevant variable programSelected or regionSelected depending on the change event
Run function updateRegionOptions();
If the variables programSelected and regionSelected both have a value
For each of the options in #region
Mutate the existing value to be of the form "?region=1" and "?region=2"
Update the value section of each of the option elements to have this value
The relevant JSFiddle for review.
If this solved your issue, please accept this answer :)

how to set text of option:selected in jquery

<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
<select id="youSelect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
Now on click of a button I want to set mySelect option:selected value in youSelect So for this I had done this
$('#youSelect option:selected').text($('#myselect option:selected').text())
but its not working.Please guide how to solve this.
Simply do:
$('#youSelect').val($('#myselect').val());
You are matching the values, not the text.
Edit: Based on your edited question, you're probably looking at the same situation as this question
var _mySelectText = $("#myselect option:selected").text();
$("#youSelect option").filter(function () {
return this.text === _mySelectText;
}).attr("selected", "selected");
$("#youSelect").val("thevalue");
just make sure the value in the options tags matches the value in the val method.
var myValue = $("#myselect option:selected").text();
var secondoption = $("#youSelect")[0];
for (var i = 0, sL = secondoption.length; i < sL; i++) {
if (secondoption.options[i].text == myValue) {
secondoption.selectedIndex = i;
break;
}
}
http://plnkr.co/edit/GVt8rZswjzZTC13vw98N?p=preview
Use this.
$(selector_to_your_button).on('click',function(){
$('#youSelect).val($("#myselect").val());
});

accessing global variables after setting them javascript

I am trying to keep track of changes to a select box in django. My code below is working up to alert(change.new_time);, so I am making the object correctly-
var changed_select_box_array = [];
function handleChanges(id){
var x = document.getElementById(id).selectedIndex;
var time = document.getElementsByTagName("option")[x].value;
var change = {id:id, new_time:time};
alert(change.id);
alert(change.new_time);
changed_select_box_array[changed_select_box_array.length] = change;
alert(changed_select_box_array[0].id);
}
but I cannot access the new item in the array. I tried 4-5 different ways and followed some rules for global variables in funcs I found on this site, and I cannot access anything from the new array. Am I doing something wrong adding to the array? I tried push too. Thank you
You can use Object as associative array.
var changed_select_box_array = {};
function handleChanges() {
var x = this.selectedIndex;
var id = this.id;
var time = this.getElementsByTagName("option")[x].value;
var change = { id: id, new_time: time };
changed_select_box_array[id] = change;
console.log(changed_select_box_array);
}
<!--Emitation of some select inputs with change events-->
<select id="s1" onchange="handleChanges.call(this)">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
<select id="s2" onchange="handleChanges.call(this)">
<option value="val4">Value 1</option>
<option value="val5">Value 2</option>
<option value="val6">Value 3</option>
</select>

How to add a "random" button that applies to two drop down menus

I have created a page with two drop-down menus containing various values.
Now I would like to add a "randomize" button. When clicked, this button would select any of the values at random in both fields. (the values are also copied on a box above each menu).
Project idea for drop down menus
So far I've coded the menus and the words display in the boxes above them when the user selects them. But now I'm trying to add a randomise button that would put any of the values in the drop down as selected and of course displayed in the above text box. Ideally, more values in the drop-down menus would be added every once in a while without making the script dysfunctional... and ideally it would all be contained in a HTML file (calling for JQuery or javascript is ok).
I've looked at this but it doesn't apply.
I also looked at this but it's not really a feature that the user activates.
Very grateful if anyone can help! Thanks
hope this helps
HTML :
<select id="s1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="s2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Javascript:
var minNumber = 0;
var maxNumber = 3;
function randomNumberFromRange(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
I create this fiddle for you...
https://jsfiddle.net/s59g8vdp/
The first example you have provided is very close to what you want to do. You just need to:
Get a random value between 0 and options.length - 1.
Get option[random] and set its selected property to true.
Copy that option's .innerHTML or .value to the .innerHTML or .value of the label on top of the dropdowns.
This is all you probably need:
function randomizeSelect(selectId, fieldId) {
var options = document.getElementById(selectId).children;
var random = Math.floor(options.length * (Math.random() % 1));
var option = options[random];
option.selected = true;
document.getElementById(fieldId).value = option.innerHTML; // You can use .value instead in both places
}
var values = {};
window.onload = function(e) {
document.onchange = function(e) { // Event Delegation: http://davidwalsh.name/event-delegate
var t = e.target;
if(t.tagName == "SELECT")
document.getElementById(t.id.replace("Select","Label")).value = t.children[t.selectedIndex].innerHTML;
}
document.oninput = function(e) {
var t = e.target;
if(t.tagName == "INPUT") {
if(values.hasOwnProperty(t.id))
var options = values[t.id];
else
var options = document.getElementById(t.id.replace("Label","Select")).children;
var currentValue = t.value;
for(i in options) {
if(options[i].innerHTML == currentValue) { // Can also use .value
options[i].selected = true;
break;
}
}
}
}
document.getElementById("randomize").onclick = function(e) {
randomizeSelect("leftSelect", "leftLabel");
randomizeSelect("rightSelect", "rightLabel");
}
}
<input type="text" id="leftLabel" value="Left 1">
<select id="leftSelect">
<option value="l1" selected>Left 1</option>
<option value="l2">Left 2</option>
<option value="l3">Left 3</option>
</select>
<input type="text" id="rightLabel" value="Right 1">
<select id="rightSelect">
<option value="r1" selected>Right 1</option>
<option value="r2">Right 2</option>
<option value="r3">Right 3</option>
</select>
<button id="randomize">RANDOMIZE</button>
This will create random number and click on random div menu:
$(function(){
$(".menu").click(function(){
alert("you clicked "+$(this).text());
});
});
function doSomthing(){
var rand=Math.floor((Math.random() * 5));
alert(rand+1);
var ele = $(".menu").get(rand);
$(ele).click();
}
fiddle example: link
Or you can use this example to put value in the menu, or wherever you want: link 2
just a concept how to make that
$('input').on('click',function(){
var randomnum = Math.floor(Math.random()*$('ul li').length);
alert($('ul li').eq(randomnum).text());
});
DEMO FIDDLE
Randomize Button added
see... ;) i hope this solve your problem!
https://jsfiddle.net/s59g8vdp/1/
Html :
<select id="s1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="s2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<a id="randomize" href="#">randomize</a>
Javascript :
var minNumber = 0;
var maxNumber = 3;
$("#randomize").click(function(){
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
});
function randomNumberFromRange(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);

Categories