0

I wish I could get an array of objets stored in an hidden input.

Thanks

Here is the hidden input in the html page :

<input type="hidden" name="idMusicians" value="[{&quot;id&quot;:7069,&quot;project_id&quot;:324,&quot;name&quot;:&quot;Gator&quot;,&quot;first_name&quot;:&quot;Ali&quot;,&quot;instrument_id&quot;:28,&quot;created_at&quot;:&quot;2019-08-02 15:48:07&quot;,&quot;updated_at&quot;:&quot;2019-08-02 15:48:07&quot;,&quot;,{&quot;id&quot;:7070,&quot;project_id&quot;:324,&quot;name&quot;:&quot;Zhette&quot;,&quot;first_name&quot;:&quot;Annie&quot;,&quot;instrument_id&quot;:29,&quot;created_at&quot;:&quot;2019-08-02 15:48:07&quot;,&quot;updated_at&quot;:&quot;2019-08-02 15:48:07&quot;,}]">

I tried this, but it doesn't work :

var musicians = $("#idMusicians").map(function(){
    var musician = this;
    return musician;        
}).get();

And this also without success :

var musicians = $("#idMusicians").data('value');
1
  • 1
    Your input is invalid JSON. Commented Aug 3, 2019 at 10:35

2 Answers 2

3

You can get the value in your input if you give it an id and then use:

$("#idMusicians").val();

Once you have your value in a variable, you can parse it as JSON, which will then allow you to iterate over your array to access its objects. However, in order for JSON.parse() to work, the value in value needs to be valid JSON. At the moment, your value isn't valid JSON as it doesn't close your first object properly. If you fix this, you can then use JSON.parse() without getting errors.

See example below:

const musicians = $("#idMusicians").val();
const res = JSON.parse(musicians);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="idMusicians" name="idMusicians" value="[{&quot;id&quot;:7069,&quot;project_id&quot;:324,&quot;name&quot;:&quot;Gator&quot;,&quot;first_name&quot;:&quot;Ali&quot;,&quot;instrument_id&quot;:28,&quot;created_at&quot;:&quot;2019-08-02 15:48:07&quot;,&quot;updated_at&quot;:&quot;2019-08-02 15:48:07&quot;},{&quot;id&quot;:7070,&quot;project_id&quot;:324,&quot;name&quot;:&quot;Zhette&quot;,&quot;first_name&quot;:&quot;Annie&quot;,&quot;instrument_id&quot;:29,&quot;created_at&quot;:&quot;2019-08-02 15:48:07&quot;,&quot;updated_at&quot;:&quot;2019-08-02 15:48:07&quot;}]">

Sign up to request clarification or add additional context in comments.

Comments

0

# is the id selector, but idMusicians is a name property. Try changing it to id=idMusicians or select by name attribute $(input[name="idMusicians"])

1 Comment

You're right, I did it. Nick Parsons gave me THE solution, thank's to him

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.