-1

In this function, data from the users array is searched by the value of input into mySearch. The line that contains the search term is outputted to return.

DATA:

var users = [{"username":"nlee6p","gender":"Female","sexuality":"Down-sized asymmetric time-frame","language":"Macedonian"},
{"username":"bbrooks6q","gender":"Male","sexuality":"Multi-channelled mobile customer loyalty","language":"Luxembourgish"},{"username":"astephens6r","email":"lmiller6r@ucoz.com","gender":"Female","language":"Estonian"}]


function myFunction(e) {
    if((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton'){
        e.preventDefault();
        var searchValue = document.getElementById("mySearch").value;
        for(var i = 0; i < users.length; i++){
        if((users[i]['last_name'] === searchValue) || (users[i]['username'] === searchValue) || (users[i]['first_name'] === searchValue)){
        document.getElementById("return").innerHTML = JSON.stringify(users[i]);
        return;
       }  
    }
  }
}

HTML

<input type="search" id="mySearch"  onkeypress="myFunction(event)"/>
<button id="searchButton" onClick="myFunction(event)">SEARCH</button>

<div id="return">
    <div id="usernameOut">
    </div>
    <div id="firstNameOut"> 
    </div>
</div><!--return-->

My Question

Is it possible to output the stringified data in individual divs without jQuery? Currently the output is the entire line of the array relating to the searched term. I'm looking for a way to split the line up and display the individual components in their own div tags (or in a table if that's easier)

For example, When the string is outputted, the username value will be shown in usernameOut, first-name in firstNameOut etc.

I've used Jput in the past, but this is for a page that's being displayed locally through a C# application and compiling jQuery in C# is a bit of a nightmare.

Answers using vanilla JS are appreciated, but if the only way is through jQuery then i'm not too fussed.

JsFiddle (that doesn't work for some reason)

(Sorry if this is unclear, I will edit if needed)

gezer4000
  • 103
  • 1
  • 9
  • 1
    Yes, this is possible. Just don't stringify the data and just loop over all those divs, adding the value from the object (users[i].username) instead of pasing a stringified version into one div. The clue is that youra rray contains objects you can access, it's the JSON.stringify that turns it into a string, so you don't ahve to split the string at all. Which part isn't working? There isn't any jquery in the code either, so why would you need it? – Shilly Feb 09 '17 at 14:42
  • @Shilly Thanks for the help! I was looking for solutions and almost all of them were jQuery and i needed something that fit with my existing code. I was also trying to workaround `.stringify` which meant parsing something thats already been parsed.... I think i have it now though. I.e. `document.getElementById("usernameOut").innerHTML = (users[i].username);` – gezer4000 Feb 09 '17 at 20:48

1 Answers1

1

Here is the working fiddle:

https://jsfiddle.net/zfywyyfj/2/

no changes were made to the code, just reposition.

You set it to only show when it's completly equal, so you have to type the whole thing to make it dump the json string.

Also, i moved the JS script to the head, because otherwise it will get called before is defined. This is a Fiddle issue as pointed out by Shilly.

UPDATE: The error is because you're trying to get last_name and first_name while the users array/object doesn't have it. Here is the working snippet, i also edited it to allow partials.

var users = [{"username":"nlee6p","gender":"Female","sexuality":"Down-sized asymmetric time-frame","language":"Macedonian"},{"username":"bbrooks6q","gender":"Male","sexuality":"Multi-channelled mobile customer loyalty","language":"Luxembourgish"},{"username":"astephens6r","email":"lmiller6r@ucoz.com","gender":"Female","language":"Estonian"},{"username":"rbishop84","gender":"Female","sexuality":"Centralized hybrid data-warehouse","language":"Amharic"},{"username":"wmorrison85","gender":"Male","sexuality":"Extended upward-trending throughput","language":"Aymara"}];

function myFunction(e){
  if((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton') {
    e.preventDefault();
    var searchValue = document.getElementById("mySearch").value;
    for(var i = 0; i < users.length; i++) {
      if( ( users[i]['language'].includes(searchValue) ) || ( users[i]['username'].includes(searchValue) ) || ( users[i]['sexuality'].includes(searchValue) ) ) {
        document.getElementById("return").innerHTML = JSON.stringify(users[i]);
        return;
      }
    }
  }
}
<input type="search" id="mySearch" onkeypress="myFunction(event)"/>
<button id="searchButton" onClick="myFunction(event)">SEARCH</button>

<div id="return">
</div>
LordNeo
  • 1,195
  • 1
  • 8
  • 21
  • Thanks for the cleanup. But moving the script to the head doesn't do anything. onclick and onkeypress will not get called before the script is loaded unless you do that manually. – Shilly Feb 09 '17 at 14:45
  • test it, move it to the bottom and you will get "myFunction undefined" errors. – LordNeo Feb 09 '17 at 14:50
  • I copy pasted the JS into a script tag and used the html `
    ` No errors. Try putting an alert as the first statement in myFuntion. It should get triggered on page load then. Anyways, offtopic.
    – Shilly Feb 09 '17 at 14:55
  • tried it on the fiddle and no go. the only way i got the myFunction to trigger propperly was moving it to the head. on this question: http://stackoverflow.com/a/15171315/2730902 it also points out the same behaviour. Also, the fiddle is working. – LordNeo Feb 09 '17 at 14:57
  • The question you show, that user had his definition inside a function, so it was undefined. Read the first comment on the accepted answer. The following code should error or alert if you're right. Neither happen for me in IE11 or Chrome56 ` ` Anyways. This is one of the reasons I always define events with `addEventListener`. I'm sorry for the discussion, but placing scripts as low as possible in the body is a best practice. – Shilly Feb 09 '17 at 15:07
  • read the coments on the answer linked. also, here is the fiddle with the code you proposed: https://jsfiddle.net/zfywyyfj/3/ it doesn't trigger on Chrome 55.0.2883.87. I know that putting the JS as low as possible is best practice, but sometimes you need to make it work. – LordNeo Feb 09 '17 at 15:17
  • That's a problem with the fiddle, not with JS, so it might confuse people if you say it this way. https://jsfiddle.net/o33d0ext/ works for me. – Shilly Feb 09 '17 at 15:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135301/discussion-between-lordneo-and-shilly). – LordNeo Feb 09 '17 at 16:02
  • Sorry, can't use chat atm alas. But I think I've explained what I meant. Moving the script to the head fixes an issue with the fiddle, but has no relevance to the OP's problem. I mentioned it so that beginners reading your answer won't start putting all their JS inside the head tag. The expression 'it will get called before it is defined' is also false. The page will check if the function exists when using inline handlers, but will not call it. – Shilly Feb 09 '17 at 16:07
  • @Shilly no problem, i edited my answer to avoid leading into mistakes. Thanks for the help! – LordNeo Feb 09 '17 at 16:27
  • @LordNeo3 Thank you for fixing the fiddle, for the explanation and for trying to actually help the OP with the issue. We're all here to learn. Have a nice day. :) – Shilly Feb 09 '17 at 16:33