Почему моя HTML-страница перезагружается при каждой отправке новой записи в форму? - PullRequest
1 голос
/ 07 июня 2019

У меня проблемы с моей HTML страницей. Моя программа предназначена для сбора имен с помощью формы, а затем вывод их в таблицу под формой. Это возможно, когда страница не перезагружается.

При первом вводе определенного имени страница перезагружается. После перезагрузки страницы, когда я ввожу то же имя, она не перезагружается при нажатии ввода в любой последующий момент. Я не знаю, почему это так и как это исправить.

Вот связанный файл JS

// Gloabal Variables
var enteredName,
  countOutput,
  count,
  table,
  form,
  allNames = [];

function project62Part2() {
  // Your code goes in here.
  function getElements() {
    form = document.getElementById("nameForm");
    countOutput = document.getElementById("numNames");
    table = document.getElementById("table");
  }

  function addName() {
    enteredName = form.name.value;
    allNames.push(enteredName);
  }

  function countNames() {
    // Reset count
    count = 0;

    // Loop through and count names
    for (i = 0; i < allNames.length; i++) {
      count++;
    }
  }

  function output() {
    // Reset table
    table.innerHTML = "<tr><th>Names</th></tr>";
    // Display count
    countOutput.innerHTML = "Total names entered: " + count;

    // Loop through and add to table display
    for (i = 0; i < allNames.length; i++) {
      table.innerHTML += "<tr><td>" + allNames[i] + "</td></tr>";
    }
  }

  // Call code
  getElements();
  addName();
  countNames();
  output();

  // Prevent page from reloading
  return false;
}
<form id="nameForm" action="#">
  <label class="formLabel" for="name">Name: </label>
  <input id="name" name="name" />

  <input type="submit" name="runExample" value="Submit" class="formatSubmit" onclick="project62Part2()" />
</form>

<div id="numNames">Total names entered: </div>

<table id="table"></table>

Мое понимание кодирования в лучшем случае элементарно, поэтому, хотя я был бы признателен за любой ответ, я бы предпочел, чтобы он был простым!

Ответы [ 4 ]

2 голосов
/ 07 июня 2019

<input type='submit'> вызывает обновление страницы.Замените его на <input type='button'>.

Подробнее здесь .

        // Gloabal Variables
    var enteredName,
    	countOutput,
    	count,
        table,
    	form,
    	allNames = [];
    
    function project62Part2() {
        // Your code goes in here.
        function getElements() {
    		form = document.getElementById("nameForm");
    		countOutput = document.getElementById("numNames");
    		table = document.getElementById("table");
    	}
        
    	function addName() {
    		enteredName = form.name.value;
    		allNames.push(enteredName);
    	}
    	
    	function countNames() {
    		// Reset count
    		count = 0;
    		
    		// Loop through and count names
    		for (i = 0; i < allNames.length; i++) {
    			count++;
    		}
    	}
    	
    	function output() {
    		// Reset table
    		table.innerHTML = "<tr><th>Names</th></tr>";
    		// Display count
    		countOutput.innerHTML = "Total names entered: " + count;
    		
    		// Loop through and add to table display
    		for (i = 0; i < allNames.length; i++) {
    			table.innerHTML += "<tr><td>" + allNames[i] + "</td></tr>";
    		}
    	}
    	
    	// Call code
    	getElements();
    	addName();
    	countNames();
    	output();
    
    	// Prevent page from reloading
    	return false;
    }
    <form id="nameForm" action="6.2projectpart2.html#">
        <label class="formLabel" for="name">Name: </label>
        <input id="name" name="name" />
        
        <input type="button" name="runExample" value="Submit" class="formatSubmit" onclick="project62Part2()" />
    </form>
    
    <div id="numNames">Total names entered: </div>
    
    <table id="table"></table>
1 голос
/ 07 июня 2019

Есть много способов добиться этого, я объясню два пути:

1. Добавление Event.preventDefault() метод

Каждый раз, когда вы нажимаете <input> элементы типа submit, пользовательский агент пытается отправить форму для настройки URL в форме.

Теперь метод preventDefault() сообщает пользовательскому агенту, что если событие не обрабатывается явно, его действие по умолчанию не должно выполняться, как обычно. Это означает, что интерфейс Form не перезагрузит страницу.

Как это устроено?
  • ну, просто добавьте переменную события к вашему submit вызову так:
<input type="submit" name="runExample" value="Submit" class="formatSubmit" onclick="project62Part2(event)" />
  • Затем добавьте параметр event в метод project62Part2().
function project62Part2(event) {
   event.preventDefault();

   ...

}

// Gloabal Variables
var enteredName,
  countOutput,
  count,
  table,
  form,
  allNames = [];

function project62Part2(event) {
   event.preventDefault();
  // Your code goes in here.
  function getElements() {
    form = document.getElementById("nameForm");
    countOutput = document.getElementById("numNames");
    table = document.getElementById("table");
  }

  function addName() {
    enteredName = form.name.value;
    allNames.push(enteredName);
  }

  function countNames() {
    // Reset count
    count = 0;

    // Loop through and count names
    for (i = 0; i < allNames.length; i++) {
      count++;
    }
  }

  function output() {
    // Reset table
    table.innerHTML = "<tr><th>Names</th></tr>";
    // Display count
    countOutput.innerHTML = "Total names entered: " + count;

    // Loop through and add to table display
    for (i = 0; i < allNames.length; i++) {
      table.innerHTML += "<tr><td>" + allNames[i] + "</td></tr>";
    }
  }

  // Call code
  getElements();
  addName();
  countNames();
  output();

  // Prevent page from reloading
  return false;
}
<form id="nameForm" action="#">
  <label class="formLabel" for="name">Name: </label>
  <input id="name" name="name" />

  <input type="submit" name="runExample" value="Submit" class="formatSubmit" onclick="project62Part2(event)" />
</form>

<div id="numNames">Total names entered: </div>

<table id="table"></table>

2. Замена input на button

Это основано на предыдущем объяснении. Если элемент <input> типа submit инициирует вызов на отправку, то если вы замените его на тип button, вызов на отправку не будет инициирован. Я рекомендую вам это сохранить submit, если вы работаете с серверными вызовами.

Как это устроено?
  • ну, просто замените тип с submit на button следующим образом:
<input type="button" name="runExample" value="Submit" class="formatSubmit" onclick="project62Part2()" />

// Gloabal Variables
var enteredName,
  countOutput,
  count,
  table,
  form,
  allNames = [];

function project62Part2() {
  event.preventDefault();
  // Your code goes in here.
  function getElements() {
    form = document.getElementById("nameForm");
    countOutput = document.getElementById("numNames");
    table = document.getElementById("table");
  }

  function addName() {
    enteredName = form.name.value;
    allNames.push(enteredName);
  }

  function countNames() {
    // Reset count
    count = 0;

    // Loop through and count names
    for (i = 0; i < allNames.length; i++) {
      count++;
    }
  }

  function output() {
    // Reset table
    table.innerHTML = "<tr><th>Names</th></tr>";
    // Display count
    countOutput.innerHTML = "Total names entered: " + count;

    // Loop through and add to table display
    for (i = 0; i < allNames.length; i++) {
      table.innerHTML += "<tr><td>" + allNames[i] + "</td></tr>";
    }
  }

  // Call code
  getElements();
  addName();
  countNames();
  output();

  // Prevent page from reloading
  return false;
}
<form id="nameForm" action="#">
  <label class="formLabel" for="name">Name: </label>
  <input id="name" name="name" />

  <input type="button" name="runExample" value="Submit" class="formatSubmit" onclick="project62Part2()" />
</form>

<div id="numNames">Total names entered: </div>

<table id="table"></table>
1 голос
/ 07 июня 2019

Вы можете изменить с <input type="submit" name="runExample" /> на

<input type="button" name="runExample" />

или

Удалите onclick="project62Part2()" с тега ввода и перейдите к тегу формы onsubmit="return project62Part2()"

<form id="nameForm" onsubmit="return project62Part2()">
0 голосов
/ 07 июня 2019

попробуйте добавить параметр события в project62Part2, затем выполните event.preventDefault () внутри

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...