I have the following select list from which the user can select multiple values.
<select name="valumethod1[]" id="valumethod1[]" onBlur="validatevalumethod()" size="6">
<option value ="t1">test1</option>
<option value ="t2">test2</option>
<option value ="t3">test3</option>
<option value ="t4">test4</option>
</select>
I want to fetch the selected values in JavaScript, but I don't know how to do this. Please help me.
Try something like this :
var ob = document.getElementById('valumethod1[]');
var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[ i ].selected) {
selected.push(ob.options[ i ].value);
}
}
The array selected is then an array of selected options. Working example here
Note: you need to add multiple="multiple" to your select list as an attribute
Related
How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
HI I have a issue with filtering one drop down list with another drop down list,
in my search.cshtml file I have added
#{
List<FormCategory> formCategories = ViewBag.formCategories;
List<Form> forms = ViewBag.forms;
List<UsersVM> users = ViewBag.Users;
List<FormSearchResultsVM> results = ViewBag.Results;
}
<select id="selFormCategories" class="sc-select sc-input" onchange="onFormCategoriesChanged(this)">
<option id="0"></option>
#foreach (var formCat in formCategories)
{
<option value="#formCat.ID">#formCat.Name</option>
}
</select>
<select id="selForms" class="sc-select sc-input" onchange="onFormsChanged(this)">
<option id="0"></option>
#foreach (var form in forms)
{
<option value="#form.ID">#form.Name</option>
}
</select>
I need to filter selForms dropdown when selFormCategories onchnage event...
function onFormCategoriesChanged(sel) {
selectedFormCategory = $(sel).find(':selected').attr('value');
}
Thanks
Here's one way I could think of. First, we should store the option elements to a jquery object array then filter that array for display whenever a select is changed.
Data attributes (data-property, data-name, etc) is used for filtering.
In my example below, whenever the vehicle select is changed, it will clear and refill the brands select with corresponding brands from that vehicle type.
$(document).ready(function(){
var vehicleList = [];
var brandsList = [];
// store brands options to variable on document ready
$("#brands option").each(function(){
brandsList.push($(this));
});
// clear brands select to hide option fields
$("#brands").html("");
// vehicle select on change, refill brands with matching data-vehicle value
$("#vehicle").change(function(){
var brandsSelect = $("#brands");
var vehicleValue = $(this).val();
brandsSelect.html("");
brandsSelect.show();
$(brandsList).each(function(){
if($(this).data("vehicle") == vehicleValue){
$(brandsSelect).append($(this));
}
});
});
});
<html>
<body>
<h5>Select a Vehicle Type</h5>
<select id="vehicle">
<option>Motorcycle</option>
<option>Car</option>
</select>
<h5>Choose Brand</h5>
<select id="brands" hidden>
<option data-vehicle="Motorcycle">Yamaha</option>
<option data-vehicle="Motorcycle">Kawasaki</option>
<option data-vehicle="Car">Mercedes Benz</option>
<option data-vehicle="Car">BMW</option>
<option data-vehicle="Car">Audi</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
I'm trying to select multiple values on page load, but it only selects the last value on the array. Take a look at the code
jQuery("#language").chosen();
var str = '12,24,36';
var languageArray = str.split(',');
for (var i = 0; i < languageArray.length; i++) {
jQuery("#language").val(languageArray[i]);
jQuery("#language").trigger("liszt:updated");
}
I get only 36 selected on page load, is there anything wrong with the js ?
Here is the HTML for the select
<select name="language[]" id="language" data-placeholder="Choose Language..." multiple="multiple">
I appreciate your help.
Thanks
You can select multiple options in a multi-value select box by passing an array to the val() method.
Example
Markup
<select name="language" id="language" data-placeholder="Choose Language..." multiple="multiple">
<option value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
</select>
JavaScript
var str = 'en,de';
jQuery("#language").val(str.split(','));
And here's a jsFiddle for funsies.
you could set the selected property of matched option element. hope it would help.
var values = ['1', '2', '4'];
$('#languages').find('option').filter(function (idx, option) {
if($.inArray(option.value, values) !== -1) {
return option;
}
}).prop('selected', 'true');
I found a nice demo on an old JSFIddle for Moving items from one multi-select box to another with JavaScript
You can see the demo here: http://jsfiddle.net/jasondavis/e6Y7J/25/
The problem is, the visual part works correctly but when I put this on a server with PHP, it only POST the last item added to the new select box. So instead of POSTING an array of items, it will only POST 1 item regardless of how many items exist in the selection box.
Can anyone help me?
The JavaScript/jQuery
$(document).ready(function() {
$('select').change(function() {
var $this = $(this);
$this.siblings('select').append($this.find('option:selected')); // append selected option to sibling
});
});
I believe I've hit this issue before. For the PHP $_POST array to populate this correctly you need to add a name field with [] at the end of the name. PHP will then interpret the result as an array of all the values and not just the last selected one.
Example:
<select name="demo_multi[]" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
When you recall the item in the $_POST array leave off the square brackets.
$values = $_POST['demo_multi'];
Change the multiselect name to an array
<select name="post_status[]" multiple id="select2" class="whatever" style="height: 500px; width: 222px;"></select>
I think you also have to select all items in the
This is pre jquery but it works.
`<form onsubmit="selectAll();"> ....</form>
function selectAll()
{
for(j=0; j<document.formdata.elements.length; j++)
{
// if a multiple select box then select all items in the box so they are sent with the form
var currObj = document.formdata.elements[j];
if (currObj.tagName == 'SELECT' && currObj.multiple == true)
for (i=0; i<currObj.length; i++)
currObj.options[i].selected = true;
}
}`
This will then be loaded into the array named in the
I want to loop over a Dropdownlist and write the value of the selected Item in a label.
I've done it before with a selection of Radio buttons but with the dropdownlist it won't work.
Now, some Code.
Here is the generated HTML Code Values are not interesting.
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
The Code to bind the event to the Dropdownlist.
$(function () {
var dropdown = document.getElementsByName("alternativeNumbers");
$(dropdown ).change(function () {
updateAlternativeDropdown();
});
});
And finally the method which is called by the event. This should fill the labels.
function updateAlternativeDropdown() {
var dropdown = document.getElementsByName("alternativeNumbers");
var lengthDropDown = addAlternativeArticleNumberDropdown.length;
for (var i=0; i < lengthDropDown; i++)
{
//This alert is for the behavior of the output!
alert(addAlternativeArticleNumberDropdown[i].value);
if (addAlternativeArticleNumberDropdown[i].selected) {
var valueOfDropdown = addAlternativeArticleNumberDropdown[i].value;
var splittedValues = valueOfDropdown.split("_");
document.getElementById("label1").innerText = splittedValues[0];
document.getElementById("label2").innerText = splittedValues[1];
}
}
};
I hope this is enough information, now the Problem / Current behavior:
The method updateAlternativeDropdown() is called fine but then the alert inside the loop returns the value of first element, value of the selected element and this 3 times. (I guess because of the 6 elements in this element)
Furthermore because of this my if-statement isn't entered. Currently I#m kind of clueless where this problem comes from.
Thanks in advance.
You don't have to iterate dropdown's options. You can access selected option like this:
dropdown.options[dropdown.selectedIndex].value
Update your updateAlternativeDropdown function:
function updateAlternativeDropdown() {
var dropdown = document.getElementById("alternativeNumbers"),
splittedValues = dropdown.options[dropdown.selectedIndex].value.split('_');
document.getElementById("label1").innerHTML = splittedValues[0];
document.getElementById("label2").innerHTML = splittedValues[1];
}
$('#alternativeNumbers').change(updateAlternativeDropdown);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
label1: <span id="label1">-</span><br />
label2: <span id="label2">-</span><br />
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
working Example