Auto check saved data in jQuery Multiselect - javascript

I am using this jQuery Multiselect plugin https://github.com/nobleclem/jQuery-MultiSelect to convert all my select boxes that have the multiple attribute enabled in to drop down boxes with check boxes.
I load the options in the select box from a database.
Upon the form submission I can save the multiple selected data, but when I retreive data back from the database I cannot display the saved data back in the multi select box by checking matching check boxes.
The multiselect plugin has a loadOptions method, but using that method I have to generate all option data with option name, option value and the check status, and set it to the multiselect plugin. How can I easily do this if I have an array of data which must be checked/selected in the multiple select plugin?
HTML
<select name="abc" id="abc" multiple title="Test Number?">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
<option value="4">Test 4</option>
<option value="5">Test 5</option>
</select>
JS (I have more than one multiple select boxes and initiate them as shown below)
$.each($("select[multiple]"), function (key, selectbox) {
$("#" + selectbox.id).multiselect({
texts: {placeholder: $("#" + selectbox.id).attr("title")}
});
});
My saved data array is [1,3,4]
I need to set these saved data to the select box and check the check boxes without going through the loadOptions method.

You could use jQuery .filter() function on your select options to preselect those wanted before initializing the multiselect plugin.
Here,
$('option',this).filter((_,e) => saved_data.includes(+e.value)).prop('selected',true);
Preselects every option, before the .multiselect() call.
let saved_data = [1, 3, 4];
$('select[multiple]').each(function() {
$('option', this).filter((_, e) => saved_data.includes(+e.value)).prop('selected', true);
$(this).multiselect({
texts: {
placeholder: $(this).attr("title")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://springstubbe.us/projects/demos/jquery-multiselect/scripts/index.js?1523890673"></script>
<link rel="stylesheet" href="https://springstubbe.us/projects/demos/jquery-multiselect/styles/index.css?1518818712">
<select name="abc" id="abc" multiple title="Test Number?">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
<option value="4">Test 4</option>
<option value="5">Test 5</option>
</select>

Related

Disabling search functionality for drop-down menu default selection

I am trying to use the code below so website users have the option to select which database they'd like to search from a list of drop-down menu options. The code works just fine, but users are able to submit a search when the drop-down menu is set to the default selection which results in an error. I only want users to be able to submit a search if they select Option 1, Option 2, etc. from the drop-down menu.
Is there a way to accomplish this? Thanks in advance!
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
window.location.href = submitto;
return false;
}
</script>
<form name="searchform" onSubmit="return dosearch();">
Search:
<select name="sengines">
<option value="" disabled selected>Select an option by category</option>
<option value="">Option 1</option>
<option value="">Option 2</option>
<option value="">Option 3</option>
<option value="">Option 4</option>
</select>
For:
<input type="text" name="searchterms">
<input type="submit" name="SearchSubmit" value="Search">
</form>
Step 1
First, you should assign different values to each dropdown options. Right now, all options have the same value "", so you can not differentiate among selected options.
<option value="option_0" disabled selected>Select an option by category</option>
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
<option value="option_4">Option 4</option>
Step 2
In dosearch() function, check if the selected option is different than option_0. If it is, then perform the search. If it is not, alert the user that he should select the option from dropdown first.
function dosearch() {
const sf = document.searchform;
const selected_option = sf.sengines.options[sf.sengines.selectedIndex].value;
if (selected_option === "option_0") {
alert('Choose an option from dropdown first.')
} else {
const submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
window.location.href = submitto;
return false;
}
}
Working example

Retrieving selected values in Materialize CSS multiple select using JavaScript

I'm using multiple select of Materialize CSS in a form to select multiple values. The UI is working fine, but I couldn't find a way to retrieve all the selected values. I used an onChange event handler to retrieve the values. However instead of an array of selected values it is returning only the first selected value in the list.
Can anybody explain how to do it using JavaScript for a simple multiple select like the one below? (Not by using jQuery)
<select id='mySelect' multiple>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
You can get the selected in this way:
html:
<select multiple id="option-select">
<option value="" disabled selected>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<label>Materialize Multiple Select</label>
js
document.addEventListener("DOMContentLoaded", function () {
const selects = document.querySelector("select");
const instances = M.FormSelect.init(selects, {});
const selectOption = document.querySelector("#option-select");
selectOption.addEventListener("change", function () {
const instance = M.FormSelect.getInstance(selectOption);
const selectedValues = instance.getSelectedValues();
console.log(selectedValues);
});
});

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

JQuery how to difference between a select option with an option selected attribute and a select without a selected value

I'm populating multiple select with a webservice.
This web service is returning the selected value.
Well, at the moment to render them, I have 2 different select
<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>
<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>
Well, the first select hasn't any selected attribute and the second one has it.
When I execute:
$("select1").find("option:selected").val(); //Returns 1
$("select2").find("option:selected").val(); //Returns A
How I can identify when the select has an option really selected?
Instead of using :selected which looks for the selected state, you can look for [selected], which will check for the selected attribute.
var $selectedOption = $("#select1 option[selected]");
if ($selectedOption.length) {
//option selected
console.log(selectedOption.val() + " selected.");
} else {
//no option selected
console.log("Nothing selected.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>
<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>
You can use the has() jQuery method to find the select that has an option with the selected attribute.
$("select").has("option[selected]")
$("#select1").has("option[selected]").val() // undefined
$("#select2").has("option[selected]").val() // "A"

Multi select onchange event jquery

I'm creating a form. I have two fields, 1. default value field and 2. preview field. Both are multiselect fields. The user will add the options to the multiselect manually. Whenever the user chooses an option in the default value, the same value should be shown as selected in the preview field. When the user removes one option, the same option should be unselected. This is how I've written the onchange event for this multiselect:
$("#MultiSelect_DefaultValues").change(function() {
alert($(this).val());
$("#MultiSelect_Preview").val($(this).val());
});
I get the correct value in the alert. But, in the preview field, there is no reaction. All the options available in the default value field are available in the preview field too. But, the options selected in the default value field is not selected in the preview field. What's wrong with this? What should I change, so that the changes in the default field reflects in the preview field too?
You said you are using select2 so execute like this:
$("#MultiSelect_DefaultValues").change(function () {
alert($(this).val());
var prevSelect = $("#MultiSelect_Preview").select2();
prevSelect.val($(this).val()).trigger('change');
});
The values on the option tags need to match for this, if I'm understanding correctly what you're trying to achieve that is.
e.g.
$("#MultiSelect_DefaultValues").change(function() {
console.log($(this).val());
$("#MultiSelect_Preview").val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="MultiSelect_DefaultValues" multiple>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
<select id="MultiSelect_Preview" multiple>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
You can provide multiple replacements by sending an int array to the select method.
$('#cars').val([1,3]);
//or $('#cars').selectpicker('val', [1,2,3]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="cars" id="cars" multiple>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
you can use this code
<script>
$("#MultiSelect_DefaultValues").change(function () {
$('select[id="MultiSelect_Preview"]').find('option[value=' + $(this).val() + ']').attr("selected", true);
});
</script>

Categories

Resources