How to show nearest div id for a given input number? - javascript

Let's say I have the following input field:
<input id="inputField" type="number" value="">
and some divs such as:
<div id="1000"></div>
<div id="1200"></div>
<div id="1500"></div>
<div id="1900"></div>
...
When the user enters a number in the input field, I want my code to go to the nearest div id to that number.
e.g: If user enters 1300 then show div with id = "1200".
What's the most efficient way to implement that in javascript considering there will be a large number of divs?
Right now I'm doing:
<script>
function myFunction()
{
var x = document.getElementById("inputField").value;
if(x >= 1750 && x <= 1900)
{
window.location.hash = '#1800';
}
}
</script>

One way is to wrap all your divs with number ids in another div if you can (and give it some id, say 'numbers'); this allows you to find all the divs in your javascript file.
Javascript:
// Get all the divs with numbers, if they are children of div, id="numbers"
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
// Append the integer of the id of every child to an array
array.push(parseInt(children[i].id));
}
// However you are getting your input number goes here
let number = 1300 // Replace
currentNumber = array[0]
for (const value of array){
if (Math.abs(number - value) < Math.abs(number - currentNumber)){
currentNumber = value;
}
}
// You say you want your code to go to the nearest div,
// I don't know what you mean by go to, but here is the div of the closest number
let target = document.getElementById(currentNumber.toString());
Let me know if there's more I can add to help.
Demo
function closestNum() {
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
array.push(parseInt(children[i].id));
}
let number = document.getElementById('inputnum').value;
currentNumber = array[0]
for (const value of array) {
if (Math.abs(number - value) < Math.abs(number - currentNumber)) {
currentNumber = value;
}
}
let target = document.getElementById(currentNumber.toString());
document.getElementById('target').innerHTML = target.innerHTML;
}
<div id="numbers">
<div id="1000">1000</div>
<div id="2000">2000</div>
<div id="3000">3000</div>
<div id="4000">4000</div>
<div id="5000">5000</div>
</div>
<br />
<input type="text" id="inputnum" placeholder="Input Number" onchange="closestNum()" />
<br />
<br /> Target:
<div id="target"></div>

With some optimization this shall be ok-
var element;
document.addEventListener("change",
function(evt){
if(element && element.classList){
element.classList.remove("selected", false);
element.classList.add("unselected", true);
}
var listOfDivs =
document.querySelectorAll(".unselected");
var val = evt.target.value;
var leastAbs=listOfDivs[0].id;
for(let anIndex=0, len=listOfDivs.length;anIndex<len;anIndex++){
if(Math.abs(listOfDivs[anIndex].id-val)<leastAbs){
leastAbs = Math.abs(listOfDivs[anIndex].id-val);
element = listOfDivs[anIndex];
}
}
element.classList.remove("unselected");
element.classList.add("selected");
});
.selected{
background-color:red;
}
.unselected{
background-color:yellow;
}
.unselected, .selected{
width:100%;
height:50px;
}
<input id="inputField" type="number" value="">
<div id="1000" class='unselected'>1</div>
<div id="1200" class='unselected'>2</div>
<div id="1500" class='unselected'>3</div>
<div id="1900" class='unselected'>4</div>

This may work for you. Loops through each div and compared it to your inputted ID. Tracks closest one, hides all divs, then displays the closest.
document.getElementById("inputField").addEventListener("change", function(){
var divs = document.getElementsByTagName("div");
var closestDiv = -1;
var inputId = document.getElementById("inputField").value;
for(var i=0; i<divs.length; i++)
{
if(Math.abs(inputId - closestDiv) > Math.abs(inputId - divs[i].id) || closestDiv == -1)
{
closestDiv = divs[i].id;
for (var x = 0; x < divs.length; x++) {
divs[x].style.display = 'none';
}
divs[i].style.display = "block";
}
}
});
See it Live: jsfiddle.net

Related

Repeating a div based on user input (JavaScript solution preferred)

Looking for the simplest implementation of the following problem:
I have a user input number field like:
<input type="number" id="numInput" name="numInput" value="1" onchange="myFunc()">
<div id="demo">*** TEST ***</div>
I want to replicate the #demo div based on the #numInput value entered by the user, e.g. if the user enters '5', there would be five #demo divs displayed on the page. At the moment, I'm using the following function:
function myFunc() {
var newArray = [];
var numInput = document.getElementById('numInput').value;
var x = document.getElementById('demo').innerHTML;
for(var i=0; i<numInput; i++) {
newArray.push(x);
}
document.getElementById('demo').innerHTML = newArray;
}
but this is adding to the existing array rather than outputting the exact number of divs based on user input. Please advise. Thanks.
There should not be multiple same id values.
function myFunc() {
let numInput = document.getElementById("numInput");
while (numInput.nextSibling) {
numInput.nextSibling.remove();
}
let numInputval = document.getElementById('numInput').value;
for(var i=numInputval; i>0; i--) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'demo' + i);
newDiv.innerHTML = '*** TEST ***';
numInput.parentNode.insertBefore(newDiv, numInput.nextSibling);
}
}
<input type="number" id="numInput" name="numInput" onchange="myFunc()">
+Edit
You can also manipulate <form> with javascript.
function myFunc() {
let numInput = document.getElementById("numInput");
while (numInput.nextSibling) {
numInput.nextSibling.remove();
}
let numInputval = document.getElementById('numInput').value;
for(var i=numInputval; i>0; i--) {
var newInput = document.createElement('input');
newInput.setAttribute('id', 'demoInput' + i);
newInput.setAttribute('type', 'text');
newInput.setAttribute('name', 'demoInputName' + i);
newInput.setAttribute('onchange', 'myFormChangeListener(this)');
numInput.parentNode.insertBefore(newInput, numInput.nextSibling);
numInput.parentNode.insertBefore(document.createElement('br'), numInput.nextSibling);
}
}
function myFormChangeListener(element) {
console.log(element);
console.log(element.value);
myForm.action = 'http://the.url/';
myForm.method = 'post';
console.log(myForm);
//myForm.submit;
}
<form id="myForm">
<input type="number" id="numInput" name="numInput" onchange="myFunc()">
</form>

How to iterate through all classes with a javascript toggle?

This is a toggle switch that when unchecked, will display 'min'. If checked, then 'min' will switch to 'max' and will toggle back and forth.
My expected result is that however many times this checkbox is on the page, the function will work across the entire page.
var x = document.getElementsByClassName("text");
function queryToggle() {
for (let i = 0; i < x.length; i++) {
if (x.innerHTML === "min") {
x.innerHTML = "max";
} else {
x.innerHTML = "min";
}
}
}
<div class="options mb-2">
<label for="toggleQuery">Use 'max-width'?</label>
<input type="checkbox" name="toggleQuery" id="toggleQuery" onclick="queryToggle()" />
</div>
<span class="text">min</span>
Using you current code, try this:
function queryToggle() {
let x = document.getElementsByClassName("text");
for (let i = 0; i < x.length; i++) {
console.log(x[i])
if (x[i].innerHTML === "min") {
x[i].innerHTML = "max";
} else {
x[i].innerHTML = "min";
}
}
}
Since x is an 'array-like' object you have to iterate over each item in it by its index, you were operating on the entire array, if that makes sense.
Shorter version
function queryToggle() {
let x = document.getElementsByClassName("text");
for (let i = 0; i < x.length; i++) {
x[i].innerHTML = x[i].innerHTML === "min" ? "max" :"min";
}
}
Another shorter version with spread operator no need to create the x array unless you need it somewhere else, downside is that you will be accessing the DOM on every call
function queryToggle() {
[...document.getElementsByClassName("t_text")].forEach((i)=>
i.innerHTML = i.innerHTML === "min" ? "max" :"min")
}
I have adjusted your code and included comments.
If you want to re-use the checkbox then simply change the id of each new checkbox you create and it will work across the page.
Run the snippet below:
//your span
var x = document.getElementsByClassName("text");
//here we are passing "input" as a function parameter
function queryToggle(input) {
//checkbox will take the id of any new input we create on the page
//the id must change for each new checkbox
var checkbox = document.getElementById(input.id);
for (let i = 0; i < x.length; i++) {
//check if checkbox is checked, if checked then change innerHTML to "max"
if (checkbox.checked == true) {
x[i].innerHTML = "max";
// else change innerHTML to "min"
} else {
x[i].innerHTML = "min";
}
}
}
<div class="options mb-2">
<label for="toggleQuery">Use 'max-width'?</label>
<input type="checkbox" name="toggleQuery" id="toggleQuery1" onChange="queryToggle(this)" />
<input type="checkbox" name="toggleQuery" id="toggleQuery2" onChange="queryToggle(this)" />
<input type="checkbox" name="toggleQuery" id="toggleQuery3" onChange="queryToggle(this)" />
<input type="checkbox" name="toggleQuery" id="toggleQuery4" onChange="queryToggle(this)" />
</div>
<span class="text">min</span>
<span class="text">min</span>
<span class="text">min</span>
<span class="text">min</span>
<span class="text">min</span>

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

Loop through div children and bold specific text not working

I have a suggestion dropdown under an input field and I am trying to make the text in the suggestion divs bold for the portion that matches what is currently in the input field.
e.g
input: AB
dropdown: ABCDE
My current code doesn't seem to be replacing the div content with the span
JS:
BoldMatchedText(inputToMatch:string){
var outerDiv = document.getElementById("dropdown");
if(outerDiv != null){
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++){
subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
html:
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">{{reg1}}</div>
<div class="reg-list-item">{{reg2}}</div>
<div class="reg-list-item">{{reg3}}</div>
<div class="reg-list-item">{{reg4}}</div>
</div>
</form>
You need to assign the result of calling the function replace.
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
function BoldMatchedText(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
BoldMatchedText('Go');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>
Try this working sample with a benchmark. Compared with the previous answer.
function BoldMatchedText1(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
function BoldMatchedText2(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if(outerDiv !== null) {
// Use `getElementsByClassName` instead using `getElementsByTagName('div')` JS will traverse your entire HTML file and look for all div tags, may take a little longer if you have a lot
var items = outerDiv.getElementsByClassName("reg-list-item");
// Getting the iteration length before the loop will give you performance benefit since items.length will not be checked per iteration
var len = items.length;
// Using while loop evaluating only if len is any positive number (true) except 0 (false) with reverse iteration making it faster
while(len--) {
var item = items[len].innerHTML;
// ONLY replace the text that contains the `inputToMatch`
if(item.indexOf(inputToMatch) !== -1) {
items[len].innerHTML = item.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
}
console.time('filter1');
BoldMatchedText1('Gom');
console.timeEnd('filter1');
console.time('filter2');
BoldMatchedText2('Gom');
console.timeEnd('filter2');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Categories

Resources