Im storing a little data in my jQuery. I want to call it from arrays with functions, but when I call the array it doesn't return any value. There's my JSFiddle
jQuery code
$('button').click(showInfo);
function showInfo(){
var data = $(this).attr("dataid");
//alert(data);
dataArray(data);
writeData(data);
}
function dataArray(call){
var person1 = [{
'name':'First Name',
'position':'Director'
}];
var person1 = [{
'name':'Second Name',
'position':'Director'
}];
}
function writeData(called){
$('.person').removeClass('hidden');
dataArray(called[0]);
// write in divs
$('.person .name').text(dataArray(called['name']));
$('.person .position').text(dataArray(called['position']));
}
asked Sep 1, 2017 at 16:52
eatmailyo
6701 gold badge13 silver badges36 bronze badges
2 Answers 2
You need to return something from your dataWrite call. in this case an object of objects with person data. then you can filter that by the name passed in.
$('button').click(showInfo);
function showInfo() {
var data = $(this).attr("dataid");
//alert(data);
writeData(data);
}
function dataArray() {
var persons = {
person1: {
name: 'First Name',
position: 'Director'
},
person2: {
name: 'Second Name',
position: 'Director'
}
};
return persons;
}
function writeData(called) {
$('.person').removeClass('hidden');
//alert(called);
// write in divs
$('.person .name').text(dataArray()[called].name);
$('.person .position').text(dataArray()[called].position);
}
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button dataid="person1">Call person 1</button>
<button dataid="person2">Call person 2</button>
<br/>
<br/>
<div class="person hidden">
<span>Name: </span>
<div class="name"></div>
<br/>
<span>Position: </span>
<div class="position"></div>
</div>
answered Sep 1, 2017 at 17:03
Zach M.
1,1947 gold badges24 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You have two problems in your code:
dataArrayfunction isn't returning anything so you need to change it to:function dataArray(call){ return { person1 :{ name:'First Name', position:'Director' }, person1 :{ name:'Second Name', position:'Director' } }[call]; }you need to access the key of the returned object , and that would be:
$('.person .name').text(dataArray(called)['name']); $('.person .position').text(dataArray(called)['position']);
here's the working fiddle
answered Sep 1, 2017 at 17:09
maioman
18.8k4 gold badges39 silver badges46 bronze badges
Comments
lang-js
var person2as the second variable, instead of 2var person1linesreturnsomething. Maybe you should just explain what you want to happen, because this code does not really reveal that.