0

I have searched on the website for solutions, but I have had no luck. I need to make this data global. My code is present below:

     function val() {
            var plans = @json($plans);
            var id = document.getElementById("plan_id").value;
            plans.forEach(function(element) {
                if (id == element.id) {
                    var  i = element.amount;
                    return i;
                }
            });

        }
        var obj =  val()
        console.log(obj)

After I log that, it wont give any values but if I log inside the foreach, I will get the amount. Pls how can I access data inside foreach

4 Answers 4

1

Your function needs to return a value if you want to log it outside like this.

function val() {
  const plans = @json($plans);
  const id = document.getElementById("plan_id").value;
  return plans
    .filter(element => id === element.id)
    .map(element => element.amount);

}

const obj = val()
console.log(obj)
Sign up to request clarification or add additional context in comments.

3 Comments

It's not still log out the amount
I don't understand, what is it currently logging and what do you want it to log?
the val() is listening to onchange event, so I need a way when I select and option, the amount will change
1

You are not returning anything from the function and return inside forEach is always undefined. Use find

function val() {
  var plans = @json($plans);
  var id = document.getElementById("plan_id").value;
  return plans.find(element => id === element.id).amount;

}
var obj = val()
console.log(obj)

1 Comment

the val() is listening to onchange event, so I need a way when I select an option, the amount will change
0

This would on change get the amountValue from based on what ID you have selected.

var amountValue = null;

function val() {
    var plans = @json($plans);
    var id = document.getElementById("plan_id").value;
    for (i = 0; i < plans.length; i++) {
        if (id === plans[i].id) {
            amountValue = plans[i].amount;
            return amountValue;
        }
    }
}
var obj = val()
console.log(obj)

Comments

0

Thanks everyone, I have fixed my issue, but I follow another process.

I actually get the amount using onclick

1 Comment

Can you edit your main post or this answer with the solution?

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.