HTML tag loop inside another tag - javascript

I have a select and a list of div elements like this:
<select name="select" id="select">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<button>submit</button>
<div id='list'>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
</div>
I want to only show the div that has the h2's text that matches the selected value.
I'm trying the following JavaScript loop:
<script>
var select = document.getElementById('select');
var divItems = document.querySelectorAll('#table div');
var h2Items = document.querySelectorAll('#table div h2');
var button = document.querySelector('button');
button.addEventListener('click',function(){
var selectValue = select.value;
for(i=0; i < divItems.length; i++){
var h2Text = h2Items[i].innerHTML;
if (h2Text == selectValue){
divItems[i].display='block';
} else {
divItems[i].display='none';
}
}
});
But it doesn't work.
The console.log show that the h2's text and selected value are all correct,
but I don't know how to control the div's style.
Can somebody help me?
Thanks.

You need to specify that you are updating a style.
divItems[i].display='block'; should be divItems[i].style.display='block';
AND
divItems[i].display='none'; should be divItems[i].style.display='none';
Also, you are targeting #table, but you should be targeting #list since that is the id set on your main div.
Full JS:
<script>
var select = document.getElementById('select');
var divItems = document.querySelectorAll('#list div');
var h2Items = document.querySelectorAll('#list div h2');
var button = document.querySelector('button');
button.addEventListener('click',function(){
var selectValue = select.value;
for(i=0; i < divItems.length; i++){
var h2Text = h2Items[i].innerHTML;
if (h2Text == selectValue){
divItems[i].style.display='block';
} else {
divItems[i].style.display='none';
}
}
});
</script>

I have changed couple of things which I will explain below but first here is the solution which works as expected:
const select = document.getElementById('select');
const divItems = document.querySelectorAll('#list div'); // this was #table
const h2Items = document.querySelectorAll('#list div h2');
const button = document.querySelector('button');
button.addEventListener('click', function() {
const selectValue = select.value;
for(let i = 0; i < divItems.length; i++) {
if (h2Items[i].innerHTML === selectValue){
divItems[i].style = "display:block";
} else {
divItems[i].style = "display:none";
}
}
});
<select name="select" id="select">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<button>submit</button>
<div id="list">
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
</div>
Suggestions:
It is worth to check how HTMLElement.style works please find a link here.
Additionally learn the differences between var, let and const.
Last but not least differences between == and ===.
I hope this helps!

Related

Find Options text in Dropdown and set selected and change text

with vanilla javascript I'd like to loop through my dropdown, and change the selected one, and then change the text that is displayed. I have it selecting, but I'm not getting the object name correct to change the optionText? of the item.
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
i.options.text = "Edgewood Login"; //This is WRONG
break;
}
}
guidance is appreciated.
You can use a querySelector and a selector to access it without a loop.
v = "222";
selProvider = document.querySelector("#membershipProvider option[value='" + v + "']");
if (selProvider) {
selProvider.text = "CHANGED!";
selProvider.selected = true;
}
<select id="membershipProvider">
<option value='111'>AAA</option>
<option value='222'>BBB</option>
</select>
You need to modify the option at that index. Right now you are trying to modify the index itself.
should be:
dd.options[i].text
not
i.options.text
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
dd.options[i].text = "Edgewood Login"; //This is WRONG
break;
}
}
<select id="membershipProvider">
<option value="cifs">CIFS</option>
<option value="LdapUsers">LdapUsers</option>
<option value="nfs">NFS</option>
<option value="test">Test</option>
</select>
You should use
dd.options[i].text = "Edgewood Login";
just like when checking for its value

Selecting an option of select tag based on text inside

I have a dropdown like this :
<select id="mySelect" size="4">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
I have another var fruit = "some_fruit" and I want to select the item in the options based on the value of the variable some_fruit.
The selection has to be done using javascript DOM.
What I have tried so far :
var x = document.getElementById("mySelect").options.namedItem("orange").text;
But this selects the option using the id.
One possible solution :
var x = document.getElementById("mySelect");
var txt = "";
var some_fruit = "some_fruit";
var i;
for (i = 0; i < x.length; i++) {
txt = x.options[i].text;
if (txt == some_fruit) {
// Hooray! We are done.
}
}
Is there any way to do it without looping the select tag options ?

How to change a select form by buttons

I have a select form:
<select>
<option value ="one">Label 1</option>
<option value ="two">Label 2</option>
<option value ="three">Label 3</option>
</select>
but I also have some buttons that call the same functions as the select form would
<button class="one">Label 1</button>
<button class="two">Label 2</button>
<button class="three">Label 3</button>
So if I select one of these buttons how could I change the option that shows up in the select form (by that I mean the text that's in the form before you open it up) ?
so if you $("button.three").click(); "Label 3" would show up in the select form
I'm not sure what the function is to change the <select>'s label. I've tried these but they don't work:
$("select").select().val("three");
$("select").find([value="three"]).select();
$("select").selectedIndex = 1;
$("button").on("click", function() {
var selectedClass = $(this).attr("class");
$("option[value="+ selectedClass + "]").attr("selected", true);
});
Try $("select").val("three");
http://api.jquery.com/val/#val-value
This seems to be the simplest solution:
$("button").click(function () {
$('select').val($(this).attr('class'))
});
jsFiddle example
Apparently others beat me to the answer while I was writing a response, but eh... here's a non-jQuery solution. ;)
var buttons = document.getElementsByTagName('button');
var mySelect = document.getElementById('mySelect');
var mySelectOptions = mySelect.getElementsByTagName('option');
for (var i = 0, length = buttons.length; i < length; i++) {
var button = buttons[i];
button.onclick = function(event) {
var text = event.target.innerText;
for (var x = 0, length = mySelectOptions.length; x < length; x++) {
var option = mySelectOptions[x];
if (option.innerText === text) {
mySelect.selectedIndex = x;
return;
}
}
}
}
http://jsfiddle.net/bvaughn/x1chabLa/

Read select=multiple not working

I have a multi select option filed like the follows;
<select name="cars" id="carsId" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit" onclick="readValues()">
I need to read all the values into an array on readValues function. The array shopuld be like
A = [Volvo,Saab,opel,audi]
Please help me guys!!
You may try this also:
var readValues = function () {
var options = document.getElementById('carsId').options;
var list = [],
i = options.length;
while (i--) {
list.push(options[i].value);
}
console.log(list);//<-- ["audi", "opel", "saab", "volvo"]
};
In-case you need the text shown to user, use list.push(options[i].innerHTML);
http://www.w3schools.com/jsref/coll_select_options.asp
var x = document.getElementById("mySelect");
var options = [];
for (var i = 0; i < x.length; i++)
{
options.push(x.options[i].value);// or .text for the text
}
with jquery :
How to get all options of a select using jQuery?
var options = [];
$("#id option").each(function()
{
options.push($(this).val());
});
You can try this:
If you're using jQuery you can try following
jQuery solution
function readValuesJQuery(){
var A = $("select option").map(function(){
return this.value;
}).get();
console.log(A);
}
OR
javascript solution
function readValuesJavascript(){
var ddlArray= new Array();
var ddl = document.getElementsByTagName('select')[0];
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl .options[i].value;
}
console.log(ddlArray);
}
Demo
using jQuery:
function readValues() {
var values = [];
$('[name="cars"] option').each(function() {
values.push($(this).val());
});
return values;
}
using pure javascript:
var readValues = function () {
var options = document.getElementById('carsId').children;
var values = [];
for(i = 0; i < options.length; ++i) {
values.push(options[i].value);
}
console.log(values);
return values;
}
Demo: http://jsfiddle.net/q94ndrcc/
click here
$("#sel").click(function(e) { // when link clicked
e.preventDefault();
$("#foo option:selected ").each(function() {
var v = $(this).attr("value"); // first select's value
$('#bar option').each(function() {
if ($(this).attr("value") == v) {
$(this).attr("selected",true); // select if same value
}
});
});
})
Try following its working.
HTML
<select name="cars" id="carsId" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" id="btnClick" value="getValue">
Script: jQuery 1.9.1
//1. for selected value:
$(document).ready(function(){
$('#btnClick').click(function(){
var selText = [];
$("#carsId option:selected").each(function () {
var $this = $(this);
if ($this.length) {
selText.push($this.text());
}
});
alert(selText);
});
});
//2. get all value without any selection:
$(document).ready(function(){
$('#btnClick').click(function(){
var selText = [];
$("#carsId option").each(function () {
var $this = $(this);
if ($this.length) {
selText.push($this.text());
}
});
alert(selText);
});
});
Running Demo

auto complete to select option in javascript

I am trying to make auto complete to select option according to input from the user
something like
<input type=text onkeyup=findit()>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
.
.
.
<select>
I found this code 'but it only work on one select in the page( I need multi select)
<html>
<head>
<script type="text/javascript">
//initialize some global variables
var list = null;
function fillit(sel,fld) {
var field = document.getElementById("entry");
var selobj = document.getElementById("sel");
if(!list)
{
var len = selobj.options.length;
field.value = "";
list = new Array();
for(var i = 0;i < len;i++)
{
list[i] = new Object();
list[i]["text"] = selobj.options[i].text;
list[i]["value"] = selobj.options[i].value;
}
}
else
{
var op = document.createElement("option");
var tmp = null;
for(var i = 0;i < list.length;i++)
{
tmp = op.cloneNode(true);
tmp.appendChild(document.createTextNode(list[i]["text"]));
tmp.setAttribute("value",list[i]["value"]);
selobj.appendChild(tmp)/*;*/
}
}
}
function findIt(sel,field)
{
var selobj = document.getElementById("sel");
var d = document.getElementById("display");
var len = list.length;
if(field.value.length > 1)
{
if(!list)
{
fillit(sel,field);
}
var op = document.createElement("option");
selobj.options.length = 1
var reg = new RegExp(field.value,"i");
var tmp = null;
var count = 0;
var msg = "";
for(var i = 0;i < len;i++)
{
if(reg.test(list[i].text))
{
// d.childNodes[0].nodeValue = msg;
tmp = op.cloneNode(true);
tmp.setAttribute("value",list[i].value);
tmp.appendChild(document.createTextNode(list[i].text));
selobj.appendChild(tmp);
}
}
}
else if(list && len > selobj.options.length)
{
selobj.selectedIndex = 0;
fillit(sel,field);
}
}
</script>
</head>
<body onLoad="fillit(sel,entry)">
<div>Enter the first three letters of a street and select a match from the menu.</div>
<form>
Street
<input type="text" name="Street" id="entry" onKeyUp="findIt(sel,this)"><br>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
<option value="s0003">bol</option>
<option value="s0004">col</option>
<option value="s0005">dol</option>
<option value="s0007">Cooper</option>
<!--and so on and so forth-->
</select>
</form>
</body>
Any Ideas How to make it work on multi select on the page?
Thanks
Baaroz
Not sure if this would work for you, but chosen.js has a really nice autocomple multi select
http://harvesthq.github.com/chosen/
Usually Autocomplete is for single values, but the jQuery UI autocomplete does have a multiple select function. Perhaps try that? Minimum effort coding for you that way.
An odd way to do that is to change the ID in the script and copy it the number of times you want to use this options in the page. so for example:
select id="sel1"
select id="sel2"
select id="sel3"
and then. copy the script and replace every (sel) with sel1 past it again and replace (sel) with sel2 and so on.
not the best solution but it will work.
Good Luck

Categories