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
The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element.
Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.
To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.
$(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">');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With