Get value of span element and output it - javascript

Ok, I am more than impressed that you guys took your time to answer this, thank you so much, I did not expect it. Hope well follows you.
To explain my problem, I used that fiddle tool you all had. This is the code I have:
enter code here
http://jsfiddle.net/5xzSy/1/
-What I need, is to sum up the values that get calculated in the spans : budgetI + actualI

Modified your code to : Use .text() to populate the Span and assign some value to your inputs..(Since you have used jQuery)
http://jsfiddle.net/xubam99v/
HTML Code
<pre>
<input id=primaryB type="text" value="100"></input><input id=primaryA type="text" value="100"></input><span id=primary></span><br />
<input id=spouseB type="text" value="100"></input><input id=spouseA type="text" value="100"></input><span id=spouse></span><br />
Budget: <span id=budget></span> <br />
Actual: <span id=actual></span><br />
</pre>
Javascript/jQuery Code
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').text(primaryBValue + spouseBValue);
$('#actual').text(primaryAValue + spouseAValue);

listen on the change-event to sum numbers after you insert then
http://jsfiddle.net/55c5uqhc/2/
$('#primaryB,#primaryA,#spouseB,#spouseA').change(calc);
function calc() {
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').html(primaryBValue + spouseBValue);
$('#actual').html(primaryAValue + spouseAValue) ;
}

You need to create a trigger upon which you populate the <span>s, also use text() instead oh html()
Here's example(probably a bad one but it's good place to start):
function:
$('input').keyup(function(e){
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#spouse').text(spouseBValue - (-spouseAValue));
$('#primary').text(primaryBValue - (-primaryAValue));
$('#budget').text(primaryBValue - (-spouseBValue));
$('#actual').text(primaryAValue - (-spouseAValue));
});
fiddle

Related

Issues with javascript using html inputs as variables (Beginner!)

Hello Everyone!
Im having some issues with a simple calculator type website. My issue involves using a javascript function to calculate an equation using variables from an HTML input form.
Below is my javascript function, which is placed above the form in the HTML file.
var userName = document.getElementsByName("userName")[0].value;
var userMmr = document.getElementsByName("userMmr")[0].value;
var userDesmmr = document.getElementsByName("userDesmmr")[0].value;
var userWinrate = document.getElementsByName("userWinrate")[0].value;
function findshit(){
alert(userMmr.value);
var LR = 1.0 - userWinrate.value;
var GP = 1;
while (1){
var GW = GP * userWinrate.value;
var GL = GP * LR;
var MMRG = GW * 25;
var MMRL = GL * 25;
var TMG = MMRG - MMRL;
if (TMG + userMmr.value >= userDesmmr.value) {
alert("Congrats! it will take you " + String(GP));
} else {
GP += 1;
}
}
}
<h2>Enter your information below</h2>
</br>
<form>
What's your name?:<br>
<input type="text" name="userName" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current mmr?:<br>
<input type="text" name="userMmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your desired mmr?:<br>
<input type="text" name="userDesmmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current win rate?<br>(put in decimal form eg. 50% = .50):<br>
<input type="text" name="userWinrate" onkeyup="findshit();" onchange="findshit();"/"><br>
<br>
<button onclick="findshit();">Try it</button>
Don't use .value when you set all the variables at the top. The code in the function expects those variables to just be the elements, because it uses .value to get their updated values. So it should just be:
var userName = document.getElementsByName("userName")[0];
var userMmr = document.getElementsByName("userMmr")[0];
var userDesmmr = document.getElementsByName("userDesmmr")[0];
var userWinrate = document.getElementsByName("userWinrate")[0];
You also need to put the script after the HTML, or put all the code inside the window.onload function. If you run the script before the HTML is loaded, none of the document.getElementsByName() calls will find the elements.
You should remove or modify while (1) loop. Because it is an infinite loop. I think you should use If loop in the scenario.

Can't grab value from hidden element

For some reason I get a javascript on the following code:
var teamOne = "";
var teamTwo = "";
var children = $(this).find(".team-url");
if (children.length === 2) {
teamOne = children[0].val();
teamTwo = children[1].val();
}
alert(teamOne + " - " + teamTwo);
The error is on .val() The code finds 2 elements and then it can't take the value. If I remove .val() I get it saying it is an [Object HTMLInputElement]
The error is
Uncaught TypeError: children[0].val is not a function
Note:
I Know that I can get this code to work by doing the following:
var teamOne = "";
var teamTwo = "";
var children = $(this).find(".team-url");
if (children.length === 2) {
teamOne = children.first().val();
teamTwo = children.last().val();
}
alert(teamOne + " - " + teamTwo);
However, I am trying to understand why my first version doesn't work so that I can have a better understanding of these functions.
EDIT:
HTML
<div class="col-md-12 game" style="margin-top: 10px">
<div class="team-details">Team Saturn
<input type="hidden" class="team-url" value="TeamSaturn">
</div>
<div class="team-details">Team Datarnan
<input type="hidden" class="team-url" value="TeamDatarnan">
</div>
</div>
Try this:
HTML
<input type="hidden" value="value 1" class="team-url" />
<input type="hidden" value="value 2" class="team-url" />
JS
var teamOne = "";
var teamTwo = "";
var children = $('body').find(".team-url");
if (children.length === 2) {
debugger;
teamOne = children[0].value;
teamTwo = children[1].value;
}
alert(teamOne + " - " + teamTwo);
In your code "$(this)" is not in the real context, and I have changed it with a global search in "body".
The JSFiddle
There is no function val on a HTMLInputElement Object. As children[0] is not a jQuery element you can not use the jQuery function val on it. But you can use the native javascript for this:
You can use teamOne = children[0].value;
First thing is that children[0] returns the DOM element not jQuery object, so you need to use children[0].value instead. To get a jQuery object, you should use .eq(0), .first(), .last() etc.
Second is that $(this).find() has no context. You could use either $('body').find(".team-url") or just $(".team-url")

Getting values from list<String> , split them and then slice them by parts, using JavaScript

I have List<String> from Spring MVC which i want to split, slice and print on browser. The problem is that i need to enter a start and end argument of slice() method as a variable from text-field. This is my code, but it doesn't work. Can someone helps me with that? This is my code:
<body>
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction()">Press</button>
<p id="demos"></p>
</form>
<script>
function myFunction() {
var str = "${first}";
var arr = str.split(",");
var first = document.getElementById('firstvalue');
var second = document.getElementById('lastvalue');
document.getElementById("demos").innerHTML = arr.slice('first', 'second');
}
</script>
</body>
Thank you in advance!
you got some issues in your code.
if ${first} is List<String>, then you need to convert it to a concatenated single comma separated String. Because by ${first} you are just printing list object.
slice expects index which is number, you are passing String
You are not doing .value after document.getElementById
You are not passing the user input variables first and second to slice, Instead you are passing hardcoded strings 'first' and 'second'.
Below is the fixed code
HTML
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction(event)">Press</button>
<p id="demos"></p>
</form>
JS
var myFunction = function (e) {
var str = "${first}" // assuming this contains string like "1,2,3,4,5,6,7,8,9,10"; and not the List obect
var arr = str.split(",");
var first = document.getElementById('firstvalue').value;
var second = document.getElementById('lastvalue').value;
document.getElementById("demos").innerHTML = arr.slice(parseInt(first, 10), parseInt(second, 10)).toString();
e.preventDefault();
};
What do we want to achieve?
We have two input textfields: one holding a start value and one holding an end value. On a click we want to create a range from the start to the end value and output it into a container.
Solution
The solution is more simple than expected and we do not require split, slice and part. Also we do not really require a predefined list holding all values.
Example
<html>
<head>
<script>
function evalRange(){
var tS = parseInt(document.querySelector('#inFrom').value); //Our start value;
var tE = parseInt(document.querySelector('#inTo').value); //Our end value;
var tR = document.querySelector('#demos'); //Our output div
if (tE >= tS){
//We are using the Array.apply prototype to create a range
var tL = Array.apply(null, Array(tE - tS + 1)).map(function (a, i){return tS + i});
//We output the range into the demos div
tR.innerHTML = tL.join(',')
}
else tR.innerHTML = 'To has to be higher than from';
//Returning the range list
return tL
}
</script>
</head>
<body>
<input type = 'text' id = 'inFrom' value = '10' />
<input type = 'text' id = 'inTo' value = '20' />
<b onclick = 'evalRange()'>Range</b>
<div id = 'demos'></div>
</body>
</html>
And here is a fiddle for it: https://jsfiddle.net/91v3jg66/

Get last part of the url

Trying to get the last part of the url in a pretty weird html structure. Don't ask why it's built that way. There is a very good reason behind it.
The html looks like this
<li class="lifilter"><input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js i'm trying to use
$('#Cheeks... label a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = url.split("/");
var finalvar = urlsplit[4];
$(this).addClass(finalvar);
});
edit: damn.. i can only post once every 90 minutes.
here is updated question with updated html
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js code i'm trying to use (from a previous answer)
$('.lifilter').each(function(){
$(this).find(".filtercheck").next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
OK, so it appears no one here attempted to try the solution here before posting.
First things first cheeks.... This is a tricky ID to find (You have to escape the periods). The label is also not part of the internal html where ID is cheeks..., so we need to find the adjacent element and look the a anchor tag you're looking for.
Here's the code:
$(document).ready(function() {
$('#Cheeks\\.\\.\\.').next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
And here is a working jsfiddle with the solution.
keeping it simple like your code you'd do
finalvar = urlsplit[urlsplit.length-1];
in case you don't want the base url as a valid return then:
finalvar = ( urlsplit.length > 1 ? urlsplit[urlsplit.length-1] : "" );
replace "" with your preferred error/default return
you could also try to find the index of the last '/' and do a substring.
try this.
FIDDLE DEMO
var URI = 'www.example.com/sub1/sub2/sub3/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
//RESULT : "sub3"
You can extract the last section of a path (i.e. everything after the last /) by using a regular expression:
text.replace(/.*\//g, "")
This will remove all of the text before a slash, as well as the slash itself. You'll also notice that your selector wasn't matching any elements; you're looking for labels nested within inputs, which doesn't match the html you posted (and isn't a valid DOM structure). An appropriate selector would be .lifilter label a, since the <label> is within the <li>.
$(function() {
setTimeout(function() {
$('.lifilter label a').each(function() {
// strip everything up to and including the last forward slash
var path = $(this).attr('href').replace(/.*\//g, "");
$(this).addClass(path);
});
}, 1500);
});
a.cheeks:after {
content: " (className = 'cheeks')";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
if you want the last section of url for example activation code or id.You can try this.
var url = 'www.abc.com/code=12345',
parts = url.split('='),
lastPart = parts.pop()
//lastPart = 12345

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Categories

Resources