Home > other >  How can I use an array in blade.page in javascript?
How can I use an array in blade.page in javascript?

Time:06-27

I have an array that I generated in my Controller.php page like this and I want to use it in blade.php page in javascript. I will explain the details below. I'm moving this to my blade.php page using compact('ids') .

array:11 [▼
  0 => 100485
  1 => 100496
  2 => 100497
  3 => 100498
  4 => 100499
  5 => 100500
  6 => 100502
  7 => 100504
  8 => 100482
  9 => 100486
  10 => 112995
]

Then there is an input like this on my blade.php page.

<input type="text" value="{{ request()->get('id') }}" name="id"  placeholder="ID" required>

There is a form like this.

 <form action="" id="your_form" onsubmit="yourFunction()">
            <div >
                <div >
                    <input id="coffee-submit"  type="submit" value="detail">
                </div>
            </div>
            <br>
        </form>

yourFunction() like this

var action_src = "http://localhost:8000/admin/"   document.getElementsByName("id")[0].value   "/orders";
var your_form = document.getElementById("your_form");
your_form.action = action_src;

No problems so far and it works. What I want to do is put a control in this function. If the value entered in the input exists in $ids, the function should work. So let me give an example:

var ids = <?php echo json_encode($ids); ?>;

if (ids.includes(document.getElementsByName("id")[0].value)) {
var action_src = "http://localhost:8000/admin/"   document.getElementsByName("id")[0].value   "/orders";
    var your_form = document.getElementById("your_form");
    your_form.action = action_src; 
}

I tried as above. I tried the following, it didn't work. var ids = JSON.parse('{{ json_encode($ids) }}');

CodePudding user response:

It seems like an issue with string to integer comparison. So I added Number()

var ids = [12, 13, 14, 15];


if (ids.indexOf(Number(document.getElementsByName("id")[0].value)) > -1) {
  console.log("ok, do the ajax");

} else {
  console.log("not found");
}
<input type="text" value="14" name="id"  placeholder="ID" required>

  • Related