This question already has answers here:
Add item to dropdown list in HTML using JavaScript
(5 answers)
Closed 8 years ago.
i need to populate year in second dropdownlist on selecting value from first dropdown.And the year range is between 1900 to 2050
can anyone help?
First, create a select element. So in your HTML document,
<select id="year">
<option value="-1"> </option>
</select>
There is an empty option if the user doesn't want to fill it in. Feel free to give it an another value or another text like "please choose a year". The reason behind it is that if the user has disabled javascript, the years won't be appended. You will end with an empty select box.
Then use a script to add more option elements to fill it with years.
// get selectbox
var selectBox = document.getElementById('year');
// loop through years
for (var i = 2050; i >= 1900; i--) {
// create option element
var option = document.createElement('option');
// add value and text name
option.value = i;
option.innerHTML = i;
// add the option element to the selectbox
selectBox.appendChild(option);
}
Please ensure that the parameter at getElementById has the same id as the HTML select element.
A needless One Liner: (DEMO)
$((new Array(150) + "").split(",").map(function (i,j) {return $("<option>").append(j + 1900)[0];})).appendTo($("select"));
Expanded:
var option = function (i,j) {return $("<option>").append(j + 1900);};
var options = (new Array(150) + "").split(",").map(option);
$("select").append(options);
I have created jsfiddle Please look
I have attached change event to first combo box and according to its value populating 2nd combo value.
You can do whatever you want inside function
$("#s1").on("change", function(){
var value = $(":selected", this).val();
if(value == 'a'){
$("#s2").val('2000');
}else{
$("#s2").val('2010');
}
})
Just create a for loop that starts at 1900 and ends at 2050 (or the other side), and append options to the dropdownlist:
<select id="myDDL"></select>
var i=0;
for(i=1900;i<=2500;i++)
{
$("#myDDL").append("<option value='"+i+"'>"+i+"</option>")
}
Related
This question already has answers here:
Get selected option text with JavaScript
(16 answers)
Closed 2 years ago.
With this HTML for a DropDownList (that relates to a model with simple int Id and string Name)
<select id="Powder_Id" name="Powder.Id">
<option value="1">50g</option>
<option value="2">100g</option>
</select>
I can get the selected option key (Id) using this JS:
function save() {
var payload = {
DdlId: $("#Powder_Id").val() // e.g. 1 or 2
};
But how can I get the selected option value (Name)? Something like SelectedValue in place of val()?:
function saveSummary() {
var p = {
Powder: { Id: $("#Powder_Id").SelectedValue } // e.g. "50g" or "100g"
}
Ideally I want to recreate the model as an object to pass to an ajax call, but to do that I need both the Id and Name values.
You can get selected text by
$("#Powder_Id option:selected").text();
var selectedText = $("#Powder_Id option:selected").text();
console.log(selectedText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Powder_Id" name="Powder.Id">
<option value="1">50g</option>
<option value="2">100g</option>
</select>
I want to know all the values of a select element once the change event is recorded on it.
Code is like this:
PHP
<select name='variant' class='variantsselect' onchange='on(this.value)'>
<option value='a'>a</option>
<option value='a'>a</option>
</select>
JAVASCRIPT
function on(value){
alert(value); //This gives me selected value
};
I need values a & b when change event is recorded on select element. Can someone help?
<select name='variant' class='variantsselect' onchange="javascript:valueselect(this)">
function valueselect(sel) {
var value = sel.options[sel.selectedIndex].value;
alert(value)
}
EDIT:
<select name='variant' id='variant' class='variantsselect' onchange="javascript:displayResult()">
function displayResult() {
var x = document.getElementById("variant");
var i;
var txt = "Text: ";
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].text;
}
alert(txt);
}
You can store the last selected value in a variable and overwrite the variable with the new selected value at the end of your function. When the function is called the variable will = to the last option selected (If you don't set a default value the variable will be empty on the first call)
Click Here For Demo
OR
This will work for a simple hide/show select without having to remember the previous selection.
The hide/show content have a class name of HideShow, this class name css display is set to none. When you change the option it will loop through all elements using the class name HideShow to compare the selected value with the id of the element, if they match it will set the style display to block }else{ set style display to none.
Demo
function HideShow(Selection){
var HScontent=document.getElementsByClassName('HideShow');
for(var i=0; i<HScontent.length; i++){
if(HScontent[i].id==Selection){
HScontent[i].style.display="block";
}else{
HScontent[i].style.display="none";
}
}
}
.HideShow{display:none;}
<select onchange="HideShow(this.value);">
<option value="cars">Cars</option>
<option value="bikes">Bikes</option>
<option value="buses">Buses</option>
</select>
<div id="cars" class="HideShow">Cars content.....</div>
<div id="bikes" class="HideShow">Bikes content....</div>
<div id="buses" class="HideShow">Buses content....</div>
If you don't understand something in the demo, leave a comment below and I will try get back to you as soon as possible.
I hope this helps. Happy coding!
I have a very simple select dropdown with urls that direct users to respective pages
<select>
<option value="url1">title1 </option>
<option value="url2">title2 </option>
<option value="url3">title3 </option>
.........
</select>
I will have this drop down in all these (url1, url2, url3...) serving for navigation. Would it be possible to set the default text in the selection box based on my urls? Say if I am currently on url2, my default text in the selection box will be title2. I know manually you can just use
<option selected="selected" value="url2">title2</option>
But is there a way I can use javascript to do because I have hundreds of pages? All the urls and titles are stored in an array that I can retrieve.
Thanks for your help!
Assuming you want to match the url in the window location (such as http://www.example.com/some/page.html) with the URL to the page found in your dropdown:
var dropdown = document.getElementById( 'dropdown' );
for ( var i = 0; i < dropdown.childElementCount; ++i ) {
if ( dropdown.children[i].value === document.location.href) {
dropdown.selectedIndex = i;
break;
}
}
Where 'dropdown' contains the ID of your <select> element. Jsfiddle: http://jsfiddle.net/RhZy6/
You should be able to use this:
var path = decodeURIComponent(window.location.pathname.replace(/\/$/, ""));
$("option").each(function () {
var url = $(this).val();
if (path.substring(0, url.length) === url) {
$(this).prop('selected', true);
}
});
Path is the end of the URL. The next block of code loops through the option elements and looks to see if the option value matches the path, and if it does, sets the selected property to true.
You can get the current URL using document.URL and on document ready you can use ,
$("#selectId option[value=" + document.URL + "]").prop('selected', true);
However document.URL contains full path , so you need to truncate the unnecessary part like http:// https:/ , if it is not present in value of select.
And , here is the working fiddle
P.S The Fiddle will work second time only. It is shwoing diffrent URL on first time. Gotta be a JSFiddle personal thing.
Say you have
<form name="MyForm">
<select name="SelectBox1">
<option>One
<option>Two
<option>Three
</select>
.. etc .. rest of form/page ..
then in your javascript code ..
var el=document.forms.MyForm.SelectBox1;
el.selectedIndex=2; // sets option to "Three" in Select box, because first option is number 0, second =1, third = 2 etc
Or to set it to a value use a function like this .. pass in the Select field name and the value it should be
function setSelect(sFieldName, sValue) {
var el=document.getElementsByName(sFieldName)[0] // returns array of all elements with that name so use [0] to get 1st one
for (var i=0;i<el.options.length;
if (el.options[i].value == sValue) { // if they match...
el.selectedIndex=i; // then this should be the default
}
}
call it usiong something like
setSelect("SelectBox1","http://ectetc")
I am using javascript to programmatically add options to an html select box. When I add a new option, I am setting that option's .selected property to true so that it is the one that appears in the select box. When I do this, the innerHTML does not change to the new value, but when I click in the select box, I see the option I wanted selected has a checkmark next to it, indicating it is selected. Why isn't the value shown the correct value?
Here is my function that populates the select box options:
function printCartList(newCart){
// Check if newCart is null
newCart = newCart ? newCart : "a_new_cart_was_not_provided_12345abcde";
// set carts object from cookie if it exists, otherwise create a new one
if($.cookie("carts") != null){
carts = JSON.parse($.cookie("carts"));
}
else{
selectOption = new Object();
selectOption.value = "newuniquecartid12345abcde";
selectOption.html = "***New Cart***";
carts = new Object();
carts.size = 1;
carts.option = new Array();
carts.option[0] = selectOption;
}
// Get the select element
var select = document.getElementById("select_cart");
// Get the length of the select options list
var length = select.options.length;
// Remove all items from the select box
while(select.options.length > 0){
select.remove(0);
}
// If newCart was provided, create a new option and add it to the cart
if(newCart != "a_new_cart_was_not_provided_12345abcde"){
selectOption = new Object();
selectOption.value = newCart;
selectOption.html = newCart;
carts.option[carts.size] = selectOption;
carts.size++;
}
// Save the cart in a cookie
$.cookie("carts",JSON.stringify(carts));
// Add the options to the select box
for(var i = 0; i < carts.size; i++){
var opt = document.createElement('option');
opt.value = carts.option[i].value;
opt.innerHTML = carts.option[i].html;
if($.cookie("activeCart") == carts.option[i].value){
// Set the option to true if the cart is the active cart.
//*****I have tested this with an alert box showing the value of carts.option[i].value This is being called for the correct option*******
opt.selected = true;
}
select.appendChild(opt);
}
}
The new item is being added to the select box, and does have a checkmark next to it when viewing all the items in the select box, it just doesn't show the correct value in the select box.
Here is my html:
<form method="POST" name="cartSelectForm" action="home.php">
<select name="cartList" id="select_cart" data-mini="true" onchange="submitCartForm()" data-icon="false">
<option value="newuniquecartid1234567890">*** New Cart ***</option>
</select>
</form>
edit
I have discovered that jquery css is interfering with javascript filling the innerHTML of the select box. I am linking in: "http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css". Is there anyway to get around the jquery? I can't just remove the jquery css. That would break everything on my site, and I don't have time to redo it all.
Here is a jsfiddle of the problem: http://jsfiddle.net/RjXRB/1/
It's better to use angular way when creating select box - look here: http://docs.angularjs.org/api/ng.directive:select
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select>
If you have a reason to use the innerHtml approach, you should consider using Scope.apply or Scope.$digest as described in the docs.
Using a nested form I generated 5 UserPrices so users are filling out 5 of all of the same form fields:
UserPricesController
def add_store_prices
#a_new_user = User.new
5.times do
#a_new_user.user_prices.build
end
end
I have one field called :purchase_date which is a date_select (date dropdown menu) field:
<%= f.date_select :purchase_date %>
I want to use only one UserPrice date_select to be the date for the other 4 UserPrices, this way users don't have to select 5 date dropdown menus and can just select one only, is there a jquery plugin or javascript code to make this possible?
P.S.: This is how it looks right now, I want to get rid of the other 4 Date rows and just have one.
New version more generic, This will change any amount of date selects as long as you have a underscore and a integer at the end an begins at 1, for each selct id
<select id="purchase_date_month_1" onchange="changesPurchaseDates(this)"><option>10<option>12</select>
<select id="purchase_date_day_1" onchange="changesPurchaseDates(this)"><option>29<option>28</select>
<select id="purchase_date_year_1" onchange="changesPurchaseDates(this)"><option>2010<option>2011</select>
so the the remaining are
<select id="purchase_date_month_2">
<select id="purchase_date_day_2">
<select id="purchase_date_year_2">
<select id="purchase_date_month_3">
<select id="purchase_date_day_3">
<select id="purchase_date_year_3">
.... to the (N)th or 5th then you could use this function to select the first option which will change the remaining.
<script>
function changesPurchaseDates(n) {
var arr_purdate_selects = []; // object to store the select boxs
var nd = (n.id).slice(0,(n.id).lastIndexOf("_")); // slice off the remaining from last underscore
arr_purdate_selects = document.getElementsByTagName("select"); // store all found selects Diry i know
// loop throught all selects
for (var i = 1; i < arr_purdate_selects.length; i++) {
// only if the ids match the change those
if(nd == (arr_purdate_selects[i].id).slice(0,(arr_purdate_selects[i].id).lastIndexOf("_"))){
document.getElementById(arr_purdate_selects[i].id).selectedIndex = document.getElementById(nd+"_"+1).selectedIndex;
}
}
}
</script>
I hope this helps