Trying to select a value from a drop-down - javascript

One Form on the page I am accessing. This form has a dropdown with 3 options. I need to select the third option. Accessing the webpage from a C# program with cefsharp library (embedded web browser).
I can change the displayed text using
document.forms[0].getElementsByClassName('css-0 Select__single-value')[0].innerText="Keep in-play";
but this has not been registered. Have also tried to trigger input and change events but it is still not recognising my selection.
Any suggestions?
Here is the original DOM for the form:
<div class="bet-widget-optional-params">
<div class="bet-params">
<div class="param-wrapper"><span class="param-label"><a class="link" href="https://help.smarkets.com/hc/en-gb/articles/115003946591" target="_blank">Time In Force</a></span>
<div class="param-select">
<div class="css-0 Select custom-select-box Select menu-on-click">
<div class="css-0 Select__control">
<div class="css-0 Select__value-container Select__value-container--has-value">
<div class="css-0 Select__single-value">Default</div><input id="react-select-bet-param-selector-input" readonly="" tabindex="0" class="css-14uuagi" value=""></div>
<div class="css-0 Select__indicators"><span class="css-0 Select__indicator-separator"></span><span aria-hidden="true" class="Select__arrow-zone"><span class="Select__arrow"></span></span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

In JavaScript you can set the selectedIndex property.
elem.selectedIndex = 2;
Setting -1 will remove any selection, and any positive integer will select that item in the list (0-indexed)... so if you want the 3rd item, just set it to 2.
HTMLSelectElement.selectedIndex docs
The property works as a getter too, so if you want to know which element is selected, you can request it like:
var currentSelectedIndex = elem.selectedIndex;
Full interactive example below:
var selectElem = document.getElementById('select');
var pElem = document.getElementById('p');
var buttonElem = document.getElementById('button');
selectElem.addEventListener('change', function() {
var index = selectElem.selectedIndex;
pElem.innerHTML = 'selectedIndex: ' + index;
});
buttonElem.addEventListener('click', function(){
selectElem.selectedIndex = 2;
});
<p id="p">selectedIndex: 0</p>
<select id="select">
<option selected>Option A</option>
<option>Option B</option>
<option>Option C</option>
<option>Option D</option>
<option>Option E</option>
</select>
<input type="button" id="button" value="Set it to C (2)"/>

Related

Setting dropdown values in Javascript

I have a dropdown with following HTML.
<select name="custom_123" id="custom_123_123" class="custom form-control form-control-full form-select searchable abcd-done" style="display: none;">
<option value="" selected="selected">None</option>
<option value="1">Alaska</option>
<option value="2">Newyork</option>
</select>
<div id="custom_123_123_abcd" class="abcd-container abcd-container-single abcd-container-
active" style="width: 100%"><a href="javascript:void(0)" class="abcd-single"
tabindex="-1"><span>Alaska</span></a>
</div>
I want to be able to select Newyork in the dropdown. For that, I am during the following.
var dropdown_id = document.querySelector('[id^="custom_123"]').id;
var dropdown_abcd = dropdown_id + 'abcd';
document.getElementById(dropdown_abcd).getElementsByClassName("abcd-single")[0].innerHTML = "Alaska";
But the same doesn't get applied. Can anyone help?
Here is an example based on your code:
const select = document.querySelector('[id^="custom_123"]');
select.value = 'Alaska';
Update on comment
If there are listeners on the select, here is an example on how to fire a change event.
const select = document.querySelector('[id^="custom_123"]');
select.value = 'Alaska';
select.dispatchEvent(new CustomEvent('change'));

Bootstrap Select Menu - Add New Option

I have a simple Bootstrap form with a select input:
<div class="form-group">
<label for="category" class="control-label col-sm-3">Category</label>
<div class="input-group col-xs-8">
<select class="form-control" name="category" id="category">
<option value="Fruit">Fruit</option>
<option value="Vegetables">Vegetables</option>
</select>
</div>
</div>
The users now have a requirement to be able to add a new option dynamically to the select menu rather than be restricted to the items on the select menu.
I'm not sure if it's possible to modify a select menu and how to make it consistent with the rest of the Bootstrap framework?
To add an option dynamically, there should be a UI button giving you that choice. To get user input, we can use the window.prompt method.
We then create an option element, set its value attribute and set its name. Then just append these elements and nodes to the DOM with appendChild
Try playing around with this. I added some items like Steak, potatoes and beer.
var addOption = document.getElementById("add-option");
var selectField = document.getElementById("category");
addOption.addEventListener("click", function() {
var item = prompt("What would you like");
var option = document.createElement("option");
option.setAttribute("value", item);
var optionName = document.createTextNode(item);
option.appendChild(optionName);
selectField.appendChild(option);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group">
<label for="category" class="control-label col-sm-3">Category</label>
<div class="input-group col-xs-8">
<select class="form-control" name="category" id="category">
<option value="Fruit">Fruit</option>
<option value="Vegetables">Vegetables</option>
</select>
</div>
</div>
<button id="add-option" class="btn btn-primary">Add a new option</button>
You mean something like this?
some select
<select id="region" class="selectpicker">
<option>region 1</option>
<option>region 2</option>
<option>region 3</option>
</select>
jquery js
$('.selectpicker').selectpicker();
$("#region").on('change', function () {
$(this)
.append('<option>region4</option><option>region5</option>')
.selectpicker('refresh');
});

How to get option value of only the selected checkboxes?

I want to get option value of only selected checkbox, but I am getting value from all the checkboxes.
My HTML code:
<div class= "outer">
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">BBQ Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane"> Alfredo Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
</div>
<input type="submit" value="Submit">
My JavaScript code:
function myAction(){
var vals = [];
var machine = document.getElementsByName('machine');
var m2 = document.getElementById('m2');
for(var i=0, n= machine.length; i<n; i++){
if(machine[i].checked){
vals.push(m2.value);
}
}
}
IDs must be unique.
Instead, you could use querySelectorAll() on the existing weight classes to grab only the select elements that follow a checked input (using the general sibling selector):
document.querySelectorAll('input:checked ~ .weight')
The select element values will be the same as their selected options' values.
Snippet
document.querySelector('input[type=submit]').addEventListener('click', myAction);
function myAction() {
var vals = [], //no need for new Array()
weights= document.querySelectorAll('input:checked ~ .weight');
for(var i = 0 ; i < weights.length ; i++) {
vals.push(weights[i].value);
}
console.log(vals);
}
<div class="outer">
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">I have a plane
<br>
<select class="weight" name="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">I have 2 planes
<br>
<select class="weight" name="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
</div>
<input type="submit" value="Submit">
You have m2 repeated twice in your code. HTML spec specifies undefined behavior when id is repeated (m2). Also your select box isn't a multi-select. You should just be able to get the value from the select box directly if that is the case.
You can use querySelector also on nested nodes,
so you could filter the div.inner blocks which have the input checked and then get the values from there:
function myAction() {
//var vals = new Array();
var inner = [].slice.call(document.querySelectorAll('.inner'));
var checked = inner.filter(function(x) {
var chk = x.querySelector('input');
if (chk.checked) return x;
})
var vals = checked.map(function(x){
var i = x.querySelector('select').value;
return i
});
}
BTW as Rick said your markup contain some errors so I would suggest to pass it through a validator_
for calling your function on click event of the input submit:
document.querySelector('input[type=submit').addEventListener('click', myAction)

Add .attr to button not working when called

Not sure if I formatted the question right. Have manually added the "data-next" and it is changing at the appropriate time, but still not changing. Have narrowed it down to the "showNext" function.
My objective is to iterate through the questions about the car the based on the number of cars the user enters. I was thinking a loop at first, but this seemed to be a cleaner way to do it. I'm new so I could be way off.
My problem is that while it does iterate through the correct number of times, and chrome shows that it is choosing that button as the "this" variable as I want it to, for some reason it is not adding the attribute. That line of code fires, I get no errors, but nothing happens.
I have tried using the exact id of the button, defining "this" as a variable (ie: var el = id of button) and a few other things I can't remember right now. Nothing has worked. Also I have used the same type of command in other areas and it worked just fine.
The rest of the code works fine and it does cycle through the correct number of times, but it will not add the attr. Any help would be greatly appreciated. If I have left anything out, please let me know. Thanks!
Here is the JS:
$(document).ready(function () {
// hide all 'hideFirst' elements, except the first one:
$('.hideFirst:not(:first)').hide();
// Method used to show/hide elements :
function showNext(el) {
// check if element has a 'data-next' attribute:
if (el.data('next')) {
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// show 'Back' button:
$('#backButton').show();
// show the element which id has been stored in 'data-next' attribute:
$(el.data('next')).show();
// push the parent element ('.hideFirst') into path array:
path.push(el.closest('.hideFirst'));
}
}
//Logs the number of cars in the household
$("#carAmount").click(function () {
numberOfCars = parseInt(document.getElementById("vehicleAmount").value);
showNext($(this));
});
//allow user to chose the type of car they drive
$("#carType").change(function () {
carChoice = $("#carType").val();
$("#carType").attr("data-next", "#" + carChoice);
showNext($(this));
});
//Decides whether the user has more cars to ask about
$(".carBtn").click(function () {
carCount++;
//asks about other cars
if (carCount < numberOfCars) {
$(this).attr('data-next', '#vehicleType');
$('#carType').prop('selectedIndex', 0);
}
//moves on to the next category
else {
$(this).attr('data-next', '#transportation');
}
showNext($(this));
});
});
And here is the HTML:
<div>
<form>
<div class="hideFirst" id="vehicleCount">
<label for="vehicleAmount">How many vehicles are there in your household?</label>
<input type="text" id="vehicleAmount" />
<button type="button" id="carAmount" data-next="#vehicleType" class="my-btn btnFoot"><i class="icon-footprint-right-d"></i></button>
</div>
<div class="hideFirst" id="vehicleType">
<label for="carType">What kind of car do you drive?</label>
<select id="carType">
<option disabled selected>--Choose One--</option>
<option value="gas">Gasoline</option>
<option value="diesel">Diesel</option>
<option value="cng">Natural gas</option>
<option value="hybrid">Hybrid</option>
<option value="elec">Electric</option>
<option value="hydrogen">Fuel Cell/Hydrogen</option>
</select>
</div>
<div class="hideFirst" id="gas">
<label for="fuelType">What type of fuel do you normally use??</label>
<select id="gasType">
<option disabled selected>--Choose One--</option>
<option value="e10">e10 (regular unleaded)</option>
<option value="e85">e85</option>
</select>
</div>
<div class="hideFirst" id="diesel">
<label for="carType">What type of diesel fuel do you normally use?</label>
<select id="dieselType" name="heatSource">
<option disabled selected>--Choose One--</option>
<option value="num5">Regular Diesel</option>
<option value="b10">B10 Biodiesel</option>
<option value="b100">B100 Biodiesel</option>
</select>
</div>
<div class="hideFirst" id="cng">
<label for="carCng">How much natural gas do you put in your car every month?</label>
<input type="text" id="carCng" />
<button type="button" id="propaneBill" class="carBtn btnFoot"><i class="icon-footprint-right-d"></i></button>
</div>
<div class="hideFirst" id="hybrid">
<label for="carType">What kind of car do you drive?</label>
<select id="carType" name="heatSource">
<option disabled selected>--Choose One--</option>
<option value="gas">Gasoline</option>
<option value="diesel">Diesel</option>
<option value="cng">Natural gas</option>
<option value="hybrid">Hybrid</option>
<option value="elec">Electric</option>
<option value="hydrogen">Fuel Cell/Hydrogen</option>
</select>
</div>
<div class="hideFirst" id="elec">
<label for="carElec">How many miles do you drive every month?</label>
<input type="text" id="carElec" />
<button type="button" id="elecMiles" class="carBtn btnFoot"><i class="icon-footprint-right-d"></i></button>
</div>
<div class="hideFirst" id="hydrogen">
<h2>Good for you, you produce no negative Co2 emission with your vehicle!</h2>
<button type="button" id="carsnow" class="carBtn btnFoot"><i class="icon-footprint-right-d"></i></button>
</div>
<div class="hideFirst" id="transportation">
<h2>Why won't I display?</h2>
<button type="button" data-next="" class="my-btn btnFoot"><i class="icon-footprint-right-d"></i></button>
</div>
</form>
<div>
<button id="backButton">Back</button>
</div>
</div>
Hoping to find some help here
OK, so it took a couple of days, but I figured this out.
The main problem is that the jquery .data- attributes are only read the very first time the property is accessed. So while I was changing them, at the right time, they weren't being read. It was also the reason that, while the back button worked it would not allow you to go to different divs when going back through the questions.
Here is the line from the jQuery documentation:
"The data- attributes are pulled in the first time the data property is
accessed and then are no longer accessed or mutated (all data values
are then stored internally in jQuery)."
Link to the page
By changing the .data- to a combination of .attr and .prop depending on the necessary functionality I was able to get it working.
As I mentioned in my original question, I'm very new so if I didn't provide enough info, please let me know.
Here is the code for it to work properly and a link to a fiddle.
var carCount = 0;
$(document).ready(function () {
// hide all 'hideFirst' elements, except the first one:
$('.hideFirst:not(:first)').hide();
var visited = [];
// Method used to show/hide elements :
function showNext(el) {
// check if element has a 'nextitem' attribute:
if (el.attr('nextitem')) {
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// show 'Back' button:
$('#backButton').show();
// show the element which id has been stored in 'nextitem' attribute:
$(el.attr('nextitem')).show();
// Push the parent element ('.hideFirst') into visited array:
visited.push(el.closest('.hideFirst'));
}
}
// click event for 'back' button:
$('#backButton').click(function () {
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// remove the last '.hideFirst' element from 'visited' array and show() it:
visited.pop().show();
// hide 'back' button if visited array is empty:
visited.length || $(this).hide();
}).hide(); // hide 'back' button on init
$(".myBtn").click(function () {
showNext($(this));
});
$("#amount").click(function () {
numberOfCars = parseInt(document.getElementById("inputNumber").value);
showNext($(this));
});
$("#typeA").change(function () {
carChoice = $("#typeA").val();
$("#typeA").attr("nextitem", "#" + carChoice);
showNext($(this));
//clears previous choices
$('#typeA').prop('selectedIndex', 0);
$('#typeB').prop('selectedIndex', 0);
$('#typeC').prop('selectedIndex', 0);
});
//Decides how many more times to iterate through
$(".carBtn").click(function () {
carCount++;
//asks about other cars
if (carCount < numberOfCars) {
$(this).attr('nextitem', '#main');
$("#bar").html(carCount);
$("#foo").html(numberOfCars);
}
//moves on to the next category
else {
$(this).attr('nextitem', '#last');
$("#bar").html(carCount);
}
showNext($(this));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form>
<div class="hideFirst">
<label for="inputNumber">Number of times to iterate through</label>
<input type="text" id="inputNumber" />
<button type="button" nextitem="#main" class="myBtn" id="amount">Next</button>
</div>
<div class="hideFirst" id="main">
<select id="typeA">
<option disabled selected>--Choose One--</option>
<option value="b">Option B</option>
<option value="c">Option C</option>
</select>
</div>
<div class="hideFirst" id="b">
<label for="typeB">Type B</label>
<select id="typeB">
<option disabled selected>--Choose One--</option>
<option value="a">Option a</option>
<option value="b">Option b</option>
<option value="c">Option c</option>
</select>
<button type="button" class="carBtn">Next</button>
</div>
<div class="hideFirst" id="c">
<label for="typeC">Type C</label>
<select id="typeC">
<option disabled selected></option>
<option value="a">Option a</option>
<option value="b">Option b</option>
<option value="c">Option c</option>
</select>
<button type="button" class="carBtn">Next</button>
</div>
<div class="hideFirst" id="last">
<p>Done</p>
</div>
</form>
<div>
<br/>
<button id="backButton">Back</button>
</div>
<div>
<p>Number of times you asked for:<span id="foo"></span>
</p>
<p>Number of times around this form:<span id="bar"></span>
</p>
</div>

Dropdown to show or hide div content is not working

I can't figure out why this script wont work:
<select name="options" id="options">
<option value="divname1"> Loan Protection Insurance</option>
<option value="divname2"> GAP or Cash Assist Insurance</option>
<option value="divname3"> Home Insurance</option>
<option value="divname4"> Landlords Insurance</option>
<option value="divname5"> Car Insurance</option>
</select>
<div id="divname1" style="display: block">Test 1</div>
<div id="divname2">Test 2</div>
<div id="divname3">Test 3</div>
<div id="divname4">Test 4</div>
<div id="divname5">Test 5</div>
document.getElementById('id-of-select').onchange = function() {
var i = 1;
var myDiv = document.getElementById("divname" + i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById("divname" + ++i);
}
document.getElementById(this.value).style.display = 'block';
};
div {
display: none;
}
Here is the code
http://jsfiddle.net/2ukyA/7/
However i can get this code working
http://jsfiddle.net/2ukyA/
But i want to have more than one of these on a page so i need something that isn't based on just numbers.
Instead of hiding all divs manually, you could just hide the <div> related to the previously selected value. You could store an associative array (like a map) in which you had, for a given <select> id, the last selected value, or even <div> id. In the onchange event handler, just hide the <div> with the id in the map, and show the new one.
Notice you'll still need to have an association (implicit if they're the same, or explicit if you store it in an array) between the <option> and the <div> id.
See an example in this JSFiddle.
In this example, there is a multidimensional associative array (sort of a map of maps) that stores the <option>s for each <select>. Each <option> is also associated to the <div> id it shows when selected. This same array is used to store the previously selected value for the array (in the entry previousValue).
Notice the definition of the associative array is done statically in javacsript, but it could be dynamically retrieved off an external JSON file, or an AJAX request. The <select> elements could also be dynamically built, but you'd need a little bit more information (i.e. option descriptions).
Javascript:
var selectDivOptions=
{select1:
{
option11: 'div11',
option12: 'div12',
option13: 'div13'
},
select2: {
option21: 'div21',
option22: 'div22',
option23: 'div23'
}
};
for (var key in selectDivOptions){
var element = document.getElementById(key);
element.onchange = selectChange;
}
function selectChange(){
// Hide the div pointed by the previous value
var previousValue = selectDivOptions[this.id]['previousValue'];
if (previousValue){
document.getElementById(previousValue).style.display = 'none';
}
// Show the div
var divToShow = selectDivOptions[this.id][this.value];
if (divToShow){
document.getElementById(divToShow).style.display='block';
}
// Store the current value as the previous value
selectDivOptions[this.id]['previousValue'] = divToShow;
}
HTML
<select name="options" id="select1">
<option value="option11"> Option 11</option>
<option value="option12"> Option 12</option>
<option value="option13"> Option 13</option>
</select>
<div id="div11">Div 11</div>
<div id="div12">Div 12</div>
<div id="div13">Div 13</div>
<br />
<select name="options2" id="select2">
<option value="option21"> Option 21</option>
<option value="option22"> Option 22</option>
<option value="option23"> Option 23</option>
</select>
<div id="div21">Div 21</div>
<div id="div22">Div 22</div>
<div id="div23">Div 23</div>

Categories

Resources