简体   繁体   中英

How to alert input value from JSON (javascript)

I have a problem trying to alert input values from json object. I get 'undefined' when i execute this code. Can someone please give me some ideas, I think I tried everything. btw. I have to use JSON because it is my school project. Thank you! xx

<script>
let arr = [];

function adduser(){
    let user = {
        name: document.getElementById("first_name").value,
        lname: document.getElementById("last_name").value,
        text: document.getElementById("txtara").value,
        email: document.getElementById("emails").value
    }

    arr.push(user);
    let json_str = JSON.stringify(arr);
    alert(json_str.name);
}
</script>

You're trying to "print" a value from string, that's not possible. If you want to convert your array to JSON and next "print" it on an alert, please try this:

let user={
name:document.getElementById("first_name").value,
 lname:document.getElementById("last_name").value,
 text:document.getElementById("txtara").value,
 email:document.getElementById("emails").value
}
let json = JSON.parse(user);
alert(json.name);

You can't access json the same way you access an object. JSON is a string, you can still find user and it's name by searching through a string, but since it's your school project I honestly doubt that is the point of the lesson.

You probably have to to JSON.parse(arr)[0].name where 0 is first index of your array, since you push the user to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM