What i'm trying to do is taking the price of every input checked, making a sum out of it.
Here's my code
function totalSum(e) {
e.preventDefault();
var unit = $("input:checked").parent("dt").siblings("dd").find("span");
total = 0;
$.each(unit, function(index, obj){
total += parseInt($(obj).text(), 10);
});
$("#totalPrice").html('<span class="count">€ ' + total + '</span> €');
}
Every unit is found inside its span. Total is set to 0. I try to call a parseInt on each checked object, then add the total inside a span. In HTML, price is stated like that:
<dd><span class="costo">€199</span></dd>
So as you see there is the Euro mark. I am afraid it could not be parsed, is this it? Because nothing change! How should I write it?
Thanks in advance
Ok I feel so ashamed but I cannot get it to work. I decided to put the code at its minimum, so I tried that way
<body>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div id="total"></div>
<script type="text/javascript" src="js/jquery-1.9.0.min.js" /></script>
<script>
$(document).ready(function(){
function sum() {
var prices = $("div.bla").find(".count");
total= 0;
$.each(prices, function(index, obj){
total += parseFloat($(obj).text());
});
$("#total").html('<span class="count">'+total +'</span> €');
};
});
This should work, yet nothing appear. Could someone be so kind to tell me what's going wrong?!
You can just replace any non-numeric characters:
total += parseInt($(obj).text().replace(/[^\d.-]/, ''), 10);
Also, you can do unit.each() instead of $.each(unit, but that has no effect on what you're trying to do.
You can simply remove the unit from the text :
var text = $(obj).text().replace(/[€\$]/,''); // add other units if needed
total += parseInt(text, 10); // are you sure you don't prefer parseFloat ?
Or, if you want to only keep digits and + and -, do
var text = $(obj).text().replace(/[^\d\-\+]/g, '');
Change your parseInt to skip the first character.
total += parseInt($(obj).text().substring(1),10);
After a couple of days trying and reading the best way to do it, I believe this could be an elegant solution of what I was trying to achieve :)
$("input").on("click", function() {
var j = $("input:checked");
t = 0;
$(j).each(function() {
t += parseInt(this.value, 10);
});
$("#total").html("<span>€ " + t + "</span>");
});
Related
Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better
I have a page of items with various prices in GBP, each price is within a span with a class of price, what I would like to do is change the value of ALL the prices to that value divided by 1.2. so along the lines of
$('.price').html() / "1.2";
now i'm aware that this won't work as the format is £10,500 for example, I havent been able to find similar here but i'd like to take that £10,500 value divide it by 1.2 and have the value update to the result (£8,750). Anything I have tried thus far leaves me with NaN and i'm struggling to make progress.
Add a button for testing:
<button id="test-button">Test Currencies</button>
Add the following jQuery:
$('#test-button').on('click', function () {
// Get currency elements
var currencies = $('.price');
var newSymbol = '£';
var eRate = 0.8333;
$.each(currencies, function (index, value) {
// Change value to a number using regex
var number = Number($(this).html().replace(/[^0-9\.]+/g, ""));
// Assign new value and add number formatting
$(this).html(newSymbol + (number * eRate).toFixed(2).toLocaleString('en'));
});
});
Hope it helps.
Here you go :-)
Tested and working.
$("span").each(function()
{
var strNewString = $(this).html().replace(',','');
$(this).html(strNewString / 1.2);
});
function format_price(_input_str){
var input_str=_input_str+''; //if input integer convert to string
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if exist spaces
input_str=input_str.replace(new RegExp('£',"g"), ''); //if exist simbil £
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if wxist
var input_int = parseInt(input_str)||0;
if(input_int==0){ return _input_str;} //return original string
input_str=input_int+'';
var out_str='';
while(input_str.length > 3){
out_str=input_str.substr(-3)+' '+out_str;
input_str=input_str.substr(0,input_str.length-3);
}
if(input_str.length>0){out_str=input_str+' '+out_str;}
out_str='£ '+out_str;
return out_str;
}
$('.price').each(function(){
var this_price=$(this).html();
$(this).html(format_price(this_price));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price">12345</div>
<div class="price">76 09</div>
<div class="price">4576 09</div>
<div class="price">45</div>
<div class="price">£ 12 345 678 </div>
MyServlet forwards to Mypage.jsp as
request.getRequestDispatcher("/pages_homepage.jsp?value="+count).forward(request, response);
where count is an integer value generated
Below is my JSP code(Mypage.jsp),
<body onload="getPage('<%request.getParameter("value");%>')">
<div id="app"></div>
</body>
Below is my javascript code,
function getPage(match){
var arr = new Array();
var ele = document.getElementById('app');
for(var i=0;i<match;i++){
var newdiv = document.createElement("label");
newdiv.id = arr[i];
newdiv.value="Page";
ele.appendChild(newdiv);
}
}
What I want is that, I want 'Page' to be displayed 'match' number of times. But I'm not being able to do so by the above code. Their might be something wrong with my js code. Can anyone suggest me any corrections?
Thanks in advance.
LIVE DEMO
Taking in consideration that your page has something like:
<body onload="getPage(5)">
function getPage(n) {
var ele = $('#app');
var labels = ""; // An empty string will be populated with labels elements:
for(var i=0; i<n; i++){
labels += '<label id="'+ i +'"> Page </label>'
}
ele.append( labels ); // append only once outside the loop!
}
The result will be:
<label id="0"></label>
<label id="1"></label>
<label id="2"></label>
<label id="3"></label>
<label id="4"></label>
If you want to start from 1 instead of 0 use:
labels += '<label id="'+ (i+1) +'"> Page </label>'
Note: ID starting with (/ containing only) a number - is only valid in HTML5
Your Code is working and i have tested it
Since you don't have any content in the label tag hence it is not visible in browser
Secondly a small error
in 6th line of js code
newdiv.id = arr[i];
arr[i] is not given any value hence change it with
newdiv.id = i;
enjoy your code
Thanks everyone for their help but I think I got the answer,
Instead of
<body onload="getPage('<%request.getParameter("value");%>')">
I wrote,
<body onload="getPage('<%=Integer.parseInt(request.getParameter("value"))%>')">
But thanks everyone again for their useful pointers.
I'm pretty stuck on how this should be achieved, mostly down to my lack of javascript knowledge. This is the code I'm looking at:
http://jsfiddle.net/spadez/VrGau/
What I'm trying to do is have it so a user can type add a "responsibility" in the responsibility field, then click add and have it appear in a list above it. The user can do this for up to 10 responsibilities.
The result would look something like this:
**Responsibility List:**
- Added responsibility 1
- Added responsibilty 2
*responsibility field - add button*
Can anyone explain how this should be done, it seems like it would have to involve ajax. I would really appreciate some more information or even an example.
Thank you.
EDIT: Here is a little bit more clarification. I want this data to be sent to the server as a list of items. I have seen examples of this being implemented, and here is a screenshot:
The user types in something in the text box, then clicks "add" and then it appears in a list above it. This information is what is submitted to the server.
Maybe this one can help also, this limits only 10 list
var eachline='';
$("#send").click(function(){
var lines = $('#Responsibilities').val().split('\n');
var lines2 = $('#Overview').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += '- Added ' + lines[i] + '\n';
}
}
$('#Overview').text(eachline);
$('#Responsibilities').val('');
});
Try it here
http://jsfiddle.net/markipe/ZTuDJ/14/
Something like that maybe?
http://jsfiddle.net/VrGau/10/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#send'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
$responsibilityList.val(newVal+'\n');
$responsibilityInput.val('');
}
}
$inputButton.click(addResponsibility);
Add id for textarea fields
<textarea rows="4" cols="50" placeholder="Responsibilities" id="resplist"></textarea>Add responsibility<br />
<textarea rows="4" cols="50" placeholder="How to apply" id="inputresp"></textarea>
You need Jquery. Use this js code
var i=0;
$("#send").click(addresp);
function addresp()
{
if (i<10)
{
$("#resplist").val($("#resplist").val()+$("#inputresp").val()+'\n');
$("#inputresp").val("");
i++;
}
}
http://jsfiddle.net/br0nsk1y/bDE9W/
It depends on if you want to post data to the server or not. If only in the client side you can do like this.
$("#send").on("click", function(event){
if($("#list li").size() < 10){
$("#list").append("<li>" + $("#responsibilities").val() + "</li>");
}
});
http://jsfiddle.net/VrGau/7/
I am going to have to repost my previous question because I need to reformulate what I need.
So, here it goes.
I have a webpage containing some list items,
HTML
<div class="container">
<p>Items are ordered Alphabetically and I want the text to be untouched</p>
</div>
All of these list items are contained in a folder on my computer. What I want to do is not have to manually input the ../Html/1.html , ../Html/2.html, ... instead, I was hoping to find a script to do the job for me.
All the items are numbered in numerical order, starting at 1 all the way to 100.
So I know iterating using i++ might come in handy in a loop. But I really dont know more than that!
Use this:
<div id="theContainer" class="container">
<p>Items are ordered Alphabetically and I want the text to be untouched</p>
</div>
<script>
window.addEventListener('DOMContentLoaded', function() {
var container = document.getElementById('theContainer'), i, p, s;
var numStart = 1, numEnd = 100;
var path = '../Html/*.html'; //use "*" to substitute the number
for (i = numStart; i <= numEnd; i++) {
p = path.replace(/\*/,i);
s += '<li>' + p + '</li>';
}
container.innerHTML = container.innerHTML + '<ol>' + s + '</ol>';
}, false);
</script>