Display all selected value of multiple drop down list - javascript

Below is what I have...
<html>
<body>
<form name="myForm">
<select name="myOption" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type=submit value="Print First" onClick="printMe()">
<input type=submit value="Print All" onClick="printAll()">
</body>
<script>
function printMe() {
alert ("Selected option is " + myForm.myOption.value);
}
function printAll() {
var str = "";
// what should I write here??
alert("Options selected are " + str);
}
</script>
</html>
Please let me know what should I write in printAll() so that I can print all the values that I selected... I know how can I print the first selected value...

how about this??
function printAll() {
var str="",i;
for (i=0;i<myForm.myOption.options.length;i++) {
if (myForm.myOption.options[i].selected) {
str = str + i + " ";
}
}
alert("Options selected are " + str);
}
Good Luck!!!

You can do something like this:
function printAll() {
var obj = myForm.myOption,
options = obj.options,
selected = [], i, str;
for (i = 0; i < options.length; i++) {
options[i].selected && selected.push(obj[i].value);
}
str = selected.join();
// what should I write here??
alert("Options selected are " + str);
}
Demo: http://jsfiddle.net/n3cXj/1/

I would use jquery as it's easier
JQuery:
$("myOption:selected").each(function () {
alert($(this).text());
});

http://jsfiddle.net/XBDmU/2/
var selected = [];
$("#Mymutiple option").each(function(){
$(this).click(function(evt){
myvar = $(this).val();
if (evt.ctrlKey){
if(jQuery.inArray(myvar, selected) >-1){
selected = jQuery.grep(selected , function(value) {
return value != myvar;
});
}
else{
selected.push(myvar);
}
}
else{
selected = [];
selected.push(myvar);
}
});
})
$("#printMe").click(function(){
alert("First selected is:" + selected[0]);
return false;
});
$("#printAll").click(function(){
alert("Options selected are :" + selected);
return false;
});
html:
<form name="myForm">
<select name="myOption" id="Mymutiple" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type="submit" value="Print First" id="printMe">
<input type="submit" value="Print All" id="printAll">

This will help you. It's in pure js. no jquery, mootools...
<!DOCTYPE html>
<html>
<body>
<script>
function get(){
var str="",i;
for (i=0;i<asa.cars.options.length;i++) {
if (asa.cars.options[i].selected) {
str += asa.cars.options[i].value + ",";
}
}
if (str.charAt(str.length - 1) == ',') {
str = str.substr(0, str.length - 1);
}
alert("Options selected are " + str);
}
</script>
<form name="asa">
<select name="cars" id="combo" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" onclick="get()">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
</body>
</html>

In angular 4, instead of using angular multi-select dropdown I used the normal one.
Following is the code.
HTML file:
<select [ngModel]="DataValue" (change)="selectChangeHandler($event)"
id="multiple-select" name="multiple-select" class ="form-control" multiple>
<option *ngFor="let ref of Data" [value]="ref['title']">
{{ref['title']}}
</option>
</select>
Ts file:
selectChangeHandler (event: any) {
let oldvalue;
let mergedValue = "";
for ( let index = 0 ; index < event.currentTarget.selectedOptions.length; index++)
{
oldvalue = event.currentTarget.selectedOptions[index].value.replace(/["']/g, "");
oldvalue = oldvalue.split(': ')[1];
if (index ==`enter code here`= 0)
{ mergedValue += oldvalue; }
else
{ mergedValue += ", " + oldvalue; }
}
console.log(mergedValue);
}
Comments:
Using event.currentTarget.selectedOptions[index].value you can get multiple selected values of multi-select dropdown. In my case, mergedValue gives me proper multiple selected values.
I have used split and replace to format the string obtained as I wanted it common separated.
I hope this can help someone.

Related

Using Javascript to check form elements and enabling/disabling the search button

I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.

Javascript, grading multiply options

I have read a lot of topics already but I still do not have a clue what I have to write to make my check() work.
When you choose an option, it will generate multiply questions ( 1 x 1 1 x 2 etc. ) then the user needs to fill in the right answer and when pressed on the submit button it needs to make the good answers green and the bad answers red.
I tried a lot of ways but this time I just can not see it haha. can anyone tell me or bring me in the right direction of what I need to write in my calc()
Thanks for helping :)
<div id="section">
<h2>De toets</h2>
<p>Welke toets wil je maken?</p>
<label for="toetsmenu"></label>
<select id="toetsmenu" onchange="toets()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="toetsding"></div>
<script>
function toets() {
var x = document.getElementById("toetsmenu").value;
document.getElementById("toetsding").innerHTML = "";
for (i = 1; i < 11; i++) {
document.getElementById("toetsding").innerHTML += x + " x " + i +
" = <input type='text' id='test'>" + "<br>";
}
document.getElementById("toetsding").innerHTML += "<input type='submit' value='check' id='sub' onclick='calc()'>"
}
function calc() {
}
</script>
</div>
When creating the <input> elements you need to give them each a unique ID: id='test" + i + "
In the calc() function you can then simply access them by their ID in the loop and check the result
function toets() {
var x = document.getElementById("toetsmenu").value;
document.getElementById("toetsding").innerHTML = "";
for (i = 1; i < 11; i++) {
document.getElementById("toetsding").innerHTML += x + " x " + i +
" = <input type='text' id='test" + i + "'>" + "<br>";
}
document.getElementById("toetsding").innerHTML += "<input type='submit' value='check' id='sub' onclick='calc()'>"
}
function calc() {
var x = document.getElementById("toetsmenu").value
for (i = 1; i < 11; i++) {
var input = document.getElementById("test" + i)
var result = input.value
console.log(input.value)
if (result == x * i) {
input.className = "correct"
} else {
input.className = "wrong"
}
}
}
toets()
.wrong {
background-color: red;
}
.correct {
background-color: green;
}
<div id="section">
<h2>De toets</h2>
<p>Welke toets wil je maken?</p>
<label for="toetsmenu"></label>
<select id="toetsmenu" onchange="toets()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="toetsding"></div>
</div>

JQuery convert string to link

I have 3 select fields, and the combined value of these I would like to use as a extra part of an url.
Here's the HTML code:
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>
And the JavaScript:
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text(str);
})
.trigger('change');
https://jsfiddle.net/eZKUU/264/
Right now it's working.. after I select an option in all 3 of the selectfields I get an output like /squad/redblack/1985.
I would like to use this output in an url, so it would look like:
mysite.com/squad/redblack/1985
Is there an easy way of doing this? And also.. To only get the link visible after all three of the selectfields have an option selected?
You can use the following. Add an a element and keep it hidden until is completed. Update a element href attribute with selected options:
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
//update href with selected values
$("#mySite").attr("href", "mysite.com/" + str);
});
//keep anchor element hidden until all three options is selected
$("#mySite").toggle($("#cos").find("option:selected").length > 0 && $("#color").find("option:selected").length > 0 && $("#year").find("option:selected").length > 0);
$("div#output").text(str);
})
.trigger('change');
#mySite {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/>
<br/>
<div id="output"></div>
<a id="mySite" href="#">Redirect Link</a>
You can check to see if the number of selected options is the same amount as the number of select elements.
var selectedAllLength = $("select").length;
$("select").change(function () {
var str = location.origin;
var selected = $("select option:selected");
var selectedCount = selected.length;
if(selectedCount == selectedAllLength) {
selected.each(
function () {
str += $(this).attr('value');
}
);
$("#output").html('<a href=' + str + '>The link is here</a>');
}
})
.trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>
To only get the link after all three have been selected, simply use an if statement to only generate and display the link if 3 options are selected. To make it a URL, just append the path you get to the base URL. Something like:
$("select").change(function () {
var str = "";
if(#("select option:selected").length === 3){
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text("mysite.com" + str);
// Or, if you want a clickable link and not just a URL:
// $("div#output").append($("<a>").attr({href: "mysite.com" + str}).append("Click me"));
}
})
.trigger('change');

how to get a value from option when select (this code working for chrome)

how to get value from option
<script>
function usgsChanged(el) {
window["display_" + el.options[el.selectedIndex].value]();
}
function display_1() {
//how to get value from option
}
</script>
how to get value from option when select
<select onchange="usgsChanged(this);">
<option value="1">1</option>
<option value="2">2</option>
<option value="">more</option>
<option value="">more</option>
<option value="">more</option>
</select>
<script>
function usgsChanged(option) {
var value = option.value; //The value now resides in this variable
}
</script>
<select onchange="usgsChanged(this);">
<option value="1">1</option>
<option value="2">2</option>
<option value="">more</option>
<option value="">more</option>
<option value="">more</option>
</select>
try something like this
$('#idOfSelectTag').change(function(){
var value = $(this).val();
alert(value);
});
Try looking at internet before sanding a question. For example here.
Try this:
<script type="text/javascript">
function usgsChanged(el) {
var index = el.selectedIndex;
var selectOptions = el.options;
var optionValue = selectOptions[index].value;
var optionText = selectOptions[index].text;
alert("Value is " + optionValue + " and text is " + optionText );
}
</script>
And HTML:
<select onchange="usgsChanged(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="">more</option>
<option value="">more</option>
<option value="">more</option>
</select>

Get first value of selected items from a multiple select in JavaScript?

I have this code to get the text of the selected option from a in JavaScript:
form_name.select_name.options[form_name.select_name.selectedIndex].text
For example, with
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
When user selects 3, the code would return 3.
My question is, when it's a multiple select such as:
<select multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
How to return the text of the first selected item in JavaScript? For example, when 2 and 3 are selected, it would return 2.
Any help would be appreciated. Thanks!
see below
<html>
<body>
<form name="myForm">
<select name="myOption" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type=submit value="Print First" onClick="printMe()">
<input type=submit value="Print All" onClick="printAll()">
</body>
<script>
function printMe() {
alert ("Selected option is " + myForm.myOption.value);
}
function printAll() {
var str="",i;
for (i=0;i<myForm.myOption.options.length;i++) {
if (myForm.myOption.options[i].selected) {
str = str + i + " ";
}
}
alert("Options selected are " + str);
}
</script>
</html>
Hope this is what you want...
I have also provided print all and print first option...
Good Luck
You can do it like so with jQuery:
$('select option:selected').first().text()
Something like this should do the job, and is easily modified to get all values, or a specific index.
var selected = ''; // make this into an array to get all / specific value
var mySelect = form_name.select_name;
while(mySelect.selectedIndex != -1)
{
if(mySelect.selectedIndex != 0)
{
selected = mySelect.options[mySelect.selectedIndex].text; // change this to selected.push(...) for all/specific values
}
}
if (selected.length)
{
// at least one thing was selected, have fun
}
HTML
<select id="your-select" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
JavaScript
function getFirstSelected(yourSelectId)
{
var yourSelect = document.getElementById(yourSelectId);
var optionLength = yourSelect.options.length;
for (i = 0; i < optionLength; i++) {
var option = yourSelect.options[i];
if (option.selected) {
return option.value;
}
}
return "";
}
Usage
var firstSelectedOption = getFirstSelected("your-select");
Edit
Just realized that this will give you the first selected value and the function is not needed
var firstSelectedOption = document.getElementById("your-select").value;

Categories

Resources