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

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

Related

jQuery getting selected option of dynamically rendered dropdown list

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>

Using JS to find select (drop down list) with only one option and then select the one option by default

In my SPA site I dynamically adding several select (dropdown list \ combo-boxes) tags to the page.
What I need to do is to check which one of them have only one option (empty string as option caption doesn't count) and for those select them by default.
I also use Knockout binding and need the selected value to be properly bind to the correlated variable .
For example, if those are the select tags:
<div>
<select for="required" data-bind="options: list1, value: val1, optionsCaption: ''">
<option value=""></option>
<option value="1">One</option>
</select>
</div>
<div>
<select for="required" data-bind="options: list2, value: val2, optionsCaption: ''">
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
The code should automatically pick the only option in the first select.
I tried using this code:
var chooseDefaultValues = function() {
var relevantComboBoxes = $("select[for='requiredComboBox']");
for (var i = 0; i < relevantComboBoxes.length; i++) {
var currentComboBox = relevantComboBoxes[i];
if (currentComboBox.disabled) continue; //Skip disabled combo-boxes
if (currentComboBox.length === 1) { //If there is only one child, select it
currentComboBox.selectedIndex = 0;
}
if (currentComboBox.length === 2) { //If there are twon childern:
if ($(currentComboBox.firsChild).text().trim() === "") { //If the first one is the empty option caption pick the second child
currentComboBox.selectedIndex = 1; //As it is the only choice there is
}
}
}
The problem is that it shows in the select box the right value, but it doesn't populate the binded variable.
I also tried to replace the line:
currentComboBox.selectedIndex = 0
by
currentComboBox[0].click()
But it didn't help...
Your help will be appretiate :)

HTML/Javascript Set up Two Select Options and redirect once first one is selected

<select id="First DropDown" name="" onchange="javascript:location.href = this.value;">
<option value="/url">Option1</option>
<option value="/url">Option2</option>
<option value="/url">Option3</option>
<option value="/url>Option4</option>
<option value="" selected="selected">Option5</option>'
</select>
<select id="Second DropDown" name="" onchange="javascript:location.href = this.value;">
<option value="/url">Option1</option>
<option value="/url">Option2</option>
<option value="/url">Option3</option>
<option value="/url>Option4</option>
<option value="" selected="selected">Option5</option>'
</select>
That's really all I got. Basically what I want is when someone selects an option (such as option 1) on the first dropdown menu, it then pulls up a specific set of options. So for example, if someone selects "Option 1" on the first drop down menu, then on the second drop down menu options such as "#1" "#2" "3" come up, but if someone selections "Option 2" on the first drop down menu, menu options such as "4" "5" "6" come up. I would also like to know how to set up a search button so that when both the drop downs have a specific set of option selected, it then redirects to a specific page I set. Sorry about all of this.. I know Im not very good
You need to create an event handler on the first text box that fills the second text box with options. A good way to do this is to store your options in a 2D array, so when the first select box is selected, your Javascript code can easily loop over and create the new options.
With HTML like this
<!-- In your own code, do not use onsubmit="return false" -->
<form id="searchForm" action="#" onsubmit="return false">
<input type="text" name="search" value="Search a little"/>
<fieldset>
<label>Search parameters</label>
<select id="first" name="first"></select>
<select id="second" name="second">
<option>-----</option>
</select>
</fieldset>
<input type="submit" value="Search" />
</form>
and Javascript like this:
var options = [
["A","B","C"],
["D","E","F"],
["G","H","I"],
["J","K","L"]
],
first = document.getElementById('first'),
second = document.getElementById('second'),
searchForm = document.getElementById('searchForm'),
searchButton = document.querySelector('input[type="submit"]'),
destination,
option;
// Fill the second text box with options from the array.
function fillSecond() {
// Get the list of options
var secondOptions = options[first.value];
// Clear the previous options
second.innerHTML = '';
// Add each option to the select box
for (var i = 0; i < options[first.value].length; i++) {
option = document.createElement('option');
option.value = secondOptions[i];
option.innerHTML = 'Option ' + secondOptions[i];
second.appendChild(option);
}
// Select the first option by default.
second.firstElementChild.setAttribute('selected','selected');
// update the from
updateFormAction();
};
function updateFormAction() {
searchForm.action = destination = '#' + first.value + second.value;
}
// When the second box is updated, update the second select
// and update the form action
first.addEventListener('change', fillSecond);
// Fill the first select box with options
for (var i = 0; i < options.length; i++) {
option = document.createElement('option');
option.value = i;
option.innerHTML = 'Option ' + i;
first.appendChild(option);
}
// By default select the first element.
first.firstElementChild.setAttribute('selected','selected');
// When search is clicked, alert where the form will take them
searchButton.addEventListener('click', function () {
alert('Sending user to location: ' + destination);
return false;
});
// When the second box is updated, update the form action
second.addEventListener('change', function () {
updateFormAction();
});
// On startup, fill the second box.
fillSecond();
You can change where your form goes to based on which options the user selects from the drop down.
See the demo at this jsFiddle to get yourself started
What you are looking for is called "Chained Select Box" - you can change the options values easy with Jquery, but better you take one Plugin which provides this functionality:
For Example:
http://www.appelsiini.net/projects/chained/demo.html
Or here if you are using a Database (MySQL) and PHP to provide the Content of your Select Boxes
http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/

Loop over Dropdownlist

I want to loop over a Dropdownlist and write the value of the selected Item in a label.
I've done it before with a selection of Radio buttons but with the dropdownlist it won't work.
Now, some Code.
Here is the generated HTML Code Values are not interesting.
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
The Code to bind the event to the Dropdownlist.
$(function () {
var dropdown = document.getElementsByName("alternativeNumbers");
$(dropdown ).change(function () {
updateAlternativeDropdown();
});
});
And finally the method which is called by the event. This should fill the labels.
function updateAlternativeDropdown() {
var dropdown = document.getElementsByName("alternativeNumbers");
var lengthDropDown = addAlternativeArticleNumberDropdown.length;
for (var i=0; i < lengthDropDown; i++)
{
//This alert is for the behavior of the output!
alert(addAlternativeArticleNumberDropdown[i].value);
if (addAlternativeArticleNumberDropdown[i].selected) {
var valueOfDropdown = addAlternativeArticleNumberDropdown[i].value;
var splittedValues = valueOfDropdown.split("_");
document.getElementById("label1").innerText = splittedValues[0];
document.getElementById("label2").innerText = splittedValues[1];
}
}
};
I hope this is enough information, now the Problem / Current behavior:
The method updateAlternativeDropdown() is called fine but then the alert inside the loop returns the value of first element, value of the selected element and this 3 times. (I guess because of the 6 elements in this element)
Furthermore because of this my if-statement isn't entered. Currently I#m kind of clueless where this problem comes from.
Thanks in advance.
You don't have to iterate dropdown's options. You can access selected option like this:
dropdown.options[dropdown.selectedIndex].value
Update your updateAlternativeDropdown function:
function updateAlternativeDropdown() {
var dropdown = document.getElementById("alternativeNumbers"),
splittedValues = dropdown.options[dropdown.selectedIndex].value.split('_');
document.getElementById("label1").innerHTML = splittedValues[0];
document.getElementById("label2").innerHTML = splittedValues[1];
}
$('#alternativeNumbers').change(updateAlternativeDropdown);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
label1: <span id="label1">-</span><br />
label2: <span id="label2">-</span><br />
<select id="alternativeNumbers" name="alternativeNumbers">
<option value="1_A">Text</option>
<option value="2_B">Text</option>
<option value="3_C">Text</option>
<option value="4_D">Text</option>
<option value="5_E">Text</option>
<option value="6_F">Text</option>
</select>
working Example

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

Categories