Javascript to populate an option box with an array - javascript

Hi was wondering if you could help, i need to use JavaScript to populate the clothes option box with appropriate options when the user specifies what type of gender they are. This is the code I have so far,
<script type="text/javascript">
var subListArray = [];
subListArray[0] = 'Select a type first';
subListArray[1] = ['skirt', 'dress', 'tights'];
subListArray[2] = ['jeans', 'hat'];
</script>
Person
Gender Type: <select name="genderType" id="genderType" >
<option value="">Gender Type?</option>
<option value="girl">Female</option>
<option value="boy">Male</option>
</select> </br>
Clothes <select name="clothType">
<option value="">Choose a Type</option>
</select>

Use objects instead of arrays so that you can map the subList to the selected gender. You don't have to do this, but it simplifies things a bit. Add a "change" listener to the gender selector that creates the option elements for the new select box:
var subListArray = {
'default': ['Select a type first'],
'girl': ['skirt', 'dress', 'tights'],
'boy': ['jeans', 'hat'],
};
document.getElementById('genderType').addEventListener('change', function () {
var sel = document.getElementById('clothType'),
value = this.value ? this.value : 'default';
sel.innerHTML = '';
subListArray[value].forEach(function (item) {
sel.appendChild(new Option(item));
});
});
http://jsfiddle.net/VdXk6/

See this page which explains adding elements to the DOM:
http://www.javascriptkit.com/javatutors/dom2.shtml
You need to use createElement, setAttribute and appendChild. E.g:
html:
<select id="mySelect">...</select>
<select id="mySubSelect"></select>
javascript:
var myNewOption = document.createElement( 'option' );
myNewOption.setAttribute( 'value', 'myOptionValue' );
document.getElementById( 'mySubSelect' ).appendChild( myNewOption );
This can go in a loop. Also you can detect when the selection changes like this:
javascript:
document.getElementById('mySelect').addEventListener('change',function(){
document.getElementById('mySelect').selectedIndex; // a number showing which element is selected
});
With jQuery it is a lot easier.

Related

Why won't it recognize an invalid selection from my dropdown menu?

I'm trying to display a message to the user if they decide not to choose an item from the dropdown menu using strictly vanilla JS. Instead, I get an error in the console that says cannot read property 'selectedIndex' of null. I cannot see what I'm doing wrong.
How can I rectify this problem?
Here's HTML:
<form>
<div>
<label>Drop Down Menu
<select name="menu">
<option value="">---</option>
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
</select>
</label>
</div>
</form>
Here's JS:
var myForm = document.getElementsByTagName("form");
myForm.id = "the-form";
var submitButton = document.getElementsByTagName("button")[1];
submitButton.id = "submit-button";
function formValidation() {
var select = document.getElementsByTagName("select");
select.id = "myMenu";
var selectId = document.getElementById("myMenu");
if(selectId.selectedIndex <= 0) {
console.log("a menu item must be selected!");
}
alert("Chosen!");
}
submitButton.onclick = myForm.onsubmit = function() {
formValidation();
};
You are targeting a DOM node by the id of "myMenu" here:
var selectId = document.getElementById("myMenu");
while the select you want to target has id "menu". Therefore, you have to change either the id in the JS selection or the select's id in the html.

Get Option HTML by it's value in Jquery

How we can get the option HTML in jquery by it's value in jQuery.
HTML
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
Array
var id_arry = ['21','24','2'];
I have this array that have some values related to values in the drop down. Now i want to get all the options that matches the value in dropdown HTML
like
<option value="21">A</option><option value="24">D</option> <option value="2">E</option>
This is the final out put i want from the drop-down.Kindly help me in this
I want to add those options html in this dropdown:
<select multiple="" style="width: 147px;" id="list" name="list1" class="list_class">
</select>
Maybe something like this:
var id_arry = ['21','24','2'];
var optionMatches = $('#list option').filter(function() {
return $.inArray($(this).val(), id_arry);
});
Breaking it down:
$('#list option') - returns all of the options in the select list with ID "list"
.filter(callback) - a simple filter function -- the callback decides whether the option makes it into the final list
$.inArray($(this).val(), id_arry) - checks if the current option value is in the array id_arry
After studying your example, it looks like you'll first want to obtain the selected options from your multi-select drop-down list to build your id_arry, which is very easy:
var id_arry = $('#list').val();
Once you have these and the optionMatches array of elements, you can clone them over to a new drop-down:
optionMatches.clone().appendTo('#otherSelect');
One solution is using join and split:
var id_arry = ['21', '24', '2'];
$("#list").val(id_arry.join(',').split(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
You can use jQuery's attribute equals selector to target elements with a specific attribute value:
$( "option[value='21']" )
Using this selector and a simple loop, you can extract all the elements you need:
var elements = [];
var id_array = ['21','24','2'];
for ( index in id_array ){
var elem = $( "option[value='" + id_array[ index ] + "']" );
if ( elem ) {
elements.push( elem );
}
}
Your elements array now contains all option elements who's values appear in id_array.
var id_arr = ['21','24','2'];
var entireHTML = "";
var options = $('select').find('option');
var tempDiv = $('div');
//id_arr = $('select').val(); //Uncomment this line to get value from the select element.
$.each(id_arr, function(index, value){
entireHTML = "";
$(options).each(function(){
if( $(this).val() === value)
{
$(this).clone().appendTo(tempDiv);
}
});
});
entireHTML = $(tempDiv).html();
Since you need the HTML content of the 'option' elements, they're cloned and wrapped in a temporary div so that the inner HTML of that temporary div is copied and appended to our final HTML string.
Check it out for yourself : JSFiddle Test Link

Get element with a certain value, make it selected

I have a form with this disabled select element (I have disabled it with jquery)
<select class="select form-control" id="ifacility" name="facility">
<option value="" selected="selected">------</option>
<option value="1">Room 1</option>
<option value="2">Room 1</option>
<option value="3">Room 2</option>
<option value="4">Room 3</option>
</select>
I want to use Jquery to find an option with a name eg Room 2 and make it selected.
$(document).on('click', '.select-option', function() {
var room = $(this).attr('value') //This is what gives the 'Room 2'
//I want to select this room from the options and make it selected
});
You don't really need jQuery for this, so here's a plain-old JavaScript solution.
Declare this function:
function setOptionByValue(select, value){
var options = select.options;
for(var i = 0, len = options.length; i < len; i++){
if(options[i].textContent === value){
select.selectedIndex = i;
return true; //Return so it breaks the loop and also lets you know if the function found an option by that value
}
}
return false; //Just to let you know it didn't find any option with that value.
}
Use it like this:
setOptionByValue(document.getElementById('ifacility'), 'Room 2');
Demo
A jQuery solution using filter():
var room2 = $('#ifacility option').filter(function() {
return $(this).text() == 'Room 2';
});
// room2.val() = '3'
$('#ifacility').val(room2.val());
Fiddle
If you want to user jQuery to accomplish task, try this
$('#ifacility').find('option:contains("Room 2")').prop('selected', true);
It finds option by text and sets its selected attribute.

How to get different selected values in javascript?

Hello everyone how can I get two values from different select boxes? I get first value in my select box but I can't get the second value from another select box.Here is my javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var select = document.forms[0].sel;
var select2=document.forms[0].sel2;
select.onchange = function () {
var value = select.options[select.selectedIndex].value; // to get Value
alert(value);
}
select2.onchange = function () {
var value2 = select2.options[select2.selectedIndex].value; // to get Value
alert(value2);
}
});
</script>
<form>
<SELECT NAME="sel" onChange="split(selected value)">
<OPTION VALUE=1>Milk</option>
<OPTION VALUE=2>tea</option>
<OPTION VALUE=3>water</option>
<OPTION VALUE=4>coffee</option>
</SELECT>
</form>
<form>
<SELECT NAME="sel2" onChange="split(selected value)">
<OPTION VALUE=1>Milk</option>
<OPTION VALUE=2>tea</option>
<OPTION VALUE=3>water</option>
<OPTION VALUE=4>coffee</option>
</SELECT>
</form>
The second select box is in the second form. So:
var select2 = document.forms[1].sel2;
That said, you can actually use jQuery for these things:
// bind a change event handler to the second select
$("select").eq(1).on("change", function() {
alert( $(this).val() );
});
jQuery Tip - Getting Select List Values
var foo = [];
$('#multiple :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
$(document).ready(function () {
$('#sel').change(function(){ $('#sel option:selected').val(); });
give id to your select control
<SELECT id="sel">
with help of jQuery ( i suggest the logic, not the solution )
$(document).on('change', 'select', function(){
var selecetdOption = $(this).val();
alert(selecetdOption );
});​
Working Demo
You have wrong into your javascript because you have put
var select2=document.forms[0].sel2;
try to put
var select2=document.forms[1].sel2;
and it works!

How do i get different information in a field based on what i select in a dropdown menu?

I want to add this functionality to my form. when a option from a dropdown menu is selected i want it to input the text field above with the corresponding info. For example:
<form name="form1" action="formhandler">
<input type="text" name="typecar">
<select name="BMWCars">
<option value="Sedan">Sedan</option> // when this option is chosen put string "5-series" in textfield above
<option value="Convertible">Convertible</option> // when this option is chosen put string "6-series" in textfield above
<option value="Truck">Truck</option> // when this option is chosen put string "X5" in textfield above
<option value="Coupe">Coupe</option> // when this option is chosen put string "3-series" in textfield above
<option value="Hatchback">Hatchback</option> // when this option is chosen put string "5-series GT" in textfield above
</select>
</form>
How can this be done with and without having to connect to the to get strings?
The code is tidier if you make your HTML conform to what you need.
http://jsfiddle.net/TgM2W/3/
<form name="form1" id="form1" action="formhandler">
<input type="text" name="typecar" id="typecar">
<select name="BMWCars" id="BMWCars">
<option value="">Select one...</option>
<option value="5-series">Sedan</option>
<option value="6-series">Convertibles</option>
<option value="X5">Truck</option>
<option value="3-series">Coupe</option>
<option value="5-series GT">Hatchback</option>
</select>
</form>
JavaScript (without jQuery):
window.onload = function() {
document.forms['form1'].elements['BMWCars'].onchange = function() {
var opts = this.options;
document.forms['form1'].elements['typecar'].value = opts[opts.selectedIndex].value;
};
};
or using jQuery:
$(document).ready(function() {
$('#BMWCars').change(function() {
var opts = $(this)[0].options;
$('#typecar').val(opts[opts.selectedIndex].value);
});
});
However, if you can't change the HTML, just use an object to store the values and reference that:
objBMW = {
"Sedan":"5-series",
"Convertible":"6-series",
"Truck":"X5",
"Coupe":"3-series",
"Hatchback":"5-series GT"
};
window.onload = function() {
document.forms['form1'].elements['BMWCars'].onchange = changer;
};
function changer() {
var opts = this.options;
document.forms['form1'].elements['typecar'].value =objBMW[opts[opts.selectedIndex].value];
};
Jan. This is what you have to do:
Add identifier to all your referenced items in the HTML.
Write an small Javascript code to detect changes in the dropdown and update the textfield accordly.
<form name="form1" action="formhandler">
<input type="text" name="typecar" id="typecar" />
<select name="BMWCars" id="dropdown">
<option value="5-series">Sedan</option>
<option value="6-series">Convertible</option>
<option value="X5">Truck</option>
<option value="3-series">Coupe</option>
<option value="5-series GT">Hatchback</option>
</select>
</form>
<script type="text/javascript">
var dropdown = document.getElementById( 'dropdown' );
dropdown.onchange = function() {
document.getElementById( 'typecar' ).value = dropdown.value;
};
</script>
You're going to want to do it in jQuery (or javascript).
$("option").change(function() {
var value;
//Do some logic to get the value you want to put in the textbox
$("input[name='typecar']").val(value);
});
Depending on the complexity of your site, there's a couple different ways you can grab the value to put in your textbox. If it will only ever be those 5 options, I would suggest a switch...case. Like this:
$("option".change(function() {
var value;
switch($(this).val()) {
case "Sedan":
value = "5-series";
break;
case "Convertible":
value = "6-series";
break;
case "Truck":
value = "X5";
break;
case "Coupe":
value = "3-series";
break;
case "Hatchback":
value = "5-series GT";
break;
}
$("input[name='typecar']").val(value);
});
$('select').change(function() {
var value = $(this).val();
$("#typecar").val(value);
});
Should do it. Add an ID of typecar to your input field first however.

Categories

Resources