Reputation: 1
I am having 6 bootstrap cards where the card details are id,content. Onclick of every card I am getting the ids of clicked card into the array from the local storage now I want to send that ids to the html form as value for input field My html code is:
<body onload = "sample(),issample()">
<div class="form-group" >
<input type="text" name="goal" id="goal" value=" ">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<input type="submit" value="Register" class="btn btn-secondary btn-block">
My JS code is:
var goal = []
function getGoal(id, content) {
if (goal.length > 0) {
var data = { id: id, content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
var index = goal.indexOf(x)
if (index == -1) {
goal.push(x)
}
else {
goal.splice(index, 1)
}
}
else {
var data = { id: id, content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
goal.push(x)
}
localStorage.setItem("goal", JSON.stringify(goal))
// To get all ids
var storedNames = JSON.parse(localStorage.getItem("goal"))
var goalIds = []
if (storedNames)
storedNames.forEach(element => {
element = JSON.parse(element)
goalIds.push(element.id)
});
console.log(goalIds)
}
function issample(){
$("#goal").val(goalIds);
}
I am getting error as goalIds not defined but the goalIds array is getting the ids but that ids are not getting in the form as a value
Upvotes: 0
Views: 45
Reputation: 3090
You have declared goalIds
in getGoal
function and it is only accessible in that function. If you need to use the array in somewhere else then you can declare it outside the function
var goal = [];
var goalIds = [];
function getGoal(id, content){
...code here
goalIds = [];
if (storedNames)
storedNames.forEach(element => {
element = JSON.parse(element)
goalIds.push(element.id)
});
console.log(goalIds)
// If you need to set the value for every `getGoal` call
issample();
}
function issample(){
$("#goal").val(goalIds);
}
Upvotes: 1