get different inner html from same class [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 5 years ago.
Can anyone help with how do you get the different innerhtml from the same class into an input text? This is the code. Thanks.
function myFunction() {
var a = document.getElementsByClassName("name");
var b = document.getElementById("whispering");
a.innerHTML = b.value;
}
<span onclick="myFunction();" class="name" id="username1"> Username 1 </span>
<span onclick="myFunction();" class="name" id="username2"> Username 2 </span>
<input type="text" id="whispering">

The issue with your code is that getElementsByClassName returns a collection, so you need to loop through that and set the innerHTML of each individual element:
function myFunction() {
var a = document.getElementsByClassName("name");
var b = document.getElementById("whispering");
for (var i = 0; i < a.length; i++) {
a[i].innerHTML = b.value;
}
}
<span onclick="myFunction();" class="name" id="1"> HAHA1 </span>
<span onclick="myFunction();" class="name" id="2"> Haha2 </span>
<input type="text" id="whispering">

Something like this will do the trick:
a[2].innerHTML = b.value;
Or if you want the specific item clicked, you could do:
HTML:
<span id="1" class="name">Content</span>
<span id="2" class="name">Content</span>
JS:
var spans = document.getElementsByClassName("name");
for(var i = 0; i < spans.length; i++){
spans[i].onclick = function(){
this.innerHTML = b.value;
}
}
NOTE: this also stops the use of inline JS :)
Fiddle: https://jsfiddle.net/yn9wauyk/

You would be better to pass a reference to the clicked element into your method - this solves all problems of referencing the correct element by id or by class.
function myFunction(elem) {
var b = document.getElementById("whispering");
elem.innerHTML = b.value;
}
<span onclick="myFunction(this);"> HAHA1 </span>
<span onclick="myFunction(this);"> Haha2 </span>
<input type="text" id="whispering">

Related

Selecting multiple elements with querySelectorAll and applying event in JavaScript

there is an onchange event on the input and want it to change the value of the spans with the class of "number" whenever it changes so there here is the HTML :
function myFunction() {
var x = document.getElementById("myText").value
document.querySelectorAll(".number").innerText = x
}
<div class="uper-container">
<p>Metric/Imperial unit conversion</p>
<!-- *********************************************************************************************** -->
<!-- this input will change the value of 6's span below with the class of "number" -->
<!-- ********************************************************************************************** -->
<input type="text" id="myText" placeholder="number here" value="20" onchange="myFunction()">
</div>
<div class="lower-container">
<p>Length(Meter/Feet)</p>
<p>
<span class="number"></span> meters = <span class="d"></span>feet |
<span class="number"></span> feet = <span class="d"></span>meters
</p>
<p>Volume(Liters/Gallons)
<</p>
<p>
<span class="number"></span> liter = <span class="d"></span>gallon |
<span class="number"></span> gallon = <span class="d"></span>liter
</p>
<p>Mass(Kilograms/Pounds)</p>
<p>
<span class="number"></span> kilogram = <span class="d"></span>pound |
<span class="number"></span> pound = <span class="d"></span>kilogram
</p>
</div>
so how to make spans with the class="number" have the same value as input id="myText"?
and one thing to mention is that I use scrimba editor.
Unlike jQuery, Vanilla JS will not execute innerText to every node returned by querySelectorAll with an inline call. You would need to loop through them.
The code below should work:
function myFunction() {
var x = document.getElementById("myText").value;
var spans = document.querySelectorAll(".number");
for (let i = 0; i < spans.length; i++) {
spans[i].innerText = x;
}
}
You can also use the for-of loop.
function myFunction() {
const x = document.getElementById("myText").value;
const numberElements = document.querySelectorAll(".number");
for (let element of numberElements) {
element.innerText = x;
}
}

Generating a secret code in the input field after clicking the button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This code does not work and I do not know why I'm learning JavaScripta but I'm doing it for the first time I was also looking for a solution on the internet but I found a similar code generation and what would work
HTML, JavaScript, JQuery
function gencode(length) {
var result = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers = "0123456789"
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
$('#btn-generate').click(function(){
$('#secret-code').val = gencode(8);
});
<div class="form-row">
<div class="form-holder">
<fieldset>
<legend>'.$lang['register']['form']['secret-code']['header'].'</legend>
<input type="text" id="secret-code" name="secret-code" placeholder="'.$lang['register']['form']['example']['secret-code'].'" class="required">
</fieldset>
</div>
<div class="form-holder">
<div class="center">
<a class="btn tooltip tt50 generate" id="btn-generate">
<span class="gencode">
<em>'.$lang['register']['form']['secret-code']['button'].'</em><i id="icon-gencode" class="fa fa-code fa-2x"></i>
</span>
</a>
</div>
</div>
</div>
val() is a method, so to update the value, you can execute the method as:
Set the value of each element in the set of matched elements.
function gencode(length) {
var result = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers = "0123456789"
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
$('#btn-generate').click(function() {
$('#secret-code').val(gencode(8));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<div class="form-holder">
<fieldset>
<legend>Legend</legend>
<input type="text" id="secret-code" name="secret-code" placeholder="" class="required">
</fieldset>
</div>
<div class="form-holder">
<div class="center">
<a class="btn tooltip tt50 generate" id="btn-generate">
<span class="gencode">
Generate
<i id="icon-gencode" class="fa fa-code fa-2x"></i>
</span>
</a>
</div>
</div>
</div>
To set value in jquery you should use val as function
$('#secret-code').val(gencode(8));
$('#secret-code').val(gencode(8));
It simply sets the value of every matched element. You can read all the explanation from the link below:
http://api.jquery.com/val/

Trouble looping through the inputs and adding them

Having an issue with peoplePaid() looping through all the inputs with the .persons class on a page through an add button. I believe this issue is that #paidTotal is trying to add contents from an array in .persons but can't access them (gives me an undefined error in console).
This variable works but only if there's one .persons class with a variable...
var personsCheck = parseFloat(document.getElementsByClassName('persons')[0].value);
However I need it to dynamically loop the values of the array that is created through .persons elements. What am I missing?
function peoplePaid() {
var checkTotal = parseFloat(document.getElementById('check').value);
var personsCheck = document.getElementsByClassName('persons');
var paidTotal = document.getElementById('paidTotal');
for (var i = 1; i < personsCheck.length; i += 1) {
paidTotal += personsCheck[i];
}
paidTotal.innerHTML = checkTotal - personsCheck;
}
$ <input type="text" id="check" value="" />
<h3>Number of People: <span id="numberOfPeople"></span></h3>
<div>
<div id="userNumbers">
<input type="text" class="persons" name="person">
</div>
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
paidTotal is an element. I believe you do not want to use += on the element itself. You should add the total to a variable.
Also, as the index of collections are 0 based, you have to start the value of i from 0. You have to take the value property from each element.
Please Note: It is good practice to use textContent instead of innerHTML when dealing with text only content.
Try the following way:
function peoplePaid() {
var checkTotal = parseFloat(document.getElementById('check').value);
var personsCheck = document.getElementsByClassName('persons');
var paidTotal = document.getElementById('paidTotal');
var pCheck = 0;
for (var i = 0; i < personsCheck.length; i += 1) {
pCheck += personsCheck[i].value;
}
paidTotal.textContent = checkTotal - pCheck;
}
$ <input type="text" id="check" value="" />
<h3>Number of People: <span id="numberOfPeople"></span></h3>
<div>
<div id="userNumbers">
<input type="text" class="persons" name="person">
</div>
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
Some mistakes exists in your code:
paidTotal is an element but in paidTotal += personsCheck[i]; you have used it some a numeric variable.
in your loop, index must starts from zero not one.
in this line: paidTotal += personsCheck[i]; you have added personsCheck[i] element to paidTotal instead of its value.
the corrected code is like this:
function peoplePaid() {
var checkTotal = parseFloat(document.getElementById('check').value);
var personsCheck = document.getElementsByClassName('persons');
var paidTotal = 0;
for (var i = 0; i < personsCheck.length; i += 1) {
paidTotal += personsCheck[i].value * 1;
}
document.getElementById('paidTotal').innerHTML = checkTotal - paidTotal;
}
$ <input type="text" id="check" value="" />
<h3>Number of People: <span id="numberOfPeople"></span></h3>
<div>
<div id="userNumbers">
<input type="text" class="persons" name="person">
</div>
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

dynamically creating div using javascript/jquery

I have two div called "answerdiv 1" & "answerdiv 2" in html.
now i want to give/create div id uniquely like "answerdiv 3" "answerdiv 4" "answerdiv 5" and so on.
Using javascript/jquery how can i append stuff in these dynamically created divs which id should be unique?
in my project user can add "n" numbers of div, there is no strict limit to it.
Help me out.
Thanks in Adv
================================================================================
My HTML code is:
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
My JS code:
function exchangeLabelsanswertxt(element)
{
var result = $(element).val();
if(result!="")
{
$(element).remove();
$("#answertextdiv").append("<label id='answertext' onClick='exchangeFieldanswertxt(this);'>"+result+"</label>");
}
}
function exchangeFieldanswertxt(element)
{
var result = element.innerHTML;
$(element).remove();
$("#answertextdiv").append("<textarea id='answertext' name='answertext' placeholder='Type answer here' rows='2' cols='40' tabindex='6' onBlur='exchangeLabelsanswertxt(this);'>"+result+"</textarea>");
}
Now from above code I want to append all stuff in unique "answertextdiv" id.
If your divs are in a container like:
<div id="container">
<div id="answerdiv 1"></div>
<div id="answerdiv 2"></div>
</div>
you could do something like:
//Call this whenever you need a new answerdiv added
var $container = $("container");
$container.append('<div id="answerdiv ' + $container.children().length + 1 + '"></div>');
If possible, try not to use global variables...they'll eventually come back to bite you and you don't really need a global variable in this case.
You can try something like this to create divs with unique ids.
HTML
<input type="button" value="Insert Div" onClick="insertDiv()" />
<div class="container">
<div id="answerdiv-1">This is div with id 1</div>
<div id="answerdiv-2">This is div with id 2</div>
</div>
JavaScript
var i=2;
function insertDiv(){
for(i;i<10;i++)
{
var d_id = i+1;
$( "<div id='answerdiv-"+d_id+"'>This is div with id "+d_id+"</div>" ).insertAfter( "#answerdiv-"+i );
}
}
Here is the DEMO
You should keep a "global" variable in Javascript, with the number of divs created, and each time you create divs you will increment that.
Example code:
<script type="text/javascript">
var divCount = 0;
function addDiv(parentElement, numberOfDivs) {
for(var i = 0; i < numberOfDivs; i++) {
var d = document.createElement("div");
d.setAttribute("id", "answerdiv"+divCount);
parentElement.appendChild(d);
divCount++;
}
}
</script>
And please keep in mind that jQuery is not necessary to do a lot of things in Javascript. It is just a library to help you "write less and do more".
I used below JQuery code for the same
$("#qnty1").on("input",function(e)
{
var qnt = $(this).val();
for (var i = 0; i < qnt; i++) {
var html = $('<div class="col-lg-6 p0 aemail1"style="margin-bottom:15px;"><input type="text" onkeyup= anyfun(this) class="" name="email1'+i+'" id="mail'+i+'" > </div><div id=" mail'+i+'" class="lft-pa img'+i+' mail'+i+'" > <img class="" src="img/btn.jpg" alt="Logo" > </div> <div id="emailer1'+i+'" class=" mailid "></div>');
var $html=$(html);
$html.attr('name', 'email'+i);
$('.email1').append($html);
}
}
my HTML contain text box like below.
<input type="text" name="qnty1" id="qnty1" class="" >
and
<div class="email1">
</div>
you need a global counter (more generally: a unique id generator) to produce the ids, either explicitly or implicitly (the latter eg. by selecting the last of the generated divs, identified by a class or their id prefix).
then try
var newdiv = null; // replace by div-generating code
$(newdiv).attr('id', 'answerdiv' + global_counter++);
$("#parent").append(newdiv); // or wherever
var newdivcount=0;
function insertDivs(){
newdivcount=newdivcount+1;
var id="answerdiv-"+(newdivcount);
var div=document.createElement("DIV");
div.setAttribute("ID",id);
var input=document.createElement("TEXTAREA");
div.appendChild(input);
document.getElementById('container').appendChild(input);
}
<button onclick="insertDivs">InsertDivs</button>
<br>
<div id="container">
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
</div>
Here is the another way you can try
// you can use dynamic Content
var dynamicContent = "Div NO ";
// no of div you want
var noOfdiv = 20;
for(var i = 1; i<=noOfdiv; i++){
$('.parent').append("<div class='newdiv"+i+"'>"+dynamicContent+i+"</div>" )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
</div>

Jquery: How to reorder DIVs after removing a single Div?

I am working on an application in which contains a few DIVs having IDs like a1,a2,a3 etc.
There is option of navigation DIVs by hitting next and previous button which brings one Div on screen at a time. strong text There are two more actions: Add and Remove. Add adds a Div with ID greated than last ID, for instance if last DIV id was a3 then Add brings a4.
The real issue is removing current DIV. If the user is on Div a2 and hits Remove option then it deletes the current Div by using .remove() method of jQuery
Now navigation breaks because it is sequential. It tries to find Div a2 but does not find. What I think that Ids of all remaining DIVs should be renamed. Since there is no a2 so a3 should become a2 and so on. How can I do that? Code doing different tasks is given below:
function removeQuestion()
{
$("#_a"+answerIndex).remove();
if(answerIndex > 1)
{
if ($("#_a"+(++answerIndex)).length > 0)
{
$("#_a"+answerIndex).appendTo("#answerPanel");
}
else if($("#_a"+(--answerIndex)).length)
{
$("#_a"+answerIndex).appendTo("#answerPanel");
}
totalOptions--;
}
}
function addQuestion()
{
var newId = 0;
totalOptions++;
var d = 1;
newId = totalOptions;
var _elemnew = '_a'+newId;
$("#_a"+d).clone().attr('id', '_a'+(newId) ).appendTo("#answers_cache");
var h = '<input onclick="openNote()" id="_note'+newId+'" type="button" value=" xx" />';
$("#"+_elemnew+" .explain").html(h)
$("#"+_elemnew+" ._baab").attr("id","_baab"+newId);
$("#"+_elemnew+" ._fx").attr("id","_fasal"+newId);
$("#"+_elemnew+" .topic_x").attr("id","_t"+newId);
$("#"+_elemnew+" .topic_x").attr("name","_t"+newId);
$("#"+_elemnew+" .answerbox").attr("id","_ans"+newId);
$("#"+_elemnew+" .block").attr("onclick","openFullScreen('_ans"+newId+"')");
$('.tree').click( function()
{
toggleTree();
}
);
$('.popclose').click( function()
{
unloadPopupBox();
}
);
}
function next()
{
console.log("Next ->");
if(answerIndex < totalOptions)
{
answerIndex++;
console.log(answerIndex);
setInitialAnswerPanel();
}
}
function previous()
{
console.log("Next <-");
if(answerIndex > 1)
{
answerIndex--;
console.log(answerIndex);
setInitialAnswerPanel();
}
}
Html of Composite DIV is given below:
<div class="answers" id="_a1" index="1">
<input placeholder="dd" id="_t1" type="text" name="_t1" class="urduinput topic_masla" value="" />
<img class="tree" onclick="" src="tree.png" border="0" />
<label class="redlabel">
xx :
</label>
<label id="_baab1" class="baabfasal _baab">
</label>
<label class="redlabel">
xx :
</label>
<label id="_fasal1" class="baabfasal _fasal">
</label>
<a title=" ddd" class="block" href="#" onclick="openFullScreen('_ans1')">
<img src="fullscreen.png" border="0" />
</a>
<textarea id="_ans1" class="answerbox" cols="40" rows="15"></textarea>
<span class="explain">
<input onclick="openNote()" id="_note1" type="button" value=" xx" />
</span>
<span style="float:left;padding-top:5%">
plus | <a onclick="removeQuestion()" href="#">minus</a>
</span>
</div>
Why don't you keep currently opened page instead of the index and search for previous and next pages using prev() and next() jQuery tree traversal methods?
Select all div elements containing questions, preferable with a css class selector, use the each method, and assign new ids to them:
$('.questionDiv').each(function(index) { $(this).attr('id', 'a' + (index + 1)); })
That should be enough.
var originalSet = $('.answers');
var container = originalSet.up() ;
var byId = function(a, b){
return $(a).attr('id') > $(b).attr('id') ? 1 : -1;
}
originalSet
.order(byId)
.each(function rearrangeIds(position){
$(this).attr({
'index': poition,
'id': '_a'+position
});
}).appendTo(container)

Categories