How onInitialized works in Bootstrap-multiselect - javascript

Very simple example : https://jsfiddle.net/x6z6w0n8/8/
How can I set selected values on Initialization step without creating duplicate?
Sample from off site works well. https://jsbin.com/yupinelefa/edit?html,js,console
As I noticed, in off-example they don't initialize select, they just use event onInitialized. But when I initialize (set options) to select in onInitialized event then nothing is changed, I also have 2 selects.
In general - I have bootstrap-multiselect on page. OnInitialization I want to set selected values in it.
I have next code as example :
<select id="example-onInitialized" multiple="multiple" class="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>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
$('.multiselect').multiselect({
onInitialized: function(select, container) {
$(select).multiselect('select', 2); // I want to select item with value '2'
}
});
But this script creates one additional select. So as result I have one select with selected value '2' and one empty select.
For me it seems like every call of .multiselect() will create new select. Is it right? Thanks.

Updated fiddle.
That happen because select is an option that should be called always on .multiselect() (that initialize the plugin), so in your case your plugin will be initilized for the second time when you will use it.
onInitialized() is a function which is triggered when the multiselect is finished initializing.
The select option is made to select also the given values after initialization of the plugin, so you could just use it like :
$('.multiple').multiselect('select', 2);
Hope this helps.

Related

Get Select value from dropdown in Vanilla JS

I'm learning JS and can't seem to be able to make this one work:
HTML code:
<select name="colors">
<option value="">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
JS:
var select = document.getElementsByName("colors")[0];
console.log(select.value); // ==> it should output selected color but is not.
Since you didn't post the full code, I'd suppose that you're running your JS code before the select element is being loaded (if your script is in the headsection for example).
Anyway, I'll provide some work arounds for this purpose and at the end of the answer I'll show you how to get the selected value whenever the selected item from the list has changed.
encapsulate your code in load event of the window :
<!-- just to simulate when your JS is placed in the head section -->
<script>
// attach a "load" event listener to the "window"
window.addEventListener('load', () => {
// select the "select" element
var select = document.getElementsByName("colors")[0];
// log its initial selected value. Here as we didn't explicitly assign the "selected" attribute to an "option", the first "option" value will be printed.
console.log(select.value);
});
</script>
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
place your code just before the body closing tag hence no need to listen for the load event
var select = document.getElementsByName("colors")[0];
// log its initial selected value. Here as we didn't explicitly assign the "selected" attribute to an "option", the first "option" value will be printed.
console.log(select.value);
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
Anyway I think that your final goal is to get the selected value whenever the selected item is being changed :
// select the "select" element
var select = document.getElementsByName("colors")[0];
// attach a "change" event listener to the "select" element
select.addEventListener('change', () => {
// log the selected value whenever it changes
console.log(select.value);
});
<p>choose an option from the list first</p>
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
BTW, I don't recommend selecting elements based on their name attributes, using classes or IDs (if the element is unique in the page or has unique functionnality) would be a better choice.
Also, using getElementsBy* (Elements not just Elment) methods is not recommended in most situations, querySelector or getElementById(for unique elments) is better.
you should create a id of that value then use const example = document.getElementById("id")
the var should be changed to const;
and the name is the string not the value
and always use id;
Try this..
function myFunction(){
var e = document.getElementById("MySelectOption");
var strUser = e.options[e.selectedIndex].value;
console.log(strUser);
}
<select id="MySelectOption" name="colors" onchange="myFunction()">
<option value="">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>

jQuery change selection and trigger change callback

I have a dialog with multiple tabs, the first tab has a list ("SELECT") when a selection is made from the list the number of tabs may change as a result of the callback attached to the list.
In my source I the list callback is attached with:
$("#listID").bind("change", function() {
//Do something
});
In code I want to change the list selection and trigger calling of the change callback. I've tried:
$("#listID").val(3); //3 is one of the valid option values
This didn't result in the change callback being called so I added:
$("#listID").change();
After the setting of the value, this doesn't work either, if I look at the list the high light has not moved.
I've searched online and what I've done should work but it doesn't. What haven't I done?
Here is the HTML:
<select id="listID" size="11">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
</select>
Should work fine doing $("#listID").val(3).change()
Note that bind() is deprecated and you should use on()
$("#listID").on("change", function() {
console.log(`Changed value to ${this.value}`)
});
$("#listID").val(3).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="listID">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
If it's not working there is something missing in question as to why
$("#listID").val(2).trigger('change'); //to trigger the change event with value 2

Set value of select to first child of that select

My code dynamically generates the options for the select element but the exact value of the options are unknown at the moment of creation.
So was playing around to set the selected value of my select element to the first child but was unable to do so in 1 line.
I was able to it in 2 lines but I was wondering if something shorter is possible.
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>
$("#selectElement").val($(this).children(":first").val());
It's worth noting that most browsers will automatically select that first option for you.
But if you need to do it for some reason: You're not far off at all, but this doesn't come from the first part of that line. Instead:
var select = $("#selectElement");
select.val(select.children(":first").val());
Or I find this simpler:
var select = $("#selectElement");
select.val(select[0].options[0].value);
Or using the selected property of the option instead:
$("#selectElement")[0].options[0].selected = true;
// or with more jQuery
$("#selectElement > option:first").prop("selected", true);
One method is using .eq() selector.It reduce the set of matched elements to the one at the specified index.
Please try this:
$(selectElement).val($('#selectElement option:eq(0)').val());
See reference here
If you want the shortest method please try this:
$("#selectElement").prop("selectedIndex", 0);
If you have only one element, you should find it (with # id selector), and the also use his selector to find the children.
Otherwise you could use (in case you also have more elements) use a class, and iterate it (the second script in the snippet)
edit
Without js, you could simply use the selected property of option to set as default when page loads.
$("#selectElement").val($("#selectElement").children("option:first").val());
$(".selectElement").each(function() {
$(this).val($(this).children("option:first").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>
<select class="selectElement">
<option value="21">Optie 21</option>
<option value="22">Optie 22</option>
</select>
<select>
<option selected value="321">Optie 321</option>
<option value="322">Optie 322</option>
</select>
You can achieve this by using :first
$(document).ready(function () {
$("#selectElement").val($("#selectElement option:first").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>
No need to use JavaScript to set selected the first element of the options because html will do it for you:
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>

Swap options between select Harvest Chosen select boxes

I am trying to swap all the options between two Harvest Chosen select boxes. The scenario is I want to record details of a phone call. The call can either be inbound or outbound. If the call is outbound the I populate a select box (caller) with a list of possible values of those users that can make outbound calls and a second box (callee) with a list of possible values of those users they can make calls to. If the user updates the call type to be inbound then I want to swap the select boxes around so that the callee's are in the caller box and vice versa.
I very nearly have this working except each time I change the call type it keeps appending the values onto the end of the select options in each respective caller/callee select rather than completely clearing them and replacing all values.
Would appreciate some help as to why this is happening.
See http://jsfiddle.net/RyHFK
HTML
<label for="call_type">Call Type:</label>
<select name="call_type" id="call_type" class="chosen">
<option value="OUTGOING">Outgoing</option>
<option value="INCOMING">Incoming</option>
</select>
<label for="caller">Caller:</label>
<select name="caller" id="caller" class="caller chosen">
<option value="Caller 1">Caller 1</option>
<option value="Caller 2">Caller 2</option>
<option value="Caller 3">Caller 3</option>
<option value="OTHER">Other</option>
</select>
<label for="caller">Callee:</label>
<select name="callee" id="callee" class="callee chosen">
<option value="Callee 1">Callee 1</option>
<option value="Callee 2">Callee 2</option>
<option value="Callee 3">Callee 3</option>
<option value="OTHER">Other</option>
</select>
The way it's written, you are appending to the same arrays every time there is a change. Move your calleeOptions and callerOptions variables inside your change handler:
// on call type change
$('#call_type').change(function(){
var callerOptions = [];
var calleeOptions = [];
Here's a jsFiddle.

Trigger event in HTML <select> box when the same entry is selected again

In a HTML form, I use a drop-down list like this:
<select onchange="send()">
<option value="a">Option A</option>
<option value="b">Option B</option>
<option value="c">Option C</option>
</select>
When the user changes the selected entry, send() is called, which basically uses jQuery.ajax(...) to send the new value to the server. This works fine.
When the transmission fails for some reason, the user is informed about the error. Most users will then select the same entry again to retry. Now the problem is that this will not trigger the onchange event again because the value hasn't changed. What would be the best way to deal with this?
Try this
HTML
<select id="chg">
<option>a</option>
<option selected>b</option>
<option>c</option>
</select>
Script
$("select#chg").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
alert($(this).val());
}
$(this).data("isopen", !open);
});
DEMO
You can create a empty value option
<option value=''></option>
Which is by default selected as first load, When error occurs for any selection you can select 'empty' option from select box. So for next time user will need to selection option and your 'send()' function will call.
// Selection empty option by code
$('#selectBoxId').val('');
maybe you can use onclick event

Categories