How to get the value of dropdown and display in label - javascript

I have a dropdown where I am filling the content with dynamic data and in the model I am appending my data to the dropdown
$("#dpp").append($("<option disabled></option>").val(0).html('Select Locations'));
$("#dpp").append($("<option selected='selected'></option>").val(1111).html('All'));
for (var i = 0; i < Location.length; i++) {
$("#dpp").append($("<option></option>").val(data[i].sno).html(data[i].name));
}
I am unable to get the value and text of the selected option by using a change handler.
I tried:
$('#dpp').change(function () {
var thisvalue = $(this + "option:selected").text();
alert(thisvalue);
});
and by default on page load All option selected in the dropdown.
How can I get that value or text and show it on the label?

For change event and document ready:
$(document).ready(function() {
getSelectData($('#dpp'));
});
$('#dpp').on('change', function() {
getSelectData($(this));
});
function getSelectData(el) {
var $option = el.find('option:selected');
var text = $option.text();
var val = $option.val();
alert('option text: ' + text + '; option value ' + val)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="name" id="dpp">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

Use the below code for both purposes (on page load as well as on change event)
$(document).ready(function() {
var dppText= $("#dpp option:selected").text(); // to get text on page load
//to get text on change of drop-down
$(document).on('change','#dpp',function(){
var thisvalue = $(this + "option:selected").text();
alert(thisvalue);
});
});

You can use this:
$(document).on('change','#dpp',function(){
var thisvalue = $(this + "option:selected").text();
alert(thisvalue);
});
This will add change listener to the document level so you will be able to detect the change on dpp.

This will do it:
$("#dpp option:selected").val();

Related

HTML select not refreshing after being populated via JQuery

I've been using JQuery to populate a drop down list on the click of a HTML select element. The options get created however on the first click the options get shown in a very small box with a scroll. see below
incorrect
If I then close and reopen the dropdown it appears correctly. as below.
correct
It feels like the dropdown list is appearing before jquery has rendered the new options elements. I've tried to find away to re-render it but with no luck.
This feels like it should be such an easy fix but I'm new to scripting and struggling.
HTML
<select class="custom-select" id="templateGroupName" name="templateGroupName">
<option selected>Please Select a group</option>
</select>
JS - Wrapped in document.ready
$('#templateGroupName').click(function () {
$.ajax({
type: "GET",
url: '/Layout/GetGroups',
success: function (data) {
helpers.buildDropdown(
data,
$('#templateGroupName'),
'Select an option'
);
}
});
});
var helpers =
{
buildDropdown: function (result, dropdown, emptyMessage) {
// Remove current options
dropdown.html('');
// Add the empty option with the empty message
dropdown.append('<option value="">' + emptyMessage + '</option>');
// Check result isnt empty
if (result != '') {
// Loop through each of the results and append the option to the dropdown
$.each(result, function (k, v) {
dropdown.append('<option value="' + v.Id + '">' + v.Name + '</option>');
});
}
}
}
First, you need a <select> as the parent, not an empty element,
dropdown = $('#templateGroupName');
then insert it as a document element, not a string:
var opt = document.createElement('option');
opt.value = v.Id;
opt.innerHTML = v.Name;
dropdown.appendChild(opt);
The browser gets confused when you inject options while the <select> is open. To be fair, your users would probably be confused too.
If you're waiting for something to load, tell them to wait.
If something isn't usable, disable it.
Putting these two together: the first time a user hovers over the <select>, disable it and set the cursor to a loading wheel. Wait until your data loads, then insert the options, re-enable it and switch the cursor back.
var helpers = {
buildDropdown: function(result, dropdown, emptyMessage) {
dropdown.html('');
dropdown.append(`<option value="">${emptyMessage}</option>`);
if (!!result) {
$.each(result, function(k, v) {
dropdown.append(`
<option value="${v.Id}">
${v.Name}
</option>
`);
});
}
}
}
const $DROPDOWN = $('#templateGroupName');
// using jQuery#one to only fire the click event once
$DROPDOWN.one('mouseenter', _ => {
// disable dropdown while loading options
$DROPDOWN.attr('disabled', true)
console.log('loading options...');
// replace contents with your GET request
setTimeout(function() {
helpers.buildDropdown(
Array.from({
length: 30
}, (_, i) => ({
Id: i,
Name: i
})),
$DROPDOWN,
'Select an option'
);
// un-disable after options are loaded and inserted
$DROPDOWN.attr('disabled', false)
}, 1000);
})
/* Show "loading" wheel while loading */
select.custom-select[disabled] {
cursor: wait;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="custom-select" id="templateGroupName" name="templateGroupName">
<option selected>Please Select a group</option>
</select>

How to select first option in a select box after appending options by jQuery

I have a select box in a modal where I am appending options using jQuery. I want the first option to be selected after appending all item. I have tried some but no luck. Here are my attempts below.
My select box in modal:
<select id="modal_cmbSection" name="modal_cmbSection" class="form-control required">
</select>
My jQuery code where appending and trying to set selected first option:
var sectionOption = "";
var $sectionSelect = $('#modal_cmbSection');
$sectionSelect.empty();
$(".section-block").each(function() {
var eachSectionName = $(this).find(".section-section-name").val();
sectionOption = "<option>" + eachSectionName + "</option>";
$sectionSelect.append(sectionOption);
});
$sectionSelect.find('option:eq(0)').prop('selected', true);
Simply do this,
var sectionOption = "";
var $sectionSelect = $('#modal_cmbSection');
$sectionSelect.empty();
$(".section-block").each(function() {
var eachSectionName = $(this).find(".section-section-name").val();
sectionOption = "<option>" + eachSectionName + "</option>";
$sectionSelect.append(sectionOption);
});
//set selected as true for first option
$("#modal_cmbSection option:first-child").attr("selected", true);
Can you try:
$sectionSelect.find( 'option:first' ).prop( 'selected', true );

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);
});

Three level connected boxes

Is there a way add another dropdown form to this script?
http://javascript.internet.com/navigation/connected-comboxes.html
Or do you happen to have another script that does the same job? I need three level connected dropdown boxes. Each one should be filtered according to previous selection and should be empty before that selection is made...
Thanks in advance...
i was bored... try this. requires jquery
html:
<form>
<select id="s1">
<option>One</option>
<option value="two">Two</option>
<option>Three</option>
</select>
<select id="s2"></select>
<select id="s3"></select>
</form>
js:
// chain select boxes select1 and select2
//
// select1 should have options set already choices is an object
// literal with the level2 options for each value in select1.
//
// options can be either scalars or arrays of length 2,
// in which case val[0] is the value and val[1] is the label text
//
//
var chain = function(select1, select2, choices) {
select1.change( function() {
select2.find('option').remove();
var options = ['<option>---</option>'];
var value = $(this).val();
if( value in choices ) {
var subchoices = choices[value]
for(var i = 0; i < subchoices.length; i++) {
if( subchoices[i].constructor == Array) {
options.push('<option value="'
+ subchoices[i][0]
+ '">'
+ subchoices[i][1]
+ '</option>');
}
else {
options.push('<option>'
+ subchoices[i]
+ '</option>');
}
}
}
select2.append($(options.join('')));
} );
select1.change();
}
you can then define sub-lists
var sub1 = { One: ["One1", "One2", "One3"],
two: [["two1", "Two1"], "Two2"]
};
var sub2 = {two1: [4,5,6,[7, 8]]};
and activate like so:
$( function() {
chain( $('#s1'), $('#s2'), sub1);
chain( $('#s2'), $('#s3'), sub2);
});

Categories

Resources