Pass text within a div (number) through calculation in real time? - javascript

For lack of a better title, I'm looking to take the example I have in my jsfiddle, and convert it to pull the number that's within a div (it will always be a number):
<div class="output" id="i1">100</div>
And pass that number through a formula, to spit it out in real time to a p tag (doesn't need to be a p tag, could be another div.
<p>200</p> or <div id="i2">200</div>
Where the 200 above, is calculated by adding the original value of the div id #i1, plus 100. Right now, the fiddle shows that when you enter in a value for the input, it spits out the real time calculation.
So the question is, what would it look like where instead of an input value, the function would be pulling the numerical data out of the DIV tag, running it through a function, and spitting it back out into a paragraph tag? I think the bulk of it is completed functionality wise, but can't quite figure out the pulling from DIV text.
Some posts I've looked at already include this one about real time inputs, this one on calculations and displaying, and a few others on here.
SOLUTION
This fiddle shows the solution for me. It's far simpler than I had before. There was a solution given below regarding a listener plugin, which looked pretty good, but way overkill for what I needed.

You may consider using a Observer pattern here.
Check this for more. http://canjs.us/#can_observe

to get the text from a div and then parse it to a float, use this:
parseFloat(document.getElementById('i1').childNodes[0].nodeValue)

This fiddle shows the solution for me. It's far simpler than I had before. There was a solution given below regarding a listener plugin, which looked pretty good, but way overkill for what I needed.
<form id="vcForm">
<div id="i1">100</div>
<p></p>
</form>
​
$("#i1").keyup(function() {
var input1 = parseFloat($("#i1").text(),10);
var input2 = 100;
total1 = parseFloat(input1) + parseFloat(input2);
$("p").text(total1);
}).keyup()​
The value in that first DIV will be dynamic (changing via a slider). Of course, we'll see about real time updates when I expand this out functionally, but for my original question, this answered it.

Related

Inserting smilies into div with jQuery

I'm working on some small chat application. I want to implement smilies over there so when i click on some smiley it will appear in textarea where user enters his message and when user clicks on select i want smilies to appear in div that contains the conversation.
After some workarounds i got to idea that replacing textarea with div contenteditable="true"
doesn't work that well so i did wrap certain smiley name with ':' like :wink: in textarea but still i need to replace :wink: with real span containing image as background.
Problem is i don't see a way to make this dynamically but doing each one by one.
for example:
if ($('.line:contains(":wink:")').length > 0) {
var oldLineHTML = $('.line:contains(":wink:")').html();
$('.line:contains(":wink:")').html(oldLineHTML.replace(/:wink:/gi, '<span class="wink></span>"'));
I have plenty of smilies so doing this very resource expensive function will costs me much and also will cause me lots of problems during maintenance.
How can i do that dynamically? Or maybe you have better solution which will require to re-design... I'm up to it if it is required.
thanks
}
var testString = "test1 :smile: test2 :wink:";
alert(testString.replace(/:([^:]*):/g, '<span class="$1"></span>'));
My suggestion is read every string that is wrapped by colons :[something]:, then convert it into span. So that you don't have to define every smile, and it is easy to maintain.
If you are doing this on page load, then you can do this in a $(document).ready(). Then you can use selector that you have $('.line:contains(":wink:")') and use the $each operator to loop over each one and perform the update. This will cover you for the page load. But if you refactor that $each code into a method, then you can call it each time the text is updated. I think this will give you the best in both cases. Something like this:
function replaceWinks(){
$('.line:contains(":wink:")').each(function(index) {
//Replace the wink here
});
}
$(document).ready(function(){
replaceWinks();
});
I would recommend replacing the winks server side for the page load though. It will be more performant. Also it will avoid content that changes when after the first view.
Jeaffrey Gilbert's idea is good, but I have another one that may be interesting:
write down you winks the way you want(let's say [SmileName]), and when processing the text with jquery, read every one of them, and replace the [ with <div class=" then replace the ] sign, with "></div>, this way, you will end up like this:
using these smilies:
1- [smile]
2- [wink]
3- [shy]
will lead to the following markup
1- <div class="smile"></div>
2- <div class="wink"></div>
3- <div class="shy"></div>
and using CSS, you will give every class of them, a different background image, which is the smile image.
by utilizing this method, every div will lead to displaying your smilies, and you will write the code once, and end up using it wherever you want, without repeating yourself

How to prevent child from one element to be on top of another element

(Okay, I know the questions probably sounds rancid bad, so someone edit if they they know how to reformulate it).
So, basically I have this: jsFiddle
And as you can probably see, I'm trying to re-create a basic windows 7 aero effect (curiosity, fun, learning, etc nothing big), but I stumbled into a few problems.
(I will explain only vaguely, since you can see it on the fiddle and otherwise it would be a textathon)
The text is stuck on top of the parent's(div) parent(div) element.
The text somehow leaks out of the duplicate element(div), even thought it doesn't from the original.
I know this all sounds odd, but you'll probably best see it on the fiddle.
Thank you.
I think the problem you're having is stemming from this:
$(container).find('*').each(function() {
var e_clone = $(this).clone(false).appendTo(processor);
// etc etc
});
By using the * selector then running .each you are cloning more markup into #processor than I think you might have intended to. You get two copies of span.lol in there because first it clones #box (including all its children) and then on the next iteration through the each it copies over span.lol on it own.
As for the "leaking" of text out of the parent, it does happen in the original... at least that's what I see in Chrome if I comment out the call to glass('#container', '#processor').

choose javascript variable based on element id from jquery

I feel like this is a simple question, but I am still relatively new to javascript and jquery.
I am developing a site for a touch interface that uses unordered lists and jquery .click functions to take input data. I have a section to input a m:ss time, with 3 divs, each containing a list of digits for time. I need to get the input for each column and set it as a variable. I originally designed the inputs to change form inputs, because I didn't understand javascript very much. It was easy to change the 3 hidden inputs by using div id's, but I can't figure out how to do it now with javascript variables.
Here is my original jquery code...
$("div#time>div>ul>li").click(function() {
var id = $(this).parents(".time").attr("name");
var number = $(this).html();
$("input#"+id).val(number); });
The last line sets one of 3 hidden inputs equal to whatever was clicked. I need to make it so separate variables take the inputs, then I can manipulate those variables however I want.
Here's a short snippet of the html, to have an idea of how jquery grabs it.
<div id="time">
<h1>Time</h1>
<div name="minute" class="time" id="t_minute">
M :
<ul>
The full time html is here: link text
Thanks everyone!
I've been using SO to answer many questions I've had, but I couldn't find something for this, so I figured I would join, since I'm sure I will have more questions along the way.
So I have tried adding the following, and I still can't get it to work right.
window.myValues[id] = number;
event[i].min = myValues["minute"];
event[i].sec = myValues["second"];
event[i].sin = myValues["single"];
event[i].time = String(event[i].min) + String(event[i].sec) + String(event[i].sin);
I tried it both with and without the quotation marks. I have not used window.* for anything, so I'm not very sure how to handle this.
First thing to mention here, don't be unnecessary specific. In your example
$('#time').find('li').click()
should be enough.
If I understand you well, you want to store the some data. You might want to use
jQuery's $.data method. Example:
$('#time').find('li').click(function(){
var $this = $(this);
var name = $this.closest('.time').attr('name');
$.data(document.body, name, $this.html());
});
This would store the html of the clicked li in a global Object, which can be accessed like
alert($.data(document.body, 'minute'));
you should be able to reference the variable from the window[] object, so something like window[id] should do the trick for referencing the variable.

Removing appended html using jQuery?

Using jquery, I currently append html to a div on a click event. The following code allows me to fade in only the appended portion of the div:
var html = "..";
$('<div></div>').appendTo("#id").hide().append(html).fadeIn('slow');
This portion works perfectly. But how can I later remove (fade out) only the appended portion? I tried hacking this by storing the html prior to the appending, and then simply hiding everything and showing the stored html. But this does not work well when the same procedure is reused for several divs on the same page (and this seems like poor implementation). Is there a good way to do this?
Just to give an idea of why I need this: Think of a blog type page where for every article on the page there are several comments with only x amount showing by default: the click event fetches the remaining comments and displays them, and then toggling the button again removes the appended comments and sends it back to the original state.
empty() is always an option
jQuery('#main').empty();
Give a look at the empty() function.
It might better solve the problem. Here's the link http://api.jquery.com/empty/
I'd just set and clear the html with '.html()' ...
-- edit
to be more clear, have an area layed out specifically for the addition of these comments:
<div id='commentarea1'></div>
etc.
Try:
var html = "..";
$('<div></div>').appendTo("#id").hide().append(html).fadeIn('slow').addClass('appended');
then later
$('#id .appended').fadeOut('slow'); // or whatever you want to do.
It is not that clear from the question but say you show 5 comments by default and then show x more comments. To get back to the original 5 comment default state you can remove all comments with an index greater than 4 (zero based).
The following assumes each comment goes inside its own div that has a class comment.
$('#id>div.comment:gt(4)').remove();

prefilling dynamically created textbox with javascript in IE

I'm trying to dynamically add some textboxes (input type=text) to a page in javascript and prefill them. The textboxes are coming up, but they are coming up empty. What is the proper way to pre-fill a textbox. Ideally I'd love to use the trick of creating a child div, setting the innerhtml property, and then adding that div to the parent main div but that didn't work. Then I thought I'd use the dom but setting textboxname.value before or after insertion won't work and doing txttextbox.setattribute('value','somevalue') won't work either. Works fine in firefox. What gives? This has to be possible? Here is my code. I know I'm only using string literals, but these will be replaced with the results of a web service call eventually. Below is some code. Oh and how do you format code to show up as you type it? I thought it said to indent four spaces, and I did that but the code is still on one line. Sorry about that.
var table=document.createElement('table');
var tbody=document.createElement('tbody');
var row=document.createElement('tr');
row.appendChild(document.createElement('td').appendChild(document.createTextNode('E-mail')));
var txtEmail=document.createElement('input');
row.appendChild(document.createElement('td').appendChild(txtEmail));
tbody.appendChild(row);
table.appendChild(tbody);
//document.getElementById('additionalEmails').innerHTML="";
document.getElementById('additionalEmails').appendChild(table);
txtEmail.value = 'my text'
Does not work?
You can also use Prototype to do this easily:
document.body.insert(new Element("input", { type: "text", size:20, value:'hello world' }))
I've encountered problems similar to this in the past, and while my memory is a bit fuzzy on why it was happening exactly, I think you may need to make sure the element is actually added to the DOM before modifying its value. e.g:
var txtEmail=document.createElement('input');
document.getElementById('someElementThatAlreadyExists').appendChild(txtEmail);
txtEmail.value = 'sample text';
I ended up solving this problem by injecting the html directly into a page via a child div. That did work, it's just that I am blind and the software I use to read the screen for some stupid reason failed to see the text in the textbox. Go figure. Thanks for the tip on prototype though, if I ever decide not to cheat and add the eleements to the dom directly, I'll do it that way.

Categories

Resources