7

I have snippet of HTML in a string like this:

var htmlString = '<input type="text" id="someID" name="someID">';

How do I, with jQuery, set its value so that the HTML ends up like this:

'<input type="text" id="someID" name="someID" value="newValue">';

Thanks, Scott

4 Answers 4

7
$(htmlString).attr("value", "newValue");

But this will return jQuery object, not string. You can add it to DOM.

$(htmlString).attr("value", "newValue").appendTo("body"); // you can give any element instead of body

EDIT :

You can use @idor_brad's method. That is the best way or

var htmlString = '<input type="text" id="someID" name="someID">';

var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");

console.log($htmlString.get(0).outerHTML);

or

var htmlString = '<input type="text" id="someID" name="someID">';

var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");

console.log($("<div>").append($htmlString).html());
Sign up to request clarification or add additional context in comments.

3 Comments

I know that... I thought maybe you had found a clever way to do it without using the DOM. Oh well :)
Do you want to retrieve the final string without using DOM ? That is also possible
That gets me most of the way there. How do I get the HTML string back out of the jQuery object?
6

You would first need to add your element to the DOM (ie to your web page). For example:

$(".container").append(htmlString);

Then you can access your input as a jquery object and add the value attribute like so:

$("#someID").val("newValue");

-- See Demo --

Comments

4

You just want to manipulate the string, right? There are a lot of ways to skin this cat, but

var newString = htmlString.replace('>', ' value="newValue">');

Comments

1

After the dom ready, append your input to body and then grab the input with id = "someID" and set its value to newValue

   $(document).ready(function(){
       $("body").append(htmlString);
       $("#someID").val("newValue");
    });

1 Comment

This is the most elegant solution in my case, as my html is complex.

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.