JaveScript Select the dropdown list by the text of options - javascript

Is it possible to select the dropdown list by using the display-text of the options in the console(JavaScript)?
In my workplace, I need to fill a web form every day. But the options are too much to load, so I hope to use the Chrome console to select the option instead of using the mouse to click.
For now, I can use Value to select the option, but when I try to use the text, it fails.
The HTML sample and the JavaScript I used are as below. Could someone help?
Success - document.querySelector("#sel").value = 123
Fails - document.querySelector("#sel").text = "Product A"
<select>
<option value="123"> Product A </option>
<option value="243"> Product B </option>
<option value="212"> Product C </option>
<option value="466"> Product D </option>
</select>

Array.from(document.querySelectorAll('option')).find(el => el.textContent === 'Product A');

Truly sorry for the confusing example.
After trying lots of solutions, the final coding as below:
var txt = prompt();
for (i = 0; i < document.querySelector("#sel").options.length; i++) {
if(document.querySelector("#sel").options[i].text == txt){
document.querySelector("#sel").options[i].selected = true;
break;
}
}
With these codes, the User can select the specific options by entering the name of the product instead of clicking the dropdown list with the mouse and crash the browser.

Related

display a part of value in select option

I have a select drop-down with country and code. In drop-down option, for user experience and understanding i am displaying name of the country along with country code.
As a normal functionality when a user selects any value from the drop-down that value gets displayed inside the input like this
however i want that only the country code should get displayed like this
Part of my code
<select name="countrycode" class="form-control pf-country" id="countrycode">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The entire code is available here
Can anyone please suggest how to do it.
As per my understanding, You can try this one. As this example providing exact output as you mentioned in your questions.
https://silviomoreto.github.io/bootstrap-select/examples/#selected-text
Basically we're trying to change innerText of selected-option. It can be achieved easily by adding onchange event listener to the select tag.
But there's a little problem, on changing innerText we lose previous value of innerText, solution by #KKK solves problem but leaves this little thing.
Following code handles problem in complete ways. We're adding data-innerText atribute with previous value of innerText and also id="previous" to identify it. Please check this demo.
function simpleTweak(select){
var previouslySelectedTag = document.getElementById('previous');
if(previouslySelectedTag!=undefined){
previouslySelectedTag.innerText = previouslySelectedTag.getAttribute('data-innerText');
previouslySelectedTag.setAttribute('id','');
}
var innerText = select.options[select.selectedIndex].innerText;
select.options[select.selectedIndex].setAttribute('data-innerText',innerText);
select.options[select.selectedIndex].setAttribute('id','previous');
var value="(+"+select.options[select.selectedIndex].value+")";
select.options[select.selectedIndex].innerText = value;
}
As I understood, you need to change the display text after selecting the option, is it? If so, you can do it like this.
You can set the selected index's text in onchange event. But it will reset the text in the option when you click the dropdown again. You may need to change it back if you prefer.
function displayCountryCode() {
var countrycode = document.getElementById("countrycode");
countrycode.options[countrycode.selectedIndex].text = '+' + countrycode.value;
}
<select name="countrycode" class="form-control pf-country" id="countrycode" onchange="displayCountryCode()">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The following JavaScript code will change the text of the selected option when you select it and change it back when you select a different one.
It does this by saving the values of the country name and country number as HTML5 data attributes (option.dataset.countryName & option.dataset.countryNumber)
Doing it this way, you don't have to change the format of the HTML from what you provided in your post.
I used vanilla JavaScript, so it'll work with or without jQuery.
window.addEventListener('load', () => {
let select = document.getElementsByName('countrycode')[0]
let options = document.getElementsByTagName('option')
for (let i = 1; i < options.length; i++) {
let option = options[i]
let matches = option.innerText.match(/(.*?) (\(\+\d+\))/)
option.dataset.countryName = matches[1]
option.dataset.countryNumber = matches[2]
// Set the value in the collection again now that the object has been changed
options[i] = option
}
select.addEventListener('change', () => {
for (let i = 1; i < options.length; i++) {
let option = options[i];
option.innerText = option.dataset.countryName + ' '
option.innerText += option.dataset.countryNumber
}
let option = document.querySelector('option:checked')
if (option !== options[0]) {
option.innerText = option.dataset.countryNumber
}
})
})
There's also a demo at CodePen

How to dynamically update select value?

Can anyone please help me how to accomplish following?
I have a dropdown field, which have flowers name.The default value is "Select your favorite flower". On tap or click, the dropdown opens and shows the list of options and when user selects a particular value, the field shows the selected flower name.
I need to append Favorite Flower: then the selected value. Can you guys please help me in how to accomplish this?
Please see the image:
All three states of dropdown
HTML Code
<select>
<list> Select your favorite flower</list>
<list>Rose</Rose> <list>Marigold </list>
<list>Lily</lily>
</select>
Use a change event, append a span with the text to the selected option:
$('select').on('change',function() {
$('option').find('span').remove();//remove previous selected span
var val = $(this).find(':selected').html();//get the text/html of the potion
$(this).find(':selected').html('<span>Favorite Flower: </span>'+val);//change the text with the option
});
https://jsfiddle.net/r5377h21/
or:
$('select').on('change',function() {
$('option').find('span').remove();
var selected = $(this).find(':selected'),
val = selected.html();
if(!selected.is('option:first')) {
$(this).find(':selected').html('<span>Favorite Flower: </span>'+val);
}
});
https://jsfiddle.net/r5377h21/1/
can you please try this.
let me know if you need any changes in it
Code :
<script>
function test(obj)
{
$("select option").each(function(){
$(this).text($(this).text().replace("favorite flower - ",""))
})
if($("option:selected",$(obj)).val() != -1){
$("option:selected",$(obj)).text("favorite flower - "+$("option:selected",$(obj)).text())
}
}
</script>
<select onchange="test(this)">
<option value="-1">Select your favorite flower</option>
<option>Rose</option>
<option>Marigold</option>
<option>Lily</option>
</select>

Javascript multiple select boxes

I tried searching for an answer to this for a while, but to no avail.
I'm trying to do a simple online calculator (that calculates some photovoltaic panels energy), but I'm stuck in something simple (I'm new to Javascript although I worked with Flash's ActionScript 3.0 for a while).
What I need done is a html select that defines which other select group appears in the page. Something like this (obviously this doesn't work, just setting an example):
HTML
<html>
<body>
<select id="test1" onclick="checkField()">
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
Javascript
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
//insert code to "echo" the first optional select group
} else {
//insert code to "echo" the second optional select group
}
}
Sorry if its a bit confusing, but I cant really explain all that well.
Here is an example of what I would want, where selecting a option makes the other fields change accordingly: http://www.toshiba.eu/innovation/download_drivers_bios.jsp
you are almost there, actually javascript doesn't "echo" values directly, it does log values using console.log(your value); to a debug console, similar to AS2 trace() if my memory isn't failing.
To "output" information to the document you should have a look into document.write
When you use document.write it will directly write to the documents end.
The "correct" way would be to create a DOM element, with the elements you want inside it, and then append it to the desired element. Have a look at the comments
<!-- Be Aware to use the onchange trigger on select boxes, if you use onclick the function will run, even
if you didn't really chose any option -->
<select id="test1" onchange="checkField()">
<!-- Is good to have a first non-value option, better to trigger the onchange event, if you have
Select A Group as first option and you click on it, it didn't really "Change", you would have to
pick B Group and then A Group again to trigger the onchange event correctly. -->
<option value="">-- select an option --</option>
<!-- You can have a value attribute on the options, so it's easy to process when programming
while displaying a more detailed description to the users -->
<option value="A">Selected A Group</option>
<option value="B">Selected B Group</option>
</select>
<!-- We create an empty element where we are gonna place the new Select -->
<div id="newSelect"></div>
<!-- By Placing the Javascript on the end of <body>, we ensure that all the DOM elements loaded before running the script -->
<script>
function checkField(){
var newSelect = document.getElementById('newSelect'); //targeting container;
var temp = document.getElementById('test1').value;
//Some tasks we do always the option chose is not the first custom one, so we don't have to repeat it
//on the two If's below
if(temp !== ""){
// We remove the select if we placed one already before, so we can add the new one,
// For example if we chose B Group but changed our mind and Chose A Group later.
if(oldChild = newSelect.getElementsByTagName('select')[0]){
oldChild.remove();
}
var select = document.createElement("select");
select.setAttribute('id', 'newSelect');
}
if(temp === "A"){
//you could do JUST:
//body.innerHTML = "all the html you want in here" instead of all the code following;
//but all those code is supposed to be the "correct way" of adding elements to the HTML,
//Google a bit about that for detailed explanations
var option1 = document.createElement("option");
option1.value = 1;
option1.text = "Option 1";
var option2 = document.createElement("option");
option1.value = 2;
option2.text = "Option 2";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
} else {
var option1 = document.createElement("option");
option1.value = 3;
option1.text = "Option 3";
var option2 = document.createElement("option");
option1.value = 4;
option2.text = "Option 4";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
}
}
</script>
Of course there are ways to make this slightly shorter, using loops if your data to ouput has a pattern, but lets do it the "simple" way so you get a grasp of Javascript.
Hope all this helped you!!
Demo here:
http://jsfiddle.net/3GkrX/
Just about the same as Mevins.... changed to switch/case though
html:
<select id="test1" id="name" onchange="checkField()">
<option>----</option>
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<div id="optional">Please select!</div>
JS:
function checkField(){
var temp = document.getElementById('test1').value;
switch(temp){
case "Selected A Group":
document.getElementById("optional").innerHTML="<select name='optionalA'><option>1</option><option>2</option></select>";
break;
case "Selected B Group":
document.getElementById("optional").innerHTML="<select name='optionalB'><option>3</option><option>4</option></select>";
break
default:
document.getElementById("optional").innerHTML="Please select!";
break;
}
}
Also added the second group as a real option, and a default as "please select". may or may not be necessary in your case
Here is the demo http://codepen.io/anon/pen/izAHo
your doing it almost right.
You should put the onclick event on the option tag to trigger changes based on the option selected.
HTML
<html>
<body>
<select id="test1">
<option onclick="checkField()">Selected A Group</option>
<option>Selected B Group</option>
</select>
<select id="test2">
<option onclick="check2Field()">Selected C Group</option>
<option>Selected D Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
JS
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
document.getElementById('test2').innerHTML="<option>Selected halloooo Group</option>";
} else {
//insert code to "echo" the second optional select group
}
}
Check out my demo for more clarity.

customize java script function from particular page when that method is used by many pages

I have a drop down like
<select>
<option value="">Select</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
</select>
I have the same select box in more than 10 places in different pages.This is populating through ajax.But when i am calling this from a particular page i need to select ABC by default.But i don't want in remaining places.
I don't want to write the code again in my page.Is there any possibility for this.
Thanks in advance...
It's going to be a very generic answer that you'll have to modify for your needs, but if the select and all other markup is the same on all pages, which is very unlikely, you have to check the URL to see if you're on a certain page.
At the bottom of the page, before </body>, you can do something like :
if ( window.location.href.indexOf('/mysite.html') != -1 ) {
document.getElementsByTagName('select')[0].value = '1';
}
This will set the default value of the first select on the page to 1, and show ABC, if the URL contains mysite.html.
FIDDLE
Here you have another example (with JQuery) taking into account the comment you did about loading your combos with options obtained with ajax: Try if yourself
JQUERY:
var options = "<option value=\"\">Select</option><option value=\"1\">ABC</option><option value=\"2\">DEF</option>";
function test() {
// Populate select with ID destiny 1 without selecting a value
populate("#destiny1", null, options);
// Populate select with ID destiny 2, selecting the value of the first index
populate("#destiny2", 1, options);
}
function populate(destiny, indexOption, options) {
$(destiny).html(options);
if (indexOption != null) {
$(destiny + " option")[indexOption].selected = true;
$(destiny).trigger("change");
}
}
HTML:
<select id="destiny1"></select>
<select id="destiny2"></select>
<input type="button" onclick="test()" value="TEST"></input>

Dropdown / Select Box Navigation with JavaScript ?

I want to ask quick question, i want to make a select drop down that when i choose one of the options the values of the other select drop down change ...
let's say i have select drop down called model that has the following
- Acura
- Aston martin
- Audi
I want when i choose (let's say ) Audi, in the type select drop down i find Audi type's only
- A3
- A5
- A4
I don't want to use AJAX calls, i just want to use javascript or jquery to filter the data
thanks guys
Like Shomz said,
Assuming the dropdowns look like this:
<!-- First dropdown. Make of car -->
<select name='Manufactor' id='make'>
<option value='null'>Select a Make</option>
<option value='Audi'>Audi</option>
<option value='BMW'>BMW</option>
<option value='Volvo'>Volvo</option>
</select>
<br />
<!-- Second dropdown. Model of car -->
<select name='Model' id='model'>
</select>
The javascript would look like this:
<script type='text/javascript'>
var model = ['','audi','bmw','volvo']; //Set makes
model[1] = ['A3', 'A5', 'A4']; // Set Audi models
model[2] = ['M3', 'M5', 'M6']; // Set BMW models
model[3] = ['C30', 'C70']; // Set Volvo models
var test = model[1][1];
function setModel(index) {
var modelDropdown = document.getElementById('model');
modelDropdown.options.length = null;
for(var i = 0; i < model[index].length; i++) {
modelDropdown.options[i] = new Option(model[index][i]);
}
}
window.onload = function() {
var makeDropdown = document.getElementById('make');
makeDropdown.onchange = function() {
setModel(this.selectedIndex);
}
}
</script>
Notice that the Models start at index 1 and not 0, because the first option is a blank Select Model option.
AJAX calls would still be the best solution, but if you don't want to use them, you can always manually create arrays for each of the main options, make an onchange event on the select element which would call the selected array and create another dropdown based on the elements of that array. Hope I didn't make it sound to complicated, since it isn't.
Here's a sample how to extract values with jQuery.

Categories

Resources