admin管理员组

文章数量:1202781

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

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

Share Improve this question asked Aug 17, 2012 at 14:59 Doo DahDoo Dah 4,02916 gold badges57 silver badges74 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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());

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 --

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">');

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");
    });

本文标签: javascriptSet value of input html string with jqueryStack Overflow