1

so, i'm working on a backend create/edit/delete page for a blog - it shows a list of articles with an edit and delete button for each. when the edit button for article 'foo' is clicked, these things happen:

  • the div expands and the raw HTML of an edit form is appended inside with jquery append().

  • the DOM has an array of objects, with each object containing the information for one article. the specific object with id 'foo' is fetched and cast to an array 'bar'.

now, what i'm trying to do is to set the values of the appended form to the values within 'bar'. i've tried using .attr(), .val(), but nothing seems to work.

i think the problem might be that i'm doing this all in the same scope. right after my .append() call, i try to access the elements i just appended by ID. is this tripping me up?

within the function, this is how i tried to do it:

$(this).parent().children('#thisone').append("<input id="articletitle">");
$(this).parent().children('#thisone').children('#articletitle').val("my title");
4
  • 1
    Can you see the highlighting above where your strings are quoted incorrectly? Commented Sep 24, 2013 at 18:38
  • 1
    In addition to the quoting syntax error, $(this).parent().children('#thisone') makes me assume you have duplicated element ids, which is invalid and can cause problems. Commented Sep 24, 2013 at 18:39
  • I guess Brian is right. And also keep in mind, that if you have problems with JavaScript/JQuery to use the console in Chrome. (Right-click -> Inspect Element -> Console) Commented Sep 24, 2013 at 18:41
  • Jason: was selecting a class with the parent.children thing in my original. good point though. Commented Sep 27, 2013 at 2:25

2 Answers 2

2

Try building the complete element before you append it:

var $input = $("<input>", { 
    id: "articleTitle",
    value: "my title"
});

$("#thisone").append($input);
Sign up to request clarification or add additional context in comments.

1 Comment

And ID's should always be unique. Therefore you wouldn't need the .parent().children()'s but just $('#thisone').append()
0

Assuming your HTML code will be somewhat like this

<div id="thisone">
    <span id="articletitle">Some Crazy Blog Title</span>
    <a id="edittile" href="#">Edit Title</a>
</div>

Javascript code to question:

$('#edittile').on('click', function() {
    var value = $('#articletitle').text();
    var html = '<form><input type="text" value="'+ value +'">';
    html += '<input type="submit" value="save"></form>';
    $('#articletitle').html(html);
    $(this).hide();
});

I have created a js fiddele code your ref too check it out here: http://jsfiddle.net/4hA6y/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.