How can I set a value of an element with JQuery from an object $this?
I have some divs of class "A"
<div class="A">
<span name='B'>some text</span>
<div>
<input name='value_1' value='15'/>
<input name='value_2' value='9'/>
</div>
</div>
<div class="A">
<span name='B'>some other text</span>
<div>
<input name='value_1' value='7'/>
<input name='value_2' value='12'/>
</div>
</div>
...more divs like those
I'm trying to set the text of the spans of name B with the greater value of their inputs (inputs 'value_1' and 'value_2').
But what I'm trying seems to fail, this is the js (using jquery):
function setSpans(){
var value1=0;
var value2=0;
var setting_value = 0;
$('.A').each(function(){
value1 = $(this).find("input[name='value_1']").val();
value2 = $(this).find("input[name='value_2']").val();
if(value1 > value2)
setting_value = value1;
else
setting_value = value2;
//here comes what I can't accomplish
$(this).find("span[name='B']").text(setting_value);
});
}
All you need to do is to cast string values to numbers before you compare them:
var value1 = Number($(this).find("input[name='value_1']").val());
var value2 = Number($(this).find("input[name='value_2']").val());
Remember that value of the input field is always a string and of course string "9" is greater then "15".
Demo: http://jsfiddle.net/ck64v16t/
Two problems that I see:
time of setSpans call. It has to be after used elements are already in DOM - either by using document.ready or by placing script after these elements in page.
values of inputs are Strings, so you can use, for example, parseInt to compare values as Numbers.
Workable example:
Fiddle.
HTML:
<div class="A">
<span name='B'>some text</span>
<div>
<input name='value_1' value='15'>
<input name='value_2' value='9'>
</div>
</div>
<div class="A">
<span name='B'>some other text</span>
<div>
<input name='value_1' value='7'>
<input name='value_2' value='12'>
</div>
</div>
JS:
$(document).ready(setSpans);
function setSpans()
{
var value1 = 0;
var value2 = 0;
var setting_value = 0;
$('.A').each(function()
{
value1 = parseInt($(this).find("input[name='value_1']").val());
value2 = parseInt($(this).find("input[name='value_2']").val());
if (value1 > value2)
{
setting_value = value1;
}
else
{
setting_value = value2;
}
$(this).find("span[name='B']").text(setting_value);
});
}
Related
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;
}
}
I have a div as follows:
<div class="questionholder" id="question5" style="display:none">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
The user is expected to select all the checkboxes that apply to his situation. Let's assume he selects all 3.
When he clicks "Next", the function displayquestion(); will fire.
function displayquestion(a) {
var Elements = '';
var b = a - 1;
Elements = document.querySelector("#question" + b + " input[name=ID1element]").value;
}
Basically, the function is meant to store all the checked values into var Elements, which is meant to be an array.
However, I'm only getting the value of the first selected answer instead of an array of all selected answers.
How do I grab all the selected answers into an array?
No jQuery please.
Use querySelectorAll to get an array-like NodeList instead of querySelector, and then you can use Array.from to transform that NodeList into an array containing only the .value of the selected inputs:
function displayquestion(a) {
const b = a - 1;
const elements = Array.from(
document.querySelectorAll('#question' + b + ' input:checked'),
input => input.value
);
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
Here is the script that you can use for that:
I haven't changed anything in your HTML structure. Except I have removed the display: none; from the style attribute of the class questionholder.
<script>
function displayquestion(b) {
let checkboxList = document.querySelectorAll("#question" + b + " input:checked");
let obj = [];
if (checkboxList.length > 0) { //Code works only if some checbox is checked
checkboxList.forEach(function(item) {
obj.push(item.value); //Contains the value of all the selected checkboxes.
});
}
console.log(obj); //array list containing all the selected values
}
</script>
<div class="questionholder" id="question5" style="">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(5);">Next</a>
</div>
Here is a JSFiddle link for that.
I hope this is helpful.
So first of I would make a variable for your
<a class="text2button">Next</a>. And I have removed the
onclick="displayquestion(6)" from your html.
Here is the variable.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
Here we have the function, so what I've done is.
I have created a variable var elements = []; Which is a empty array.
Then I create this variable var inputs = document.getElementsByClassName("input5");
This variable gets all the inputs with class input5.
Next I would loop through each of the inputs from the var inputs. Like this.
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
So what I do here is loop through each input for (var i = 0; i < inputs.length; i++) and then I check if any of the inputs are checked if (inputs[i].checked), then I push them to the array var elements with elements.push(inputs[i].value);.
And then I use console.log(elements); so show it in the console.
Check out the snippet below to see it in effect.
Hope this helps.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
function displayquestion() {
var elements = [];
var inputs = document.getElementsByClassName("input5");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button">Next</a>
</div>
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>
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">
I have a set of number fields, each with a class "product-quantity", and a set of empty divs. the number fields are set with a data-attr small, medium, and goes up to 5xl. The empty div's are set with a data-attr small, medium, and goes up to 5xl as well because the small number field is associated with the small div and so one.
When you increase or decrease the number inside the small number field a div "small" should insert after the empty div with the attr small.
When you increase or decrease the number inside the medium number field a div "medium" should insert after the empty div with the attr medium.... and so on
additionally, all of the above belongs to a product x container, and there are multiple products on a page.
I have this jsfiddle that simulates what I am trying to do:
http://jsfiddle.net/7PhJZ/25/
however, right now when I add/subtract a number to the small number fields, it adds/subtracts a div to both the empty small/ medium div as well as in both products. and same for the medium.
I am having a hard time trying to associate which number field belongs to which empty div, which belongs to which product.
html:
<div id="product-1">
<div class="size-field">
<div id="size-label">
s
</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small" min="0"
max="9999" data-product-id="1">
</input>
</div>
</div>
<div id="size-label">
m
</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number" name="Medium"
min="0" max="9999" data-product-id="1">
</input>
</div>
<div class="name-number-header"><h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
<br clear="all">
<div id="product-2">
<div class="size-field">
<div id="size-label">
s
</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small" min="0"
max="9999" data-product-id="2">
</input>
</div>
</div>
<div id="size-label">
m
</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number" name="Medium"
min="0" max="9999" data-product-id="2">
</input>
</div>
<div class="name-number-header"><h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
js:
$('.product-quantity').on('change',function(){
$('.name-number-field').remove();
var val = $(this).val();
for (var i = 0; i < parseInt(val); i++){
$('<div/>',{'class':'name-number-field'}).insertAfter($("[data-size]"));
}
});
$('.product-quantity').on('change', function () {
var val = $(this).val(),
ele = $(this).closest('[id^="product"]').find('[data-size="'+this.name+'"]');
ele.nextUntil('[data-size]').remove();
for (var i = 0; i < parseInt(val); i++) {
$('<div/>', {
'class': 'name-number-field'
}).insertAfter(ele);
}
});
FIDDLE
EDIT:
Based on the comments, what you're really trying to do is just add one if the value increments, and remove the last if the value decrements, and for that the approach would be somewhat different:
$('.product-quantity').each(function() {
$(this).data('val', this.value);
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val'),
ele = $(this).closest('[id^="product"]').find('[data-size="'+this.name+'"]'),
inc = val >= old;
if (inc) {
$('<div/>', {
'class': 'name-number-field'
}).insertAfter(ele);
}else {
$('.name-number-field', ele.parent()).last().remove();
}
$(this).data('val', this.value);
});
FIDDLE
Make Use of your data-product-id and hook the textbox's parent and target the required elements.
Try this,
$('.product-quantity').on('change',function(){
$('.name-number-field').remove();
var val = $(this).val();
for (var i = 0; i < parseInt(val); i++){
$('<div/>',{'class':'name-number-field'})
.insertAfter($(this).parents('#product-' + $(this).data('product-id')).find("[data-size]"));
}
});
DEMO
Edit:
$('.product-quantity').on('change',function(){
$('.name-number-field').remove();
var val = $(this).val();
for (var i = 0; i < parseInt(val); i++){
$('<div/>',{'class':'name-number-field'})
.insertAfter($(this).parents('#product-' + $(this).data('product-id')).find("[data-size='"+ $(this).attr('name') +"'][data-size]"));
}
});
NEW - DEMO