How to change an element using a select dropdown menu - javascript

I'm trying to change an element through a select drop down menu- however, I'm unable to get it to change dynamically.
<select id="optMapList">
<option>Map 1</option>
<option>Map 2</option>
</select>
<script>
document.getElementById("maptype").innerHTML=optMapList.options[optMapList.selectedIndex].text
</script>

Your code seems to run fine. I think you're missing the fact that you have to listen to a 'change'-event in order to by able to run code on changes. This is done as follows:
var optMapList = document.getElementById('optMapList');
optMapList.onchange = function() {
document.getElementById("maptype").innerHTML = optMapList.options[optMapList.selectedIndex].text;
}
Working example: http://jsfiddle.net/thijs_s/gx9mf1ct/

You can just use the value property of the select list inside an event listener as noted below.
var optMapList = document.getElementById('optMapList');
optMapList.onchange = function() {
document.getElementById("maptype").innerHTML = optMapList.value;}

Related

Get selected value from multiple select on change in dynamic form

I'm currently working on a dynamic form which enables the user to add as many variants as they would like. This form which can be added has a price, size and color. The size and color are select2 select boxes which enable the user to select multiple things. The form:
<div class="col-sm-4">
<label>Kleuren</label>
<select name="colors[{{$i}}][]" id='color-options' class="form-control multiple-select" multiple="multiple">
#foreach($colors as $id=>$color)
<option value="{{$id}}">{{$color}}</option>
#endforeach
</select>
</div>
When looking at the HTML code I have multiple of these forms which go by name: colors[0][], colors[1][], colors[2][] etc.
How do I print the value of a selected new color in a new div? The code which I have thus far:
$(document).ready(function() {
$('.multiple-select').select2({
language: 'nl'
});
$('.summernote').summernote();
var addVariantButton = document.getElementById('addVariant[0]');
addVariantButton.addEventListener('click', function(){
addVariant(0);
});
var colorSelected = document.getElementsByName('colors[0][]');
colorSelected.addEventListener("click", displayColorSelected);
});
function displayColorSelected() {
var selected_value = document.getElementById("color-options").value;
console.log(selected_value);
}
But this only works for the first colors input form, but how can I make this into a more dynamical function to get all colors input?
You can get all selected values in array as below:
function displayColorSelected() {
var selected_value = $("[id='color-options']").toArray().map(x => $(x).val());
console.log(selected_value);
}
Note: id selector will always return single element which will be first with that id. So you're getting value for first select only.
You can use attribute selector ([]) instead which will find every element with given id. So here $("[id='color-options']").toArray() will find every element with id equal to color-options and map(x => $(x).val()) will return only value part from the elements array.
Add all the selects a class ("color-select" for example), and run over all the selects -
$('.color-select').each(function() { console.log($(this).val()); })
You may need to delegate your event listener
document.addEventListener('event',function(e){
if(element){//do something}
})
Since you are using jquery its easier
$(document).on('event','element',function());

How to change default dropdown style to a navbar-links and default select event still work?

I have a #Html.DropDownList extension in my razor view , which generate a html dropdown , sort options and append a url (query string) to each option.
what i am trying to do is changing it css/html to achieve a navbar-link style instead dropdown style.
i use #html.dopdownlist extension for all of the dropdowns in my website.
i don't want change the extension code or create another extension.
the picture blow shows what i am trying to do (changing drop-down style to a navbar style same as second row).
it's my back-end code :
#Html.DropDownList("products-orderby",
Model.AvailableSortOptions, new { onchange = "setLocation(this.value);" })
client-side code :
<select id="products-orderby" name="products-orderby" class="sortOptionsDropDown">
<option selected="selected" value="15">New</option>
<option value="10">Price : High to Low</option>
<option value="11">Price : Low to High</option>
<option value="5">Alphabetic</option>
</select>
a simple html for my goal is blow but if i want do this , i have to edit #html.dopdownlist extension which i use for all of my dropdowns or i have to create another extension.
<!-- my desired style -->
<div id="products-orderby" name="products-orderby" class="sortOptionsDropDown">
<a class="selected" >New</a>
<a data-value="10">Price : High to Low</a>
<a data-value="11">Price : Low to High</a>
<a data-value="5">Alphabetic</a>
</div>
is there any jquery plugin or javascript code to change my dropdown's style to navigation bar links? (there is a simple plugin called jquery bar rating which change a drop down to a rating bar).
or is this possible to change dropdown style to my desired style at client side?
here is jsfiddle with my current dropdown style and what i am trying to achieve.
Update : changing code in front-end with java script cause default select option event doesn't get run (dropdown on change event). it's from my controller code which modify my current page url and add selected sort option to it :
if (pagingFilteringModel.AllowProductSorting)
{
foreach (var option in activeOptions)
{
var currentPageUrl = _webHelper.GetThisPageUrl(true);
var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + (option.Key).ToString(), null);
var sortValue = ((ProductSortingEnum)option.Key).GetLocalizedEnum(_localizationService, _workContext);
pagingFilteringModel.AvailableSortOptions.Add(new SelectListItem
{
Text = sortValue,
Value = sortUrl,
Selected = option.Key == command.OrderBy
});
}
}
You can do it like below on the client side:
// Selecting your dropdown
var yourSelect = $('#products-orderby');
// Checking for existing
if (yourSelect != undefined) {
// Creating div that includes a tags according to your dropdown
var navBarDiv = $(document.createElement("div"))
.addClass($(yourSelect).attr("class"))
.attr("name", $(yourSelect).attr("name"))
.attr("id", $(yourSelect).attr("id"));
// Selecting dropdown options
var options = yourSelect.find('option');
// Creating a tags according to options
$.each(options, function() {
var link = $(document.createElement('a'))
.attr("data-value", $(this).val())
.text($(this).text());
// Appending a tags to parent div
navBarDiv.append(link);
});
$('#products-orderby').after(navBarDiv);
}
Online demo (jsFiddle)
Edit
For default selecting, you can add code below:
// default select
if($(this).prop("selected"))
link.addClass("selected");
Online demo (jsFiddle)

Initialize with javascript and html

<script>
$(document).ready( function()
{
var element1 = getElementById('#SelectTable1');
element1.style.background = element1.options[element1.selectedIndex].value;
}
</script>
I have a dropdown box which contain colorthat I want to initialise its value as its background. The select does work. I just can't make it to be initialized with the background that has the color of selectedindex.value.
The html code for the select is below:
<select class="tableselect" id="SelectTable1" onchange="this.style.background=this.options[this.selectedIndex].value;">
<option value="#4eb96e">ΟΛΟΚΛΗΡΩΘΗΚΕ</option>
<option value="#e57d24">ΑΝΑΜΟΝΗ</option>
<option value="#efc319">ΕΠΙΔΙΟΡΘΩΝΕΤΑΙ</option>
<option value="#e64c3b" selected>ΑΠΟΡΡΙΦΘΗΚΕ</option>
</select>
The onchange does work. I wish I could find a way to initialize my select's background with its value. Tried css.background and does not work. Only style.background does..
First problem is a syntax error, you didn't close the DOM ready handler properly.
Second problem is you use # with document.getElementById(), which it does not require.
Demo
$(document).ready( function(){
var element1 = document.getElementById('SelectTable1'); // no #
element1.style.background = element1.options[element1.selectedIndex].value;
}); // <-- close properly
Since you're using jQuery, you might as well make full use of it:
$(document).ready( function(){
var element1 = $('#SelectTable1');
element1.css('background', element1.val());
});
[enter link description here][1]Use jQuery
$(document).ready(function()
{
var selElem = $('#selColor');
var bgColor = selElem.val();
selElem.css("background-color", bgColor);
});
http://jsfiddle.net/HavgB/

Changing selection in a select with the Chosen plugin

I'm trying to change the currently selected option in a select with the Chosen plugin.
The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.
I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:
$('button').click(function() {
$('select').val(2);
$('select').chosen().val(2);
$('select').chosen().select(2);
});
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options):
https://jsfiddle.net/59x3m6op/1/
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

Form change with JavaScript

I have two drop down lists:
<select name="branch">
<option value="b">Blacksburg</option>
<option value="c">Christiansburg</option>
<option value="f">Floyd</option>
<option value="m">Meadowbrook</option>
</select>
but I would like the second list to be different based upon what is selected from the first list. So FREX Blacksburg's might be:
<select name="room">
<option value="Kitchen">Kitchen Side</option>
<option value="Closet">Closet Side</option>
<option value="Full">Full Room</option>
</select
While Christiansburg's is:
<select name="room">
<option value="Window">Window Side</option>
<option value="Door">Door Side</option>
<option value="Full">Full Room</option>
and of course the options are also different for the other branches...
Is it possible to change the second drop down list based on what they select for the first one? I have used JavaScript a teensy bit, but not much so please explain in detail.
Yes, this is called a drilldown.
What you want to do is attach an onChange handler to your first dropdown that will grab new values based on the selected value (of the first dropdown) and populate those values into the second dropdown.
I recommend doing this with jQuery. It will make the experience much more pleasant. That being said:
var optionsMap = {
b: {
Kitchen: "Kitchen Side",
Closet: "Closet Side",
Full: "Full Room"
},
c: {
Window: "Window Side",
Door: "Door Side",
Full: "Full Room"
},
...
};
jQuery("#firstSelect").change(function() {
/* "this" is a reference to firstSelect element. Wrapping jQuery(...)
around it turns it into a jQuery object. Then you get the value
of the selected element with .val() */
var $select = jQuery(this);
var value = $select.val();
/* I'm doing the following to illustrate a point; in some cases
you may have to get it from a database with an AJAX request.
Basically YMMV */
var newOptions = optionsMap[value];
/* remove all the old options */
jQuery("#secondSelect").find("option").remove();
/* Iterate over the hash that you got and create new option
objects that use the key of the hash as the option value
and the value of the hash as the option text */
jQuery.each(newOptions, function(option, value) {
jQuery("#secondSelect").append(
jQuery("<option></option>").attr("value", option)
.text(value)
);
});
});
First, these kind of DOM modifying actions are made much easier with jQuery. It abstracts a lot of browser-specific crap away from you, making it much easier to do your thing. However, since you didn't mention the jQuery, I'll address the JavaScript issues. This is completely possible with JavaScript.
Second, you're going to want to give all of your select elements ids. This will make it much easier for JavaScript to identify them. Ids must be unique. I'm just going to follow the convention of naming the id after the name of the element.
Third, what we do is listen for the JavaScript event onchange on the select element and then do something with it (note the id attributes).
<select id="branch" name="branch" onchange="handleChange();">
<option value="b">Blacksburg</option>
<option value="c">Christiansburg</option>
<option value="f">Floyd</option>
<option value="m">Meadowbrook</option>
</select>
<select id="room" name="room">
</select>
The above code assigns the event listener handleChange to the branch select element. When a change event is fired, handleChange will be called. Now let's define the handleChange function:
<script type="text/javascript">
var handleChange = function() {
// get a handle to the branch select element
var branch = document.getElementById('branch');
// get the index of the selected item
var index = branch.selectedIndex;
// handle displaying the correct second select element
if (index === 0) {
// if the index is 0 (the first option,) call the Blacksburg function
doBlacksburg();
// I'll leave this up to you ;)
} else if (index === 1) {
// more stuff
}
}
</script>
Now we'll define the function that updates the second select list with Blacksburg information:
var doBlacksburg = function() {
var blacksburg = document.getElementById('room');
blacksburg.options[0] = new Option("Kitchen Side", "Kitchen", true, false);
blacksburg.options[1] = new Option("Closet Side", "Closet", false, false);
blacksburg.options[2] = new Option("Full Room", "Full", false, false);
}
That will update the second select list with the Blacksburg options. Reference for the JavaScript Option object.
That code is by no means extensive, but it should be enough to get you started. Like I said earlier, all of the above code can be done in as few as 5 lines of jQuery and it might be worth your time to look into jQuery or a similar library.
Are you familiar with / comfortable using a library like jQuery? I'd approach it with something like this:
var roomOpts = {
b: [
'<option value="Kitchen">Kitchen Side</option>',
'<option value="Closet">Closet Side</option>',
'<option value="Full">Full Room</option>'
]
....
};
$('select[name=branch]').change(function () {
$('select[name=room']).html(roomOpts[$(this).val()].join(''));
});
You can use an onchange event handler on the first list that calls a function to change the other list(s).
Look at this one:
http://www.webdeveloper.com/forum/showthread.php?t=97765

Categories

Resources