jQuery select (Dropdown) populate from array - javascript

I currently have this here working..
$(document).ready(function() {
$("#image").change(function() {
$("#imagePreview").empty();
$("#imagePreview").append("<img src=\"" + $("#image").val() + "\" />");
});
});
<select name="image" id="image" class="inputbox" size="1">
<option value="imageall.jpg" selected> - All - </option>
<option value="image1.jpg">image1.jpg</option>
<option value="image2.jpg">image2.jpg</option>
<option value="image3.jpg">image3.jpg</option>
</select>
<div id="imagePreview">
</div>
from this previous question:
Previous Question
I was wondering how can I populate the from a jQuery Array instead?
How could I do that? So basically the values and name from an array
This is the example in Fiddle i will be using Example Working

function populateSelect(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('please select', '');
$.each(items, function () {
el.options[el.options.length] = new Option(this.name, this.value);
});
}
As seen here:
Using javascript and jquery, to populate related select boxes with array structure

You may want to retrieve names and values from JSON array this way.
var image_maps = {image1: "image1.jpg", image2: "image2.jpg"};
$.each(image_maps , function(name, value) {
alert("name: " + name + " value: " + value);
});

Related

kendo multiselect set with text?

How to set values in kendo multiselect using the text value we have i mean not with value.
multi = $("#multiselect").kendoMultiSelect({
dataSource: data,
dataTextField: "exampletext",
dataValueField: "examplevalue",
tagTemplate: "<span class='' entity_id =" + 'examplevalue' + " path ="+'examplevalue' + " >" + 'examplevalue' + "</span>",
}).data("kendoMultiSelect");
To set the value in kendo multi select is working fine with below code :
multi.value(["value1","value2"]);
I need to set with text value.
There is no direct property to set the value based on text.
It can be achieved by this way:
HTML:
<select id="multiselect" multiple="multiple">
<option value="1">Item1</option>
<option value="2">Item2</option>
</select>
Javascript:
<script>
$("#multiselect").kendoMultiSelect();
var multiselect = $("#multiselect").data("kendoMultiSelect");
var d = multiselect.dataSource.data();
var val = [];
var selectedItems = ["Item1", "Item2"];
for(i=0;i<selectedItems.length;i++)
{
var t = d.find(x => x.text === selectedItems[i]);
if(t!=undefined)
{
val.push(t.value);
}
}
// set the value of the multiselect.
multiselect.value(val);
</script>

create a select dropdown option with values and text according to the specified data attribute

so below is my snippet. What I want is to create a select dropdown option base from the data attribute (data-select-text and data-select-values) of the currently clicked button, so below is a working snippet except for getting the data-select-values which is the problem because i dont know how to loop it along with the data-select-text so that the result of each select option will have values and text base from the split values of the data-select-text and data-select-values attribute, any ideas, help, suggestions, recommendations?
NOTE: currently, I could only able to use the attribute data-select-text as a select options values and text.
$(document).ready(function(){
$(document).on("click", "button", function(){
if($(this).attr("data-input-type").toLowerCase() === "select"){
var classList = $(this).attr('data-select-text').split(/\s+/);
var field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + item.replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
You could create an array for the values, the same as so did for the text.
Make sure that the order in both data-select-text and data-select-values is the same. Then you can use the index in your $.each loop:
$(document).ready(function(){
$(document).on("click", "button", function(){
var elem = $(this);
if( elem.attr("data-input-type").toLowerCase() === "select" ){
var classList = elem.data('select-text').split(/\s+/),
valueList = elem.data('select-values').split(/\s+/),
field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + valueList[index].replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
The result will be:
<select>
<option value="1">select 1</option>
<option value="2">select 2</option>
<option value="3">select 3</option>
</select>
Here is one way to do it, if I understand correctly. This code does not take into account different text or value lengths. It expects that the text length of options created is always equal to the values length being used.
$(document).ready(function () {
$(document).on("click", "button", function () {
if ($(this).attr("data-input-type").toLowerCase() === "select") {
var classList = $(this).attr('data-select-text').split(/\s+/);
var valueList = $(this).attr('data-select-values').split(' ');
var field = '<select>';
$.each(classList, function (index, item) {
field += '<option value="' + valueList[index] + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
Fiddle: http://jsfiddle.net/32qt0vn8/

Get selected value of option with multiple dropdown menus using javascript

I have multiple features that have multiple options that need to be updated when an option is selected. I also need to pass a third piece of data through the attribute element.
.getElementById() works for a single dropdown menu, but how do I get it to work when there are multiple menus on the page?
I have tried var e = document.getElementsByClassName("testClass"); which did not work.
I also tried to create optionsText & optionsValue in the same way that optionsFtr is created with var optionsValue = $('option:selected', this).value; and that didn't work either.
http://jsfiddle.net/8awqLek4/4/
HTML Code
<ul>
<li>
<div class="ftrsTitle">BODY</div>
<select class="testClass" id="testId">
<option>Select</option>
<option ftr="bod" value="blk">Black</option>
<option ftr="bod" value="grn">Kelly Green</option>
<option ftr="bod" value="red">Red</option>
<option ftr="bod" value="roy">Royal</option>
</select>
</li>
<li>
<div class="ftrsTitle">TRIM</div>
<select class="testClass">
<option>Select</option>
<option ftr="trm" value="blk">Black</option>
<option ftr="trm" value="grn">Kelly Green</option>
<option ftr="trm" value="red">Red</option>
<option ftr="trm" value="roy">Royal</option>
</select>
</li>
</ul>
<div id="vars"></div>
Javascript Code
$(document).ready(function () {
$("select").on('change', function () {
var e = document.getElementById("testId");
var optionsText = e.options[e.selectedIndex].text;
var optionsValue = e.options[e.selectedIndex].value;
var optionsFtr = $('option:selected', this).attr('ftr');
$("#vars").html("<p>optionsText: " + optionsText + "</p><p>optionsValue: " + optionsValue + "</p><p>optionsFtr: " + optionsFtr + "</p>");
});
});
To read select value you can simply use $(this).val(). To get selected option label you should use text() method.
Fixed code looks like this:
$("select").on('change', function () {
var optionsText = $('option:selected', this).text();
var optionsValue = $(this).val();
var optionsFtr = $('option:selected', this).attr('ftr');
$("#vars").html("<p>optionsText: " + optionsText + "</p><p>optionsValue: " + optionsValue + "</p><p>optionsFtr: " + optionsFtr + "</p>");
});
Demo: http://jsfiddle.net/8awqLek4/3/
This should do it:
$(document).ready(function(){
$("select").on('change', function(){
var e = $(this).find("option:selected");
$("#vars").html("<p>optionsText: " + e.text() + "</p><p>optionsValue: " + $(this).val() + "</p><p>optionsFtr: " + e.attr("ftr") + "</p>");
});
});
use the this keyword. Than you can access the select targeted, and with find in combination with the :selected selector you can find the option element currently selected.
http://jsfiddle.net/8awqLek4/5/

Appending a div (multiple times) in Jquery without cloning

I am still trying to work this out. Currently this is the way it looks, It works on JSFiddle but on my for it only clones once and the clone has data in it that when changed, changes the 1st item
I am trying to streamline my very large form to speed up the processes. I have a section that repeats multiple time that I want to reduce to having coded once with a button to add more if needed. The section cannot be cloned as each is separate and specific. Also note that they each need a unique identifier. As I have it not they ar "transectA", "transectB", etc. Below is a small snippet to give you an idea wof what I am working with. Each select actually has 12 options and there are 14 transects.
<div class="transect">
<select name="transectA" id="transectA">
<option value="">Transect A </option>
<option value = "RIGHT/SED-CORE">RIGHT/CORE</option>
<option value = "RIGHT/HOOP">RIGHT/HOOP</option>
<option value = "RIGHT/CHLPHL-1">RIGHT/TEMPLATE</option>
<option value = "RIGHT/NONE">RIGHT/NONE</option>
<option value = "CENTER/SED-CORE">CENTER/CORE</option>
<option value = "CENTER/HOOP">CENTER/HOOP</option>
<option value = "CENTER/CHLPHL-1">CENTER/TEMPLATE</option>
<option value = "CENTER/NONE">CENTER/NONE</option>
<option value = "LEFT/SED-CORE">LEFT/CORE</option>
<option value = "LEFT/HOOP">LEFT/HOOP</option>
<option value = "LEFT/CHLPHL-1">LEFT/TEMPLATE</option>
<option value = "LEFT/NONE">LEFT/NONE</option>
</select> </div>
I have attempted a couple of solutions (hide/show) & clone but neither give me a satisfactory result. All of the attempts I have tried with append seem to produce basically what the show/hide does.
<script>
$(document).ready(function() {
var $transect = $('.transect');
$transect.on('change', 'select', function() {
var $this = $(this),
$parent = $this.parent(),
$transects = $('.transect');
if($transects.length < 14 && !$parent.next('.transect').length) {
var ltr = String.fromCharCode(65 + $transects.length),
label = 'transect' + ltr;
$transect
.clone(true)
.find('select')
.attr('name', 'transect' + ltr)
.attr('id', 'transect' + ltr)
.find('option:eq(0)')
.text('Transect ' + ltr.toUpperCase())
.end()
.end()
.insertAfter($parent);
}
});
})
</script>
As always, your help will be greatly appreciated
Can anyone advise me why all of these solutions work in JSFiddle but not on my form. Even the script above works on the fiddle but only clones once on the form
you could do something like this:
var counter = 0
$('.add-new-button').click(function(){
$('#transectA').append('<option id="input ' + counter +'" value = "RIGHT/SED-CORE">RIGHT/CORE</option>');
counter++;
});
This will add a new option to #transectA. You can use this method to add form fields elsewhere as well. You can use the counter to make sure it has a unique ID or name or whatever. Good luck
You should be able to combine clone and some DOM manipulation to get the desired affect: http://jsfiddle.net/fjJfk/2/
But you'll likely need to make this example match your own markup/situation.
var $transect = $('._25');
$transect.on('change', 'select', function() {
var $this = $(this),
$parent = $this.parent(),
$transects = $('._25');
if($transects.length < 14 && !$parent.next('._25').length) {
var ltr = String.fromCharCode(65 + $transects.length);
$transect
.clone(true)
.find('select')
.attr('name', 'transect' + ltr)
.attr('id', 'transect' + ltr)
.find('option:eq(0)')
.text('Transect ' + ltr)
.end()
.end()
.insertAfter($parent);
}
});
You can use following;
HTML:
<div id="tempSelect" style="display:none">
<select name="transect" data-mini="true" id="transect">
<option value="">Transect_ </option>
<option value = "RIGHT/SED-CORE">RIGHT/CORE</option>
<option value = "RIGHT/HOOP">RIGHT/HOOP</option>
<option value = "RIGHT/CHLPHL-1">RIGHT/TEMPLATE</option>
<option value = "RIGHT/NONE">RIGHT/NONE</option>
</select>
</div
<fieldset>
<div class="_100">
</div>
</fieldset>
<input type="button" name="newSelect" id="newSelect" value="New"/>
JS:
$("#newSelect").on("click", function() {
var lastSelect = $("._100 select").last().attr("name");
if (lastSelect != undefined) {
var temp = lastSelect.split("_");
var id = parseInt(temp[1]) + 1;
} else {
var id = 0;
}
$("#tempSelect select").attr("name", "transect_" + id);
$("#tempSelect select").attr("id", "transect_" + id);
$("#tempSelect select option:first").text("Transect_" + id);
$("._100").append($("#tempSelect").html());
});
Here is working demo: jsfiddle

Getting a SelectList obejct from a ListBox and placing into an HTML Selection List

Say I have a ListBox populated with a name value pair SelectList(myUsers, "Key", "Value"):
#Html.ListBox("ListReviewers", (SelectList)ViewBag.ListOFReviewers, new { style = "width:120px;" })
I want to double click an option in this ListBox, and place it in a SelectionList like below:
<div class="selectedEmployees">
<select class="selectionList" multiple="multiple" name="AssignedReviewer" style="width:120px;">
<!--x.UserID, x.FirstName + " " + x.LastName) -->
<option value=""></option>
</select>
</div>
Once this collection is placed in the above, I want to store all the values in another SelectionList Collection for later use.
Here is the start of my jQuery code:
<script type="text/javascript">
$('#ListReviewers').dblclick(function (i, selected) {
//double click on this value of listbox of type SelectList(myUsers, "Key", "Value")
//store this value and text
var value = $(this).val;
//var empName = $(this).data[0];
var empName = $(selected).text();
alert(empName);
//append an option element <option value=""></option>
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
I can get the value of the dblclicked collection object, but not the text of the collection object. Is there a better way to do this?
Try attaching your event to the option within the select itself. You can then use this to access it's properties.
$('#ListReviewers option').dblclick(function () {
var value = $(this).val();
var empName = $(this).text();
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
Alternatively, you can use clone() and append() to move the option from one select to the other. This will save you having to worry about duplicate options being appended.
$('#ListReviewers option').dblclick(function () {
var $newOptions = $(this).clone(false);
$(this).remove();
$('.selectionList').append($newOption);
});

Categories

Resources