views:

81

answers:

5

Hi,

I am working on a project which needs to extract text form a predefined div tag.

My requirement is to send the content in the target div in a email body. I have to use javascript or php for this task.

The Process : When a given link will be clicked; a javascript function will trigger and read that target div. The content of the div will be then submitted to server in dynamic form.

What options I have to get this task done?

Thanks.

+1  A: 

I would get the innerHTML of the div. So if your div is div_obj:

var div_obj = document.getElementById("...");
alert(div_obj.innerHTML);
nc3b
A: 

document.getElementById( ID_OF_DIV ).innerHTML;

should do it if I'm not mistaken. W3Schools is a wonderful website for information on web programming.

Mimisbrunnr
Since when is [HTML DOM](http://www.w3schools.com/htmldom) traversing [Ajax](http://www.w3schools.com/ajax)? Your answer a bit implies that. It are two separate subjects, Ajax and the code snippet you posted.
BalusC
You are quite right. Sorry for the mistake. I assumed the need to post changes back to the site in my response.
Mimisbrunnr
+2  A: 

jQuery's text() (link) would let you get the text inside the div.

var thetext = jQuery('div#foo').text();

You could then use its post() (link) to send the data to a PHP script for emailing.

Nathan Long
A: 

Indeed, I'd give the div an id and then use the innerHTML method to get its contents.

After that, you could use XMLHttpRequest to submit the contents to the server.

Tom
+1  A: 

So assuming that you have something that looks like

<a href="#" onClick="someClickHandler(); return false;">Click Here</a>
<div id="foo">Hello World!</div>

I recommend using jQuery:

<script type="text/javascript">
    function someClickHandler() {
        var text = $("#foo").text();
        $.get("url_on_the_server", {some_query_parameter_name: text}, function(response){
            // do something with the response you get back from the server
        });
    }
</script>

Here's what this is doing:

  • The onClick attribute causes the someClickHandler function to be called when the link is clicked. Because we put return false in that attribute, the browser will not try to follow the link; instead when clicked it will just execute the click handler and stop.

  • Saying $("#foo") finds the element on the page with an id of "foo", as documented here. Saying $("#foo").text() returns everything inside that div as text, as documented here.

  • The $.get call is explained at depth in the jQuery documentation here. Basically you're making an AJAX request to the server and passing the text from the div as a query parameter. The function you pass to $.get defines what you do with the response you get back from the server.

Of course, you could also use the jQuery click method instead of manually setting the onClick attribute yourself, but I figured that this way would be somewhat more intuitive for a beginner.

Eli Courtwright