Set html input string value with jquery

I have an HTML snippet in a line like this:

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

How do I, with jQuery, set its value so that the HTML ends as follows:

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

Thanks Scott

+6
source share
4 answers
 $(htmlString).attr("value", "newValue"); 

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

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

EDIT:

You can use the @idor_brad method. This 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()); 
+6
source

First you need to add your element to the DOM (i.e. to your web page). For instance:

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

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

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

- see demo -

+6
source

You just want to manipulate the string, right? There are many ways to hide this cat, but

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

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

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

Source: https://habr.com/ru/post/923132/


All Articles