0

I want to be able to set the contents of the value attribute in the input element but have not been successful doing this.

HTML:

<div class='photo-info'>
    Photo Name : <span class='photo-name'><?php echo $title; ?></span>
    <span class='title-edit'><a href='#'>Edit</a></span>
</div>

jQuery:

// show editable area for title
    $('.title-edit').on('click', function () {
        var $titleElm = $(this).prev();
        var text = $titleElm.text();
        $titleElm.html("<input type='text'>").val('tom');
    })

Result:

https://jsfiddle.net/fh7t9qwd/1/

1
  • I would suggest just doing the following $titleElm.html("<input type='text' value='tom'>"); Commented Jul 2, 2016 at 19:25

1 Answer 1

2

Add find('input') after you update the HTML:

$titleElm.html("<input type='text'>").find('input').val('tom');

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! The way I was thinking was: .html() returns a jquery object so why not chain .val() right after. Do you know why it did not work as I had in mind?
Because html() here is returning the jQuery object of $titleElm which isn't an input. html() does not return a jQuery object of the specified HTML, but of the outer container itself.

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.