1

I have a text box and a button. On the button . click function the name appears but I want id (that the user enters into the text box for the corresponding name to appear)

this is a snip from the json:

{"user":[{"ID" : "001","name": "Zara Ali"}]}

This is the button/text ( that i have inside an alert div because i think it looks cool in my page and works with the .click)

<div class="alert alert-info"> 
  <input type="text" id="userName" value> 
  <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button>
</div>

and this is the js i have used for the .click

$(document).ready(function() {
  $("#loginbtn").click(function(event){
    $.getJSON('result.json', function(jd) {
      $('#details').html('<p> Name: ' + jd.name + '</p>');
    });
  });           
});

the result is going inside:

<div id = "details">

</div>
4
  • Are you returning more than one user? If not why the array instead of returning just the user object? Commented Dec 14, 2015 at 15:42
  • console.log(jd). you don't have jd.name, you have jd[0].name. an object containing an array of objects... Commented Dec 14, 2015 at 15:46
  • try this @Mac $.grep( [{"ID" : "001","name": "Zara Ali"}], function( n, i ) { return n.ID==='001'; }); Commented Dec 14, 2015 at 15:54
  • @Mac try this fiddle Commented Dec 14, 2015 at 15:58

1 Answer 1

1

Try this:

 $(document).ready(function() {
    $("#loginbtn").click(function(event){
       $.getJSON('result.json', function(jd) {
          var id = $('#userName').val();
          for (var i=0; i<jd.user.length; i++) {
            if (jd.user[i].ID == id) {
              $('#details').html('<p> Name: ' + jd.user[i].name + '</p>');
            }
          }
       });
    });
 });
Sign up to request clarification or add additional context in comments.

3 Comments

Hi jcubic - thank you very much for your answer but this did not work for me - would there be anything I would have to change in my json maybe?
@LMac forget about val() try now.
@LMac If it solve your problem don't forget to mark the answer.

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.