change selected value in msdropdown - javascript

I'm trying to use the msDropdown JavaScript plugin (https://github.com/marghoobsuleman/ms-Dropdown) to create html tags that include images.
It seems to work good except for if I try to change the selected value using JavaScript.
Like in this jsFiddle: https://jsfiddle.net/cmu845eh/7/
I'm trying to make it so that if you call the setValue() function, it will change the selected value to a certain index.
I've tried multiple different solutions online but none work, solutions such as this:
var oHandler = $("#main").msDropDown().data("dd");
oHandler.set("length", 0);
always result in an error, and more basic jquery approaches dont work either.
Can someone help me change the value of my select tag to a certain index using javascript?

Using msdropdown
Let me give you a full code on how to populate select dropdown from server-side using another select dropdown.
1st Select Dropdown
<select name="" id="from" class="selectFlags" style="width:100%;">
<option value="2" title="https://fxtop.com/ico/aon.gif">GBP</option>
<option value="3" title="https://fxtop.com/ico/aon.gif">GBP</option>
</select>
2nd Select Dropdown
<select name="" id="selectFlagTo" class="selectFlagTo form-control" style="width:100%;height:52px;">
</select>
JScript
<script language="javascript">
$(document).ready(function(e) {
try {
$(".selectFlags").msDropDown({mainCSS:'dd'});
} catch(e) {
alert(e.message);
}
$(".dd").css({ 'width' : '100%' });
});
$(document).on("click",".dd .ddChild",function(e){
let $from=$("#from option:selected").val();
let $to=$("#selectFlagTo");
$to=$to.empty();
$(".dd").css({ 'width' : '100%' });
$(".dd2").css({ 'width' : '100%' });
$.ajax({
url: "http://odin.test/load_countries",
type: "POST",
data: {from:$from},
success: function(response) {
$.each(response, function(key, entry) {
$to.append("<option title='https://fxtop.com/ico/aon.gif' value='"+entry.id+"'>"+entry.name+"</option>" );
});
var oDropdown = $(".selectFlagTo").msDropDown({mainCSS:'dd2'});
$(".dd3").css({ 'width' : '100%' });
}
});
});
</script>
Enjoy coding!!!

Solved it here by fixing how I was initializing the msdropdown element after the html was created.
https://jsfiddle.net/uvbjhy31/

Related

Javascript - Changing tag-it source with select option

I have a select with two options. When changing the select ... I want to filter/autocomplete a different database. Without http://aehlke.github.io/tag-it/ it's working fine and the autocomplete is changing the source ... but not with it. It stays at source_01.php although I see in the console the change of Test Source 01 to Test Source 02. What might causes this?
HTML:
<select id="search_database" class="form-control">
<option value="1" selected="">Source 01</option>
<option value="2">Source 02</option>
</select>
Javascript:
$('#search_database').on('change', function () {
if ( $('#search_database').val() == 1 ) {
console.log('Test Source 01');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_01.php",
...
});
},
...
})
});
} else if ( $('#search_database').val() == 2 ) {
console.log('Test Source 02');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_02.php",
..
});
},
...
})
});
}
});
Your problem is the value not getting picked up by the script when you change the options if you want to pick the value of the changed option you've to do something similar to the below code.
HTML:
<label for="clientSelect" style="margin-left:14px;">Client:</label>
<select name="clientSelect" id="clientSelect" onChange="clientId(this.id)" style="width:180px;"></select>
<input type="text" id="clintId" size="1" hidden>
JavaScript:
function getClient(cId){
//Get the selected ID using this.is in client side HTML then breaks it up using this to get the ID only
var select = document.getElementById("catSelect"),
optionId = select.options[select.selectedIndex],
catId = optionId.id;
I use the hidden text filed to send the selected ID to my PHP then to the database.

Default selected value of dropdown menu using Jquery

I have 3 nested dropdown menus which are dynamically populated from a mysql database and I use Jquery. I want to set a selected value, depending on the entry in my database.
For example:
I have a table that contains many devices. Each device has its storage place (room, shelve, box). Notice: different rooms contain different shelves which contain different boxes, thats why I use a nested dropdown menu.
Next to each device is a button "change".
What I want is that the current storage place of the device is already selected in my dropdown menu.
This is part of my JS functions (got them from another site, I'm very new to JS):
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
mySelect.append($('<option></option>').val(optionValue).html(optionText));
});
}
This is my html code:
Raum:</br></br><select name="manufacturer" id="manufacturer" >
<option value="">Auswahl:</option></select> </br></br>
Regal:</br></br> <select name="printertype" id="printertype" disabled="disabled" >
<option value="">Auswahl:</option></select> </br></br>
Kiste:</br></br><select name="printermodel" id="printermodel" disabled="disabled" >
<option value="">Auswahl:</option></select></br></br>
<div id="loading" style="display: none;"></div>
<div id="output" ></div>
Part of my ajax code:
jQuery().ready(function($){
$('#loading')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
// Ajax Called When Page is Load/Ready (Load Manufacturer)
jQuery.ajax({
url: 'man_list.php',
global: false,
type: "POST",
dataType: "xml",
async: false,
success: populateComp
});
Sorry for that much code, I hope anyone has a good solution for me, which I (the JS noob) can understand :)
You can check your server's response while populating dropdown options
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
var $opt = $('<option> </option>').val(optionValue).html(optionText);
if(/* compare current data with your device here */) $opt.attr("selected", "selected");
mySelect.append($opt);
});
}

On change on multiple select jquery with Ajax and PHP

I have a multiple selection in my HTML page which is generated in an AJAX response: the format is like this:
<div>
<select class='myselect' idselect=1>
<option value='private'>Private</option>
<option value='public'>Public</option>
</select><button idfeed=1 class='change'>Change status</button></div>
<div>
<select class='myselect' idselect=2>
<option value='private'>Private</option>
<option value='public'>Public</option>
</select><button idfeed=2 class='change'>Change status</button>
</div>......
In my jquery/Ajax I have something like that (the code which generating the HTML above):
<script>
$( document ).ready(function() {
var id= $('#idUser').val();
//console.log('findAll');
$.ajax({
type: 'GET',
url: 'http://localhost/ws/api/getUserFeeds/'+id,
dataType: "json", // data type of response
success:function(data){
//alert(data[0].URL);
$.each(data, function (i) {
var toappend="<div><select class='myselect' idselect="+data[i].id+"><option value='private'>Private</option><option value='public'>Public</option></select><button idfeed="+data[i].id+" class='change'>Change status</button></div>";
console.log(toappend);
$("#foo").append(toappend+"<div id=rss"+i+ ">"+i+"</div>");
$('#rss'+i).FeedEk({
FeedUrl: data[i].URL,
MaxCount: 1,
DateFormat: 'MM/DD/YYYY HH:mm'
});
});
}
});
});
</script>
And when I want to retrive the value of selected by user which must either private or public I use this jquery code to select,but the problem is that it select only private all time.
<script type="text/javascript">
$(document).on('change','.myselect',function(){
var selectvar = $('.myselect').val();
console.log(selectvar);
});
</script>
As you can see I display in my console the value of the selected one,and using the JQuery change event.
I try by many ways to try to make it work but it always return private(My select is composed of two choice:private and public)
Thanks for your help!!!
You made a small mistake at the end. You should retrieve your select input with $(this), not $('.myselect') :
$(document).on('change','.myselect',function(){
var selectvar = $(this).val();
console.log(selectvar);
});
Try this
DEMO
$(document).on('change','.myselect',function(){
var selectvar = $(this).val();
console.log(selectvar);
});
$(this) = > the element changed
$(".myselect") => it can be any of the two select elements in your
given html

Jquery to get the value of Dropdown list

I'm using following html for dropdownlist,
<select id="dd">
<option>Select ReportType</option>
<option value="1">Blocked Details</option>
<option value="2">Supervisor Input</option>
</select>
Following code for a button,
<input type="button" name="Excel" value="ExportToExcel" onclick="javascript:DownloadExcel($('#dropdown').val());" />
Following is the Jquery function,
function DownloadExcel(value)
{
debugger;
if(value=="Blocked Details"){
value="1";
}
else if(value=="Supervisor Input"){
value="2";
}
$.ajax({
url:"#Url.Action("TravelReadyAdminDownload", "TravelReady")",
datatype:"html",
type:"post",
data:{Id:value},
error:function(){},
success:function(data){
window.location.href=data.url;}
});
}
is it possible to get the dropdown values("1/2" instead of "Blocked Details/Supervisor Input").What is the javascript i need to use to get the value in that function?
Selected dropdown value can be fetched like
$('#dd').val();
or
$('#dd option:selected').val();
EDIT: Actually you're doing it right, following are your mistakes
1) wrong selector
$('#dropdown').val()// WRONG selector
it has to be
onclick="javascript:DownloadExcel($('#ddd').val());" //Correct
2) value parameter will hold only value (1 or 2) not text (Blocked Details or Supervisor Input)
Also following is the right way
if(value=="1"){
//do something
}
else if(value=="2"){
//do something
}
Can you try the following
$('#dropdown :selected').val()

Get attributes values from select2 selected option

I'm using the Select2 plugin from http://ivaynberg.github.io/select2/select2-latest.html what works fine but i'm having a problem to get the values from the options attributes.
I've got a select menu like this:
<select name="invoice_line[0][vat]" class="vat">
<option value="20440" data-value="21.00" data-name="20440" selected="selected">21%</option>
<option value="20441" data-value="6.00" data-name="20441">6%</option>
<option value="20442" data-value="0.00" data-name="20442">0%</option>
</select>
How can I get the values of the attributes 'data-value', 'data-name' and 'value' of the selected option?
obj = $("#dropdown").select2("data")
in obj variable i will get all the data of the selected node.
This was answered in another SO question
There is no direct method with select2, you can use a combinaison of select2 data and jQuery :
$("#example").select2().find(":selected").data("id");
First you get the select2 data then you find your selected option with jQuery and finally the data-attribute.
We can use a combination of select2 data and jQuery :
$("#example").select2('data').element[0].attributes['data-name'].value
Following worked for me. Idea is to use "change" function as follows
<select class="drop-down">
<option value="0">A</option>
<option value="1">B</option>
</select>
$('.drop-down').select2().on("change", function(e) {
var obj = $(".drop-down").select2("data");
console.log("change val=" + obj[0].id); // 0 or 1 on change
});
var return_option = $("#your-select-input-id").select2().find(":selected")[0];
above given statement will return select option and then put that return result as given below:
var name_of_attribute = $( return_option ).attr('name-of-attribute');
This will return the attribute value.
No idea about the pluggin, and without checking if the code works i imagine it would be something like this:
$('.vat li').each(function(){
var me = $(this),
mevalue = me.attr('value'),
datavalue = me.data('value'),
dataname = me.data('name');
//do what you want with the data?
});
Put select2 into tagging mode , it will help you.
Or
Try below similar code, it may work for you ...
$("$id").select2("val", option);
$("$id").attr("data-name");
I know that this is an old post, but I was struggling with this same problem. This is the solution that me and my good friend Thys finally got to work:
<script type="text/javascript">
$(document).ready(function ()
{
$("#e1").select2();
$("#e1").change(function () {
var theID = $("#e1").val();
$('#staffNr').val(theID);
$('#staffNr').val();
//var theID = $(test).select2('data').id;
var theSelection = $(test).select2('data').text;
$('#selectedID').text(theID);
$('#selectedText').text(theSelection);
});
});
#Html.Hidden("fieldName","staffNr");
This worked in my MVC 4 view with the last line in my html form where it is correctly added to the model. Don't forget to up-vote if you use my answer please :) I haven't got much of a reputation...
I hope you solved the issue. Here we dont use select2(), if we use select2() it will not work all other functions like formatNoMatches, on-change....
$("#example").find(":selected").data("id");
el = document.getElementsByName("invoice_line[0][vat]")
el.options[[el.selectedIndex]].attributes["data-id"].value
The params.data.element object of the selected item holds the data you're looking for.
Where .foo is the select element I'm calling, and the data attribute within the options I want to access is data-bar="some value" The following works for me:
var $fooSelect = $('.foo');
$fooSelect.on(function (e) {
console.log($(e.params.data.element).data('bar'));
});
You can access to attributes looking in DOM structure:
<select id="select_name">
<option value="20440" data-value="21.00">21%</option>
<option value="20441" data-value="6.00">6%</option>
<option value="20442" data-value="0.00">0%</option>
</select>
$('#select_name option').each(function (index) {
console.log($(this).attr("data-value"));
});
set an id for your select element and this would work
$('select#your-id').find('option[value="'+$('#your-id').val()+'"]').attr('data-attribute');
You haveto do it with on("change"... because of this is a dynamicly generated option list.
$('.select_class').on("change",function(){
var selected_value= $('.hakemler').val();
var wanted= $('.select_class').find('option[value="'+selected_value+'"]').attr('data-foo');
alert(selected_value+" "+wanted);
});

Categories

Resources