Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't even get $().text to work properly. Outputs a massive string of code instead

I've set up a test so I can begin using jQuery in a cakePHP environment but I'm having a problem before I've even started.

I have twitter bootstrap also but when I had this problem I turned everything off to make sure it wasn't that. It wasn't.

I'm testing this in Chrome & Waterfox.

When I tried to $('#test').html('Hello'); I didn't get anything. So I tried alerting something out using the following:

$(document).ready(function() {

    $('#test').click(function() {
        alert($('#test').text);
    });
});

and

<span id="test">test span</span>

Which gives me the result:

function (a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)}

Could someone please tell me what the hell that is please and why didn't I get 'test span'. Thank you :)

like image 911
Andrew Myers Avatar asked Jun 21 '12 13:06

Andrew Myers


People also ask

Why my JavaScript is not working?

In the "Preferences" window select the "Security" tab. In the "Security" tab section "Web content" mark the "Enable JavaScript" checkbox. Click on the "Reload the current page" button of the web browser to refresh the page.

When there is a problem with JavaScript code there are generally two types of errors?

There are two types of JavaScript error: Syntax Error: Occurs when there is a mistake in the way the code is written; for example, a typo or missing character. Runtime error: Occurs when the script is unable to complete its instructions; for example, if a specified object cannot be found.

Which is the correct way to write a JavaScript array?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


2 Answers

'text' is a function, the code of which you are outputting

Just call it like any function

alert($('#test').text());
like image 60
Thomas Avatar answered Nov 15 '22 04:11

Thomas


jQuery.text() is a function, not a property. Here is how you use it:

var a = $('#test').text(); // getter
$('#test').text(a);        // setter

Note: consider using jQuery.html() if you plan to inject fragments of HTML.

like image 40
Salman A Avatar answered Nov 15 '22 04:11

Salman A