Mike Thrussell
Mike Thrussell

Reputation: 4525

dynamic javascript using jquery

<div id="text">some text</div>

<img src="#" onclick="$.function('http://url.com?q=some+text')"/>

I want the q= to be dynamic using the text in the previous paragraph. I can get the text into a variable

var str = $("#text").text();

but am struggling to output this dynamically.


EDIT:

It's much simpler than I thought, figured out the solution from Darin's answer:

  <div id="text"><p>Testing text to speech</p></div>
  <div id="textlink"></div>
  <img src="#" onclick="$.sound.play('http://translate.google.com/translate_tts?q='+ str)" />
<script>
var str = $("#text").text(); 
</script>

Just needed to know how to append a variable. Thanks

Upvotes: 0

Views: 261

Answers (4)

Naftali
Naftali

Reputation: 146350

Start of what I think you want to do:

$('img').click(function(){
    var str = $("#text").text();
    alert('http://url.com?q=' + str);
});

Or maayyyyybe:

$('img').click(function(){
    var str = $("#text").text();
    window.location = 'http://url.com?q=' + encodeURIComponent(str);
});

Or even:

$('img').click(function(){
    var str = $("#text").text();
    this.src = 'http://url.com?q=' + encodeURIComponent(str);
});

Fiddle: http://jsfiddle.net/maniator/UrDRX/
(works in HTML5 browsers, edit the color code)

And on and on....

Upvotes: 2

Kris Krause
Kris Krause

Reputation: 7326

Separation of concerns. In this case you want to keep behavior (javascript) separate from the content (html) and style (css). - http://en.wikipedia.org/wiki/Separation_of_concerns

So... onclick="x();" is not preferred. Rather:

$(document).ready(function(
 $("#buttonId").click(function() { 
    var val = $("#text").text();
    var url = 'http://url.com?q=' + encodeURIComponent(val);

    alert(url); // or window.location or whatever you want to accomplish
 });
));

Upvotes: 1

David Thomas
David Thomas

Reputation: 253485

Perhaps, if you want to use the entire text-content of the paragraph:

var str = encodeURIComponent($('#text').text());

$('#linkId').attr('href','http://url.com?q=' + str);

JS Fiddle demo.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

Lemme shoot in the dark:

<img src="#" onclick="window.location.href = 'http://url.com?q=' + encodeURIComponent($('#text').text());" />

or if you want to assign this src dynamically:

<img src="#" id="foo"/>

and then:

$(function() {
    $('#foo').click(function() {
        window.location.href = 'http://url.com?q=' + encodeURIComponent($("#text").text());
    });
});

Upvotes: 2

Related Questions