Call for HTML class method



  • User class available. He has two properties. We need a new copy of the class to be added to the fascinating list when we press the button to add value. JS:

    var Users=new Array();
    class User{
        constructor(text,option){
            this.text=text;
            this.option=option;
        }
        Add(){
            alert('Работает');
            var str=document.form.textarea.value;
            alert(str);
            var properties=new Array();
            properties=str.Split(',');
            alert(properties);
            var User=new User(properties[0],properties[1]);
            Users.push(User);
            UsersList.append(User);
            User.selected = true;
        }
    

    }

    HTML:

    <form class="form">
    <input name="textarea" onkeypress="return isNumberKey(event)" placeholder="Поле1"></textarea>
    <select id="UsersList">
    <option disabled>Список объектов</option>
    </select>
    <p><input type="button" value="Добавить значение" onclick="Add()"></p>
    <p><input type="submit" value="Пермешать"></p>
    <p><input type="submit" value="Вывести свойство"></p>
    <p><input type="submit" value="Вывести массив"></p>
    <!-- <input class="form__btn" type="button" onclick="Sum()" value="Добавить значения"> -->

    </form>

    Text of the assignment:
    Implement with JS classes:
    ∙ Set up a page in the form of two fields: a text-writing list;
    ∙ Add four buttons under these fields:
    o Add values
    o Change.
    o Remove property
    o Remove the mass
    ∙ When labelling &quot; add value &quot; the user &apos; s data, add to the facility the relevant properties:
    · text
    o option
    This object shall be added to the general area where all input values will be stored, and then clear the fields of form;
    ∙ When we cross the click, cross the objects.
    ∙ In the case of &quot; Remove the properties &quot; , remove the option of the last site in the mass;
    ∙ With the evidence on "Employ the mass" to remove the mass into the console, there's nothing difficult to do with this for your discretion, but it would be convenient for you to retrieve and test the crypt.



  • Well, let's go in order.

    var Users = new Array(); 
    // Дело вкуса, но я бы тут написал const users = [];
    

    // Класс здесь не нужен, можно обойтись стандартным классом Object.
    // Но если в задании так написано - можно и класс.
    class User{
    constructor(text,option){
    this.text=text;
    this.option=option;
    }
    }

    // В качестве метода класса вы не сможете вызвать эту функцию по onclick,
    // т.к. для этого нужен либо экземпляр класса, либо сделать этот метод static
    // - в любом случае нужно обращение к User.
    // Короче, как написал @Alexander Chernin - это должна быть отдельная функция.
    function Add(){
    // alert('Работает');
    console.log('Тоже работает и не надо нажимать ОК');

    // var str=document.form.textarea.value; 
    // document.form не существует. Есть document.forms, 
    // можно обратиться к вашей форме document.forms[0], 
    // но лучше использовать селектор:
    const form = document.querySelector('.form');
    
    const str=form.textarea.value; 
    console.log(str);
    
    // Я всё же считаю, что вы не совсем верно поняли задание 
    // и список - это не список пользователей, а список опций
    var option=form.optionslist.value;
    console.log(option);
    
    // var User= new User(str, option);
    // При таком объявлении с помощью var вы затираете 
    // в данной области видимости имя "User", 
    // которым у вас назывался ваш класс
    //  и на этой строчке (и внутри этой функции в целом с самого начала)
    // у вас User уже переменная без значения. (гуглить hoisting)
    
    const user = new User (str, option);
    // Это не обязательно, но среди разработчиков принято 
    // именовать классы с большой буквы, а экземпляры - с маленькой.
    // В данном случае решает вышеописанную проблему
    
    // В этой строчке всё было хорошо)
    Users.push(user);
    
    // Очистка формы
    form.textarea.value = "";
    form.optionslist.options[0].selected = true;
    

    }

    function printArray(){
    console.log(Users);
    }

    // Функции перемешивания массива и выведения свойства я оставил вам

    <form class="form">
    <!-- onkeypress="return isNumberKey(event)" нет такой функции -->
    <input name="textarea" placeholder="Поле1">
    <!--
    </textarea>
    Вы закрываете тег textarea, который не был открыт. input name= textarea - это не textarea, это другой тег и его не надо закрывать.
    -->
    <select id="UsersList" name="optionslist">
    <!-- Судя по заданию, здесь всё же нужны заранее заготовленные опции -->
    <option value="" disabled selected>Список опций</option>
    <option value="Option 1">Опция 1</option>
    <option value="Option 2">Опция 2</option>
    </select>
    <p><input type="button" value="Добавить значение" onclick="Add()" /></p>
    <p><input type="submit" value="Пермешать"></p>
    <p><input type="submit" value="Вывести свойство"></p>
    <p><input type="submit" value="Вывести массив" onclick="printArray()"></p>

    </form>



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2