0

i have a script like this:

<script>
    var stuff = '<input id="testinput" name="testinput" type="text" value="this is the right one" /><input id="testinput2" name="testinput2" type="text" value="this is the wrong one" />'
</script>

How can I with jQuery get the value ("this is the wrong one") from the stuff variable?

4 Answers 4

7

Use .val method.

var value = $(stuff).val();

Update: Did not notice there is multiple input in your string. In the case, you need to use .map method to return the values as an array.

The demo.

var stuff = '<input id="testinput" name="testinput" type="text" value="this is the one" /><input id="testinput2" name="testinput2" type="text" value="this is the wrong one" />';

console.log($(stuff).map(function() {
    return $(this).val();
}));​
Sign up to request clarification or add additional context in comments.

1 Comment

The Boss way haha one liner helped a lot it is actually kind of returning an element
6
var stuff = '<input id="testinput" name="testinput" type="text" value="this is the one" /><input id="testinput2" name="testinput2" type="text" value="this is the wrong one" />';

console.log($(stuff).val()); // This is the one

Demo

console.log($($(stuff)[1]).val());​ // This is the wrong one

Comments

0

Use val() for getting the value or if you are after an attribute use .attr()

var v = $(stuff).val();

var attr = $(stuff).attr('attribute you want');

Comments

0

I had a similar issue with selectors failing, until I did this:

var stuff = '<input id="testinput" name="testinput" type="text" value="this is the one" /><input id="testinput2" name="testinput2" type="text" value="this is the wrong one" />';

var myValue = HtmlElementAttribute(stuff, 'testinput2', 'value');

function HtmlElementAttribute(htmlString, elementId, attributeName) {
    var foundValue = '';
    $(htmlString).filter(function (x) {
        var idX = eval('$(htmlString)[x].id');
        if (idX && idX == elementId) {
            foundValue = $(eval('$(htmlString)[x].outerHTML')).attr(attributeName);
        }
    });
    return foundValue;
}

Comments

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.