jQuery getting selected option of dynamically rendered dropdown list - javascript

I am working on an MVC + jQuery project, I am creating dropdown list on runtime. After rendering while submitting form through jQuery, I am trying to get selected value. Drop down is rendered and working fine
Also I can check in source code. I am trying to get dropdown list by
$('#Monday_Periods').children('.PeriodRow').each(function () {
var elements = $(this).html();
var found = $('.Subject', elements);
});
I found all objects in variable found, and I can see it in Chrome debug
But after this I am unable to get selected value. As you can see in debug mode that no option is selected. I tried to get by val or text but no luck. Anybody can tell me that how I can get selected value

$(this).html(); is loosing the reference to the DOM (html() returns a String, not a DOM node).
Try to modify in:
var elements = $(this);
var found = $('.Subject', elements);
found.each(function(el){
console.log($(this).val());
}
or use directly (you already have an id on it!):
$('#subject1').val();
EDIT: SNIPPET ADDED
function printResults(){
$('#Monday_Periods').children('.PeriodRow').each(function () {
var elements = $(this);
var found = $('.Subject', elements);
found.each(function(el){
console.log($(this).val());
});
});
}
$('#print-results').click(printResults);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Monday_Periods">
<div class="PeriodRow">
<select class="Subject">
<option value="none">-- Select Subject --</option>
<option value="1">Biology</option>
<option value="2">Physics</option>
</select>
<select class="Subject">
<option value="none">-- Select Subject --</option>
<option value="1">Biology</option>
<option value="2">Physics</option>
</select>
</div>
<button type="button" id="print-results">PRINT RESULTS</button>
</form>

Related

Select a drop-down value using javascript (Bookly WP Plugin)

I'm trying to select a drop-down value using js. In my case, I need to select "DRAW PORTRAIT" drop-down option after the plugin loads.
I tried two methods but I'm not getting anywhere. This is a part of the frontend found in Bookly WordPress plugin. I added an id id="category" to the dropdown so that I can select a value.
HTML:
<div class="bookly-js-chain-item bookly-table bookly-box" style="display: table;">
<div class="bookly-form-group">
<label>Service Type</label>
<div>
<select id="categorydraw" class="bookly-select-mobile bookly-js-select-category">
<option value="">Select category</option>
<option value="6">DRAW PORTRAIT</option>
<option value="7">DRAW DUMMY FIGURE</option>
<option value="8">DESIGN WAX SCULPTURE</option></select>
</div>
</div>
</div>
Method 01
document.getElementById("categorydraw").value = "DRAW PORTRAIT";
Method 02
var objSelect = document.getElementById("categorydraw");
setSelectedValue(objSelect, "DRAW PORTRAIT");
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
Please see the full code where the js doesn't work: https://jsfiddle.net/3z5hcv62/
I would really appreciate if someone can correct my cranky code. Thanks in advance!
One line of jQuery will allow you to select the item necessary:
$('#categorydraw option[value="7"').prop("selected", true);
https://jsfiddle.net/fLc1p5mq/
Edit: In order to activate on a WordPress page load, use:
jQuery( document ).ready(function() {
jQuery('#categorydraw option[value="7"').prop("selected", true);
});
First, i want to make sure. Do you want to select the value of the dropdown or set the value to the dropdown?. Maybe this will help your problem.
HTML
<!-- I set the "categories" id to the dropdown -->
<select class="bookly-select-mobile bookly-js-select-category" id="categories">
<option value="">Select category</option>
<option value="1">Cosmetic Dentistry</option>
<option value="2">Invisalign</option>
<option value="3">Orthodontics</option>
<option value="4">Dentures</option>
</select>
<p>
Selected value: <strong id="selected"></strong>
</p>
JavaScript
var dropdown = document.getElementById('categories');
var datas = [];
var select = 3;
/* Get value with text from dropdown */
for(var i=0;i<dropdown.options.length;i++) {
datas.push({
id: dropdown.options[i].value,
text: dropdown.options[i].text,
});
}
/* For set the value */
dropdown.value = select; // after page loaded,, default value will selected is "Orthodontics"
/* For select current value with the text */
var dataSelected = datas[select];
document.getElementById('selected').innerHTML = "ID: "+dataSelected.id+", TEXT: "+dataSelected.text;
The result will show like this https://jsfiddle.net/65jnzLko/1/
You can improve that code. Like selecting datas by id of the dropdown value.
Or if you just want to set the value for your dropdown, you can do this
// using pure js
document.getElementById('yourdropdown').value = 3 // or other values
// using jquery
$("#yourdropdown").val(5) // 5 can replace with other values

selectmenuchange appending object list only on first event

I have two selectmenus, one of which $('#parent') relates to certain options in the $('#members') menu (related through a data attribute in their HTML). I have a function to limit the choices in 'members' where they relate to the choice selected in the parent menu.
SCRIPT
$("#parent").selectmenu();
$("#members").selectmenu();
var allMembers = $('#members option'); // keep object list of all of the options for the select menu
$("#parent").on("selectmenuchange", function() {
var someMembers = [];
var id = $('#parent option:selected').data('id');
allMembers.each(function() {
if ($(this).data('parent-id') == id) {
someMembers.push($(this))
}
});
$('#members').empty().append(someMembers);
});
At the moment, this works, but only on the first selectmenuchange event - which is odd because using console.log() when the arrays are recreated in the function I can see that the correct have been selected each time, they just don't show in the menu on subsequent changes.
I can't figure out if this is a problem with selectmenuchange or empty().append()
HTML
<select name="members" id="members">
<option data-id="101" data-parent-id="1">Name1</option>
<option data-id="102" data-parent-id="1">Name2</option>
<option data-id="103" data-parent-id="1">Name3</option>
<option data-id="104" data-parent-id="2">Name4</option>
<option data-id="105" data-parent-id="2">Name5</option>
<option data-id="106" data-parent-id="3">Name6</option>
<option data-id="107" data-parent-id="3">Name7</option>
</select>
<select name="parent" id="parent">
<option data-id="1">Parent1</option>
<option data-id="2">Parent2</option>
<option data-id="3">Parent3</option>
</select>
Well the options were changing but it wasn't reflecting in the selectmenu created by plugin. So one of the way is you destroy it and re-initialize the selectmenu as below:
$('#members').html(someMembers).selectmenu('destroy').selectmenu();
DEMO
Instead of selectmenu('destroy') and re-initializing the select menu you can also use selectmenu('refresh'). Refreshing sounds nicer than destroying it each time.
I have updated the fiddle of Guruprasad Rao with the refresh:
fiddle

2 related Multiselect form elements

I want to create 2 multiselect side by side. The first one is populated, but the 2nd is empty. The 2nd gets populated only when I select an option from the 1st one and depends on the value of the 1st one.
I'm thinking the only way to do this is with javascript. Can someone confirm this, and do you know of existing examples.
I'm using jquery, but prefer to not use plugins.
I'm also thinking to use Zend so if an existing component exists that would be great.
Here's a demo
You can easily do this with some DOM manipulation.
HTML
<select id="from" multiple>
<option value="-">King</option>
<option value="9">Queen</option>
<option value="5">Rook</option>
<option value="3">Knight</option>
<option value="3">Bishop</option>
<option value="1">pawn</option>
</select>
<select id="to" multiple>
</select>
javascript
var from = document.getElementById("from");
var to = document.getElementById("to");
from.onchange = function(){
//remove this to allow for duplicates
to.innerHTML = "";
var fromOptions = from.getElementsByTagName("option");
for(var i in fromOptions) {
if (fromOptions[i].selected == true) {
//remove "cloneNode(true)" to simultaniusly
//remove the node from the from list.
to.appendChild(fromOptions[i].cloneNode(true));
}
}
}

how to get the selected index of a drop down

I have a normal dropdown which I want to get the currently selected index and put that in a variable. Jquery or javascript. Jquery perfered.
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
$("select[name='CCards'] option:selected") should do the trick
See jQuery documentation for more detail: http://api.jquery.com/selected-selector/
UPDATE:
if you need the index of the selected option, you need to use the .index() jquery method:
$("select[name='CCards'] option:selected").index()
This will get the index of the selected option on change:
$('select').change(function(){
console.log($('option:selected',this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
If you are actually looking for the index number (and not the value) of the selected option then it would be
document.forms[0].elements["CCards"].selectedIndex
/* You may need to change document.forms[0] to reference the correct form */
or using jQuery
$('select[name="CCards"]')[0].selectedIndex
the actual index is available as a property of the select element.
var sel = document.getElementById('CCards');
alert(sel.selectedIndex);
you can use the index to get to the selection option, where you can pull the text and value.
var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);
<select name="CCards" id="ccards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
<script type="text/javascript">
/** Jquery **/
var selectedValue = $('#ccards').val();
//** Regular Javascript **/
var selectedValue2 = document.getElementById('ccards').value;
</script>
You can also use :checked for <select> elements
e.g.,
document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')
You don't even have to get the index and then reference the element by its sibling index.

Jquery/Javascript link $(this) to an element in a different div?

I've got a multiple select that I want to use to pick which elements show up in an HTML template window. So I have several options that I want to iterate over, and based on whether it's been selected, make the preview elements visible or hidden.
I'm going for something like this:
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
$(??????).css($css);
});
As you can see, I'm just iterating over each option (I'm pretty sure that syntax works) in my area_select menu, but I don't know how to make the css get applied to the corresponding piece.... how can I reference my preview elements via my options?
An easier way to go is to call .val() on the multiple select. That returns an array of selected values that you can iterate over.
var array = $('#area_select').val()
$.each(array, function(i,val) {
// your code
});
So as far as showing the elements is concerned, it would depend on what type of data is stored in the value of the select options.
For an ID, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('#' + value).css('visibility','visible');
});
Or if they are class names, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('.' + value).css('visibility','visible');
});
Give each of the options a name corresponding to the ID of the correct piece.
e.g.
<select>
<option value="whatever">Whatever</option>
<option value="whatever2">Whatever 2</option>
</select>
Then each of you elements will be contained in a a div like this:
<div id="whatever-preview">
<!-- Whatever -->
</div>
Then your Javascript
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
var div_name = "#" + $(this).attr('value') + "-preview";
$(div_name).css($css);
});
Give each option an id referencing the id of the corresponding element in the preview window.
for instance:
<option id="option-1">This turns on the first option element in the preview window</option>
<option id="option-2">This turns on the first option element in the preview window</option>
and give the preview window elements similar-ending ids:
<div id='window-1'>corresponding window preview element</div>
Then in the javascript:
$("#window-" + $(this).attr('id').split('-')[1]).css($css);
First, give the elements to hide or show the same class but id's matching the options values:
<div class="something" id="val_1">content1</div>
<div class="something" id="val_2">content2</div>
<div class="something" id="val_3">content3</div>
<div class="something" id="val_4">content4</div>
<select id="area_select">
<option value="val_1">val 1</option>
<option value="val_2">val 1</option>
<option value="val_3">val 1</option>
<option value="val_4">val 1</option>
</select>
then, when the select choosen option changes hide all the stuff and show the selected
$('#area_select').change( function(){
var val = $(this).val();
$('.something').hide();
$('#'+val).show();
return false;
});

Categories