Моя форма не позволяет отображать мой результат при клике - PullRequest
0 голосов
/ 27 сентября 2018

Я создал простой калькулятор оценок и сейчас просто работаю над мелочами.Один не позволяет пользователю не вводить ввод в поле ввода.Возможное решение этой проблемы - включить обязательный атрибут html5.Чтобы использовать это, я должен был поместить свой код в форму, подобную примеру W3Schools. HTML обязательный атрибут .

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

My code

    var Result;
    var Worth;
    var caPercentage;
    var gradeWanted;
    var examPercentage;
    var gradeWorth;
    var marksNeeded;

    //Calculates the Continous Assessment result based on users inputs 
    function calcCaPercentage() {
  
  	//result equals the users Continous Assesment results input value
	Result = parseFloat(document.getElementById("caResult").value);
  
  	//result equals over Continous Assesment Worth input value
	Worth = parseFloat(document.getElementById("caWorth").value);
	
	caPercentage = Worth * (Result / 100);
  
  	//CA Percentage result gets displayed here
	document.getElementById("caPercentage").innerHTML = caPercentage + "%";
  
  	//Returns the Continous Assessment Precentage for the other methods
	return caPercentage;
    }

    //Calcualtes the users exam percentage needed to get the grade they want
    function calcExamPercentage() {

  	//GradeWanted equals the grade the user wants     
	gradeWanted = parseFloat(document.getElementById("gradeWanted").value);
  
  	//x equals the Continous Assessment Precentage from the calcCaPercentage 
    function calcExamPercentage(){

	var x = calcCaPercentage();
	examPercentage = gradeWanted - x;
  
  	//Exam Percentage gets displayed here
	document.getElementById("examPercentage").innerHTML = examPercentage +"%";
  
  	//Returns the Exam Precentage for the other methods
	return examPercentage;
    }

    //Calculates the Marks needed for the user to get the grade they want
    function calcMarkNeeded() {

  	//gradeWorth equals what the overall Exam worth input
	gradeWorth = parseFloat(document.getElementById("gradeWorth").value);
  
  	//y equals the Exam Precentage from the calcExamPercentage function
	var y = calcExamPercentage();
  
  	//marksNeeded equals a round up version of the overall result
	marksNeeded = Math.floor((y / gradeWorth) * 100 /1);

  	//The marks needed will be displayed here
	document.getElementById("marksNeeded").innerHTML = marksNeeded + " Marks!";
    }
	<form>
		<div class="container">
		
			<div class="box boxInput1">

				<h4>Calculate your CA Percentage</h4>

				<p>Enter your CA Result: <input type="text" class="inputBox" placeholder="Enter you CA Result here.." id="caResult" required></p>
				

				<p>Enter overall CA mark: <input type="text" class="inputBox" placeholder="Enter what the CA is worth here.." id="caWorth" required></p>

				<!--
				<button type="submit" class="btn" onclick="calcCaPercentage()"> 
				<input type="submit" class="btn" onclick="calcCaPercentage()"> 
				-->

			</div>
			
			<div class="box boxResult boxInput1">
				<p><br>Your CA percentage is: <br><br><span id="caPercentage"></span></p>
			</div>
			
			<div class="box ">

				<h4>Calculate the percentage needed to pass the exam!</h4>

				<p>Enter the Grade you are aiming to achieve: <input type="text" class="inputBox" placeholder="Enter the Grade you want to get here.." id="gradeWanted" required></p>

				<!-- 
				<button type="button" class="btn" onclick="calcExamPercentage()">Calculate</button> 
				<input type="submit" class="btn" onclick="calcExamPercentage()">
				-->
			</div>
			
			<div class="box boxResult">
				<p><br>Percentage you need to pass the exam is: <br><br><span id="examPercentage"></span></p>
			</div>
			
			<div class="box">

				<h4>Calculate the marks needed to pass the exam!</h4>

				<p>Enter what your exam is worth overall: <br> <input type="text" class="inputBox" placeholder="Enter what the exam is worth here.." id="gradeWorth"></p>

				<input type="submit" class="btn" onclick="calcMarkNeeded()" required>
				<!-- <button type="button" class="btn"  onclick="calcMarkNeeded()">Calculate</button> -->

			</div>
			
			<div class="box boxResult">
				<p><br>You Need <br><br><span id="marksNeeded"></span></p>
			</div>
		
		</div>
  	
	</form>

Вот ссылка на мой код, работающий в Codepen

Является ли это недостатком использования форм?

1 Ответ

0 голосов
/ 27 сентября 2018

Просто измените <input type="submit" class="btn" onclick="calcMarkNeeded()" required> на <input type="button" class="btn" onclick="calcMarkNeeded()"> или <button class="btn" onclick=calcMarkNeeded()">Calculate</button>.

Кнопки отправки будут отправлять форму любому (серверному) действию, которое она определяет.Но сервер для отправки вашего запроса не прослушивается, поэтому ваш веб-сайт будет загружать пустую страницу вместо ответа на отправку формы.И пустая страница не содержит выходного div, в который вы пытаетесь записать результат.

Поэтому никогда не используйте <input type="submit">, если вы на самом деле не хотите отправить форму.Вместо этого можно использовать <input type="button"> и даже элемент <button></button>.

Кроме того, использование обязательного атрибута для кнопки ничего не дает.Кнопки должны быть нажаты, а не представлены.Вы не можете «заставить» пользователя нажать кнопку, используя требуемый, как вы можете «заставить» пользователя заполнить определенный ввод.

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