Alter an existing script that works - javascript

I do not want to use JQuery. Here is a simple piece of javascript that works that allows you to search a dropdown menu list:
<HTML><HEAD><SCRIPT type="text/javascript">
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('realitems').options;
for(var i=0;i<output.length;i++) {
if(output[i].value.indexOf(input)==0){
output[i].selected=true;
}
if(document.getElementById('realtxt').value==''){
output[0].selected=true;
}
}
}
</SCRIPT></HEAD><BODY>
<FORM>
Search <input type="text" id="realtxt" onkeyup="searchSel()">
<SELECT id="realitems">
<OPTION value="">Select...
<OPTION value="afghanistan">Afghanistan
<OPTION value="albania">Albania
<OPTION value="algeria">Algeria
<OPTION value="andorra">Andorra
<OPTION value="angola">Angola
</SELECT>
</FORM></BODY></HTML>
The problem is that in order for it to work, the value of each option has to have the text. I tried changing the "value" fields in the javascript code to "name" so that it would search the name only, but no go. My option fields have numbers, and I cannot easily convert them to names. Is there a way to tweak this javascript to work with names or better yet search within the option tags?

You will need to change two things in the line
if(output[i].value.indexOf(input)==0){
use the .text property instead of .value at your <option> elements.
make it lowercase to match the lowercased input. With lowercase value attributes and numbers you did not have this problem.
This script would be the result:
function searchSel() {
var input = document.getElementById('realtxt').value.toLowerCase(),
len = input.length,
output = document.getElementById('realitems').options;
for(var i=0; i<output.length; i++)
if (output[i].text.toLowerCase().slice(0, len) == input)
output[i].selected = true;
if (input == '')
output[0].selected = true;
}
I also have used an improved startswith check.

This line:
var input=document.getElementById('realtxt').value.toLowerCase();
makes input a string.
<OPTION value=1>text
value is an integer.String will never == integer.
Change
if(output[i].value.indexOf(input)==0) to
to
if((output[i].value.indexOf(input)==0) || (output[i].value.indexOf(parseInt(input)))

use this code, i have replaced "value" with "innerHTML"
function searchSel() {
var input = document.getElementById('realtxt').value.toLowerCase();
var output = document.getElementById('realitems').options;
for (var i = 0; i < output.length; i++) {
if (output[i].innerHTML.indexOf(input) == 0) {
output[i].selected = true;
}
if (document.getElementById('realtxt').value == '') {
output[0].selected = true;
}
}
}

Related

How to obtain multiple select options when serializing Form data in javascript (vanilla or jQuery)?

I wrote the following function that turns a div/Form into serialized object. I use this returned to pass into my database javascript calling methods.
Tater.prototype._formToObject = function(formData) {
var p = {};
jQuery.each(jQuery(formData).serializeArray(),function(i, e){
p[e.name] = e.value;
});
return p;
};
The only issue is if I change my form to have a multiple select option, it only grabs the first value of the multiple selected. How would I extend this to allow for such behavior?
Try something along these lines to get the array of values.
If you give us a working snippet of what you are doing it will be easier to adapt to what you want.
Most likely you need to add a check for the multiple attribute on e (see comments below)
else do the current logic that seems to be working
in the below logic replace this with e for your scenario
`
Tater.prototype._formToObject = function(formData) {
const p = {};
jQuery.each(jQuery(formData).serializeArray(),function(i, e){
//check for multiple attr
e.getAttribute('multiple') == null ?
(p[e.name] = e.value) :
(p[e.name] = $(e).val());
});
return p;
};
`
document.getElementById('multi').addEventListener('change', function () {
//jquery
this.getAttribute('multiple') != null && console.log($(this).val());
//vanilla
if(this.getAttribute('multiple') != null) {
const arr = [], nodes = this.querySelectorAll(':checked');
for(let i = 0; i < nodes.length; i++) {
arr.push(nodes[i].value);
}
console.log(arr);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="multi">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<!-- from https://www.w3schools.com/tags/att_select_multiple.asp -->

Why does dropdown list selection from a location hash work on Chrome, but not Firefox, IE, or Safari?

Complete JS novice. I want a "Request A Quote" button to auto-populate a dropdown menu on a new page based on the product and url. Each product quote button links to the same form but with a different hash value in the url which matches an option in the dropdown menu.
Example:
User clicks "Request A Quote" for 'Product A'
User is sent to www.example.com/request-a-quote/#Product A
Product dropdown menu (id=product-select) on form already reads "Product A"
This code works on Chrome, but not for anything else. What am I doing wrong?
//Get select object
var objSelect = document.getElementById("product-select");
var val = window.location.hash.substr(1);
//Set selected
setSelectedValue(objSelect, val)
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;
}
}
}
I found that applying decodeURIComponent() cleaned up my val variable.
Also, building links as www.example.com/request-a-quote/#Product A is important. If the forward slash is not before the hash, mobile Safari will ignore everything after the hash and it won't work.
Below is my final solution:
//Get select object
var objSelect = document.getElementById("product-select");
var val = decodeURIComponent(window.location.hash.substr(1));
//Set selected
setSelectedValue(objSelect, val)
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;
}
}
}
Without seeing more code.... The option tag officially supports the value attribute vs text which is the user readable name. We use value as an identifier:
selectObj.options[i].value == valueToSelect;
You will also need to change the select.options markup to use the value attribute rather then text.
UPDATE more info as requested:
The purpose of text is to provide a user readable option. We use value to identify the selection to the server and in your case the URL hash. By using the value attribute, you can use URL safe values and user readable text.
The fix you posted in your answer is really bad practice and will become problematic as the complexity of your code increases.
This example will work in all browsers and is the proper way to implement.
//Simulate hash
window.location.hash = '2'
var val = window.location.hash.substr(1);
var selectEle = document.getElementById('select')
setSelectedValue(selectEle, val)
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
var selection = selectObj.options[i]
if (selection.value == valueToSet) {
selection.selected = true;
}
}
}
<select name="selections" id="select">
<option value="1">Product A</option>
<option value="2">Product B</option>
<option value="3">Product C</option>
</select>

Replace option code with another code by using option index

I have a dropdown list
<select name="answers[0][]">
<option value="0" >Beredskap</option>
<option value="1" >Förbundsledning</option>
<option value="2" >Förbundsledning stab</option>
<option value="3" >Ekonomiavdelningen</option>
</select>
What i am seeking for is to get the value getElementsByTagName('select')[1] and then replace it with
<option value="1" disabled >Förbundsledning</option>
the reason for it is that the list is auto generated so i need to modify the html output instead.
what i have sofar that does not work is :
document.getElementsByTagName('select')[0]
.innerHTML.replace('<option value="1" disabled>apple</option>')
The option with the value 1 happens to be at index 1 in your code, should that always be the case other answers than this one will apply.
In the case where you don't know the order of the generated options and thus don't know the index of the option you want to change, it depends on whether you want to change the text based on the value or the original text.
You could do this:
var options = document.getElementsByTagName("option");
for(var e = 0; e < options.length; e++) {
//change by text
if (options[e].text == "Apple") {
options[e].text = "Förbundsledning";
}
//change by value
if (options[e].value == "1") {
options[e].text = "Förbundsledning";
}
}
you could use jQuery and selectors to find your list box $('#myListBox').val();
you can easily change the value by $('#myListBox').val("new value");
You can also easily iterate over the list of options and do whatever you wish.
$("#id option").each(function()
{
// add $(this).val() to your list
});
How about this ?
var sel = document.getElementsByTagName('select')[0];
sel.innerHTML = sel.innerHTML.replace('Förbundsledning', 'apple');
http://jsfiddle.net/VxhvF/
use function ;
function select_text_replace(option_text, replace_text) {
var el = document.getElementsByTagName('select')[0];
el.innerHTML = el.innerHTML.replace(option_text, replace_text);
};
select_text_replace("Förbundsledning", "apple");
select_text_replace("Ekonomiavdelningen", "apple2");
see sample: http://jsfiddle.net/sm94N/
document.getElementsByTagName('select')[0].options[1].text="apple"
[1] is index of your options item. 0 = Beredskap, 1 = Förbundsledning.

How to set selectedIndex of select element using display text?

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories