How to replicate text on many spans - javascript

What you type inside the input box should be replicated below, on each span.
I can do this with de js code below, but to do so I need to make the same code over and over again for each span that needs to be completed. I've tried using same class "one" on every span, but only works on the first span. I have to create a new class for every span and some code for each one of those spans.
I want to know a way to replicate the same text in many many spans without so much code. How?
var rep = document.getElementById('A');
rep.addEventListener('input', function() {
var result = document.querySelector('span.one');
result.innerHTML = this.value;
});
var rep = document.getElementById('A');
rep.addEventListener('input', function() {
var result = document.querySelector('span.two');
result.innerHTML = this.value;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="A">
<p>One: <span class="one"></span></p>
<p>Two: <span class="two"></span></p>

Use querySelectorAll to select all the elements of same css selector. Please use following code:
Please use this link to study more about querySelectorAll
var rep = document.getElementById('A');
rep.addEventListener('input', function() {
var result = document.querySelectorAll('span');
for(const res of result) {
res.innerHTML = this.value;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="A">
<p>One: <span class="one"></span></p>
<p>Two: <span class="two"></span></p>

Related

Set the color of a string variable in JavaScript (element.value) when it appears in html outside of a form

This is a simple example to help with a larger project -
Desired outcome: When you type a name in the form box, a sentence appears with the name included. However, only the name should have the color red, and only in the result (it shouldn't be red when it appears in the form box).
I get an error when I include "nameHere.style.color" in this code:
JS:
function getResponse(){
var nameHere = document.getElementById("name").value;
nameHere.style.color = "red";
var resultValue = "Hello my name is " + nameHere + ", nice to meet you.";
document.getElementById("result").innerHTML = resultValue;
}
HTML:
<div class="formclass">
<label for="name">Input name here</label>
<input id="name" onchange="getResponse()"></input>
</div>
<div id="result"></div>
Is there any real way to do what I'm trying to do within JavaScript?
Edit: to emphasize, I really do want to change the color of the variable that takes the element.value - not just the element. And I want it to appear in the result as the color. I can't find anything that allows me to do this correctly.
Basically, you apply styles to elements, not raw text. In your code, you are trying to set the style property of a piece of raw text, which doesn't have a style property and therefore is erroring out. In this case, you need to add an element to distinguish your output name. From there, you can either have a class ready (I called this one .theName) and apply the class name to the element or you can just set the style directly (like you were attempting) through script. I show both examples here. The second one uses a setTimeout - which is only to allow a brief delay before changing the color - that is just for illustrative purposes.
function getResponse(){
let nameHere = document.getElementById("name").value;
let resultValue = `Hello my name is <span class='theName'>${nameHere}</span>, nice to meet you.`;
document.getElementById("result").innerHTML = resultValue;
// or if you want to change the element after it's been written to the page
setTimeout(() => {
document.querySelector('.theName').style.color='blue';
}, 1000);
}
.theName{
color:red;
}
<div class="formclass">
<label for="name">Input name here</label>
<input id="name" onchange="getResponse()"></input>
</div>
<div id="result"></div>
Sure, you just need to use an element like span instead of a literal string.
const input = document.getElementById("name");
const result = document.getElementById("result");
function getResponse() {
const name = input.value;
let nameWrapper = document.createElement('span');
nameWrapper.style.color = 'red';
nameWrapper.innerText = name;
result.innerHTML = '';
result.appendChild(document.createTextNode('Hello my name is '));
result.appendChild(nameWrapper);
result.appendChild(document.createTextNode(', nice to meet you.'));
}
<div class="formclass">
<label for="name">Input name here</label>
<input id="name" onchange="getResponse()">
</div>
<div id="result"></div>

Manipulate value dynamically (onchange) from span to input?

I am developing a form which has an input called "net worth" and I have an embedded widget below this input which you can choose your currency and insert your budget and it would convert it to your desired currency. it looks like this:
You can check online the widget here.
So I want whenever the result changes (onChange) my input field value changes too. The result is in the span with #result-fit ID and my input box is #netWorthValue ,
I have searched a lot and try some best practice but still, I can not figure it out. The most relevent question in Stackoverflow was this question but it couldn't help me unfortunately, I have tested this code and it didn't retrieve the value from span (maybe because it is inside an embedded form?)
var value = $("#result-fit").text();
var lower = $("#netWorthValue").val(value);
alert(lower.val());
var value = $("#result-fit").text();
var lower = $("#netWorthValue").val(value);
alert(lower.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<p>Your personal net worth</p>
<div class="input-group">
<label>Amount in CDN (Canadian dollar):</label> <input type="number" class="form-control" name="netWorth" title="networth" id="netWorthValue">
<!-- START CODE Attention! Do not modify this code; -->
<script>
var fm = "EUR";
var to = "CAD";
var tz = "timezone";
var sz = "1x1";
var lg = "en";
var st = "info";
var lr = "0";
var rd = "0";
</script>
<a href="https://currencyrate.today/converter-widget" title="Currency Converter">
<script src="//currencyrate.today/converter"></script>
</a>
</div>
Listen for changes to the input and write to the '#result-fit' span.
$(document).ready(function(){
$("#result-fit").on("change", function(e){
$("#netWorthValue").text($(this).val());
})
})

only first paragraph appending javascript

I am attempting to add multiple "p" elements with different inner texts but for some reason only one paragraph element in total is appending, which always seems to be the final one in the code.
My code is shown below. Thanks for the help.
HTML:
<select>
<option>Movie Title</option>
<option>Movie Actor</option>
<option>Genre</option>
<option>Release Year</option>
</select>
<input type="text" id="search">
<button id="submitSearch">SUBMIT</button>
<div id="searchresult">
</div>
JAVASCRIPT:
var searchBtn = document.getElementById("submitSearch");
var userSearch = document.getElementById("search");
var resultDiv = document.getElementById("searchresult");
searchBtn.addEventListener("click",function(){
var userMovie = userSearch.value.toLowerCase();
//removing all white space from title
var arraySearch = userMovie.split(" ");
var convertedSearch = arraySearch.join("");
if (!movies[convertedSearch]){
console.log("Sorry, this does not match any DVD's you own");
} else {
var para = document.createElement("p");
resultDiv.appendChild(para);
para.innerText = "Title: " + movies[convertedSearch].title;
resultDiv.appendChild(para);
para.innerText = "Cast: " + movies[convertedSearch].cast;
}
})
The problem is that you're not asking the browser to append two paragraphs: you're asking it to append the same one (para) twice. No DOM element can be in two places at once, so it is failing.
You need to repeat para = document.createElement("p"); after appending it the first time. That will ask the browser to create two paragraphs and append them both.

Iterating over dynamically generated input field ids and using keyup to get their values in a separate input field

The mandatory div id gets different numbers of inputs field displayed in it dynamically. Each input field starting from the first gets an id attr1, then attr2,..attr[n]. I need a way to get this into an array that gets the value of each input field with keyup and puts them into a separate input field with id detail.
This code works but returns undefined in some case when the hard coded input field ids exceed the generated input field ids. Thanks.
<div id="attributes"> <!--Start of Div Refreshed on Ajax Page Refresh-->
<div id="mandatory">
</div>
</div>
var total = '#attr1, #attr2';
$("#attributes").on('keyup', total, function(){
update();
})
function update() {
$("#detail").val($('#attr1').val() + "," $('#attr2').val());
}
If I understood right your question I think you're looking for something like that:
var fields = $("#mandatory").find("input"),
ids = [];
fields.each(function(){
$(this).on("keyup", function(){
var val = "";
ids = [];
fields.each(function(){
val += $(this).val() + (fields.length === ($(this).index() + 1) ? "": ", ");
ids.push($(this).get(0).id);
});
$("#detail").val(val);
console.log(ids)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="attributes">
<div id="mandatory">
<input id="one" class="one" value="54"/>
<input id="two" class="two" value="55"/>
<input id="three" class="three" value="587"/>
</div>
</div>
<input id="detail" type="text" />
I'm not sure if this is what you're looking for, but I think it'll take you down the right path. In this example, any time a text input field is generated, an input event handler is attached to it that changes the value of a main textarea. If this isn't quite what you're looking for, please let me know and I'll be happy to try to work it out more.
document.getElementById('adder').onclick = function() {
var dynamicTextbox = document.createElement('input');
dynamicTextbox.setAttribute('type', 'text');
dynamicTextbox.setAttribute('class', 'dynamicText');
dynamicTextbox.addEventListener("input", function() {
var allTextboxes = document.getElementsByClassName('dynamicText');
var allValues = '';
for (var i=0; i < allTextboxes.length; i++) {
allValues += allTextboxes[i].value;
}
document.getElementById('detail').value = allValues;
});
document.getElementById('textboxes').appendChild(dynamicTextbox);
}
<textarea id="detail"></textarea>
<input id="adder" type="button" value="Add Text Field" />
<div id="textboxes"></div>

div search form with formatting

I am trying to create a syntax highlighted search field, where certain items are a particular color, bold, underline, etc. when I type. As I type, I would like the word in to become bold. This works with what I currently have, but when in is typed the cursor goes to the beginning of the div, and you can't type anything after the word in either. What can I do to fix this? You can see the jsfiddle here.
The JavaScript:
$(document).on("keyup", "#q", function(){
var val = $(this).text();
val = val.replace(/\sin\s/ig, " <b>in</b> ");
$(this).html(val);
});
The HTML
<div id="q" name="q" class="form-control input-lg" contenteditable="true"></div>
With the rangy library I was able to accomplish this like this:
$(document).on("keyup", "#q", function(){
var savedSel = rangy.saveSelection();
var val = $(this).html();
val = val.replace(/\sin\s/ig, " <b>in</b> ");
$(this).html(val);
rangy.restoreSelection(savedSel);
});

Categories