B
B
BoriHagen2020-04-23 22:41:47
JavaScript
BoriHagen, 2020-04-23 22:41:47

What is wrong in js code?

There is a code:

<select name="orderStatus" id="orderStatus" class="main__order-meta-data__order-status">
          <script>
            function checkStatus(){
              var status = document.getElementsByClassName("option").innerText;
              console.log(status);
              for (var i = 0; i < status.length; i++) {
                if ("<?echo $orders_data['order_status']?>" == status[i]){
                  status[i].setAttribute('selected');
                } else {
                  return false;
                }
              }
              
            }
          </script>
          <option class="option" onload="checkStatus()">Новый</option>
          <option class="option" onload="checkStatus()">Нужен доп звонок</option>
          <option class="option" onload="checkStatus()">Готов к отправке</option>
          <option class="option" onload="checkStatus()">Отправлен</option>
          <option class="option" onload="checkStatus()">Доставлен</option>
          <option class="option" onload="checkStatus()">Выкуплен</option>
        </select>


The logic of work is as follows: the database has a table with order data. There is an order status field. The order page has a select tag that allows you to select the order status. It is necessary for me that at opening of page of the order the status which is specified in a DB was selected. To do this, I wrote a script that collects the values ​​of all option tags and compares them with the value from the database. If a match is found, it adds the selected attribute to the desired option. But the code doesn't work.

I debugged the console with logs, apparently I somehow incorrectly get the values ​​​​of the elements themselves. I've gone through a bunch of sites.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
galaxy, 2020-04-24
@BoriHagen

If there is php, what else is there to sort through with javascript? Why is it impossible to put the selected attribute on the desired option via php?

<option class="option" <?if ($orders_data['order_status'] == "Новый"):?>selected<?endif?>>Новый</option>

D
Denis Ineshin, 2020-04-23
@IonDen

Immediate error:

document.getElementsByClassName("option") // вернет коллекцию элементов а не один элемент

A
anakondoz, 2020-04-23
@anakondoz

Try like this, status innerText is already on comparison

let status = document.getElementsByClassName('option');
console.log(status);
for (var i = 0; i < status.length; i++) {
  if ("Новый" == status[i].innerText){
    status[i].setAttribute('selected', '');
    console.log(status[i].innerText);
  }
}

Sandbox

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question