Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery val is undefined?

I have this code:

<input type="hidden" id="editorTitle" name="title" value="home">
<textarea name="text" id="editorText"></textarea>

But when i write $('#editorTitle').val() and $('#editorText').html(), $('#editorTitle').val() is 'undefined' and $('#editorText').html() is empty?

What is wrong?


Edit:

Here is my full code:

function openEditor() {
    $("#editor").show().animate({ width: 965, height: 380 }, 1500);
    $("#editor textarea").show();
}

function closeEditor() {
    $("#editor").animate({ width: 985, height: 1 }, 1500, function () {
        $("#editor").hide();
        $("#editor textarea").hide();
    });
}

function setedit() {
    $.ajax({
        type: "POST",
        url: "engine.php",
        data: "title=" + $('#editorTitle').attr('value') + "&text=" + $('#editorText').html(),
        beforeSend: function () {
            $('#mainField').html('<img src="data/images/loader.gif" alt="Loading...">');
        },
        success: function (msg) {
            alert(msg);
            closeEditor();
            search();
        }
    });
}
function search() {
    $('#title').val($('#search').val());

    $.get('engine.php?search=' + $('#search').val(), function (data) {
        $('#mainField').html(data);
    });

    $.get('engine.php?raw=true&search=' + $('#search').val(), function (data2) {
        $('#editorText').html(data2);
    });

    $.get('engine.php?title=true&search=' + $('#search').val(), function (data2) {
        $('#h1').html(data2); // Row 152
        $('#editorTitle').html(data2);
    });
}

$(document).ready(function () {
    $("#ready").html('Document ready at ' + event.timeStamp);
});

But what is wrong?!?!

like image 228
Thew Avatar asked Feb 15 '11 16:02

Thew


2 Answers

You probably included your JavaScript before the HTML: example.

You should either execute your JavaScript when the window loads (or better, when the DOM is fully loaded), or you should include your JavaScript after your HTML: example.

like image 196
Aron Rotteveel Avatar answered Oct 06 '22 01:10

Aron Rotteveel


You should call the events after the document is ready, like this:

$(document).ready(function () {
  // Your code
});

This is because you are trying to manipulate elements before they are rendered by the browser.

So, in the case you posted it should look something like this

$(document).ready(function () {
  var editorTitle = $('#editorTitle').val();
  var editorText = $('#editorText').html();
});

Hope it helps.

Tips: always save your jQuery object in a variable for later use and only code that really need to run after the document have loaded should go inside the ready() function.

like image 39
Jonathan Avatar answered Oct 05 '22 23:10

Jonathan