Я создаю форму, которая позволяет рассчитать рейтинг слона: https://jsfiddle.net/molecoder/1oqxsw81/.
Пользователь может выбирать между 4 вариантами, и каждый из этих вариантов (0 см, 1-2 см, ...) имеет соответствующее значение.
Вот код HTML для формы:
<form action = "" id = "bishopform" onsubmit = "return true;">
<div>
<fieldset>
<legend>Bishop score</legend>
<p>(modify one field to see the score)</p>
<div id = "bishopScore"></div>
<label><b>Cervical Dilatation</b></label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi1" onclick = "calculateTotalBishop()"/>0 cm</label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi2" onclick = "calculateTotalBishop()" checked/>1-2 cm</label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi3" onclick = "calculateTotalBishop()" />3-4 cm</label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi4" onclick = "calculateTotalBishop()"/>5-6 cm</label><br/>
<br/>
</fieldset>
</div>
</form>
Вот код JavaScript для обработки выбора:
var cervical_dilatation = new Array();
cervical_dilatation["cerdi1"]=0;
cervical_dilatation["cerdi2"]=1;
cervical_dilatation["cerdi3"]=2;
cervical_dilatation["cerdi4"]=3;
// getCervicalDilation() finds the points based on the answer to "Cervical Dilation".
// Here, we need to take user's the selection from radio button selection
function getCervicalDilation()
{
var cerdiPoints=0;
//Get a reference to the form id = "bishopform"
var theForm = document.forms["bishopform"];
//Get a reference to the answer the user Chooses name=selectedcervicaldilatation":
var selectedCervicalDilation = theForm.elements["selectedcervicaldilatation"];
//Here since there are 4 radio buttons selectedCervicalDilation.length = 4
//We loop through each radio buttons
for(var i = 0; i < selectedCervicalDilation.length; i++)
{
//if the radio button is checked
if (selectedCervicalDilation[i].checked)
{
//we set cerdiPoints to the value of the selected radio button
cerdiPoints = cervical_dilatation[selectedCervicalDilation[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cerdiPoints
return cerdiPoints;
}
function calculateTotalBishop()
{
//Here we get the Bishop Score by calling our function
//Each function returns a number so by calling them we add the values they return together
var bishopScore = 3*getCervicalDilation() + 1;
//display the result
var divobj = document.getElementById('bishopScore');
divobj.style.display='block';
divobj.innerHTML = bishopScore+"% likelihood that induction will be successful";
}
По какой-то конкретной причине я не могу увидеть результат выбора пользователя.
Как это исправить?
он был адаптирован отсюда: javascript-coder.com/javascript-form/…



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Это не работает из-за того, как JSFiddle обрабатывает свои скрипты в предварительном просмотре. Поскольку они вводят введенный скрипт в iframe с помощью метода window.onload, ваши функции становятся частный в новой области и не могут быть вызваны из html.
Ваш код работает ожидаемо, как и в скрипке от SO:
var cervical_dilatation = new Array();
cervical_dilatation["cerdi1"]=0;
cervical_dilatation["cerdi2"]=1;
cervical_dilatation["cerdi3"]=2;
cervical_dilatation["cerdi4"]=3;
// getCervicalDilation() finds the points based on the answer to "Cervical Dilation".
// Here, we need to take user's the selection from radio button selection
function getCervicalDilation()
{
var cerdiPoints=0;
//Get a reference to the form id = "bishopform"
var theForm = document.forms["bishopform"];
//Get a reference to the answer the user Chooses name=selectedcervicaldilatation":
var selectedCervicalDilation = theForm.elements["selectedcervicaldilatation"];
//Here since there are 4 radio buttons selectedCervicalDilation.length = 4
//We loop through each radio buttons
for(var i = 0; i < selectedCervicalDilation.length; i++)
{
//if the radio button is checked
if (selectedCervicalDilation[i].checked)
{
//we set cerdiPoints to the value of the selected radio button
cerdiPoints = cervical_dilatation[selectedCervicalDilation[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cerdiPoints
return cerdiPoints;
}
function calculateTotalBishop()
{
//Here we get the Bishop Score by calling our function
//Each function returns a number so by calling them we add the values they return together
var bishopScore = 3*getCervicalDilation() + 1;
//display the result
var divobj = document.getElementById('bishopScore');
divobj.style.display='block';
divobj.innerHTML = bishopScore+"% likelihood that induction will be successful";
}#bishopScore{
padding:10px;
font-weight:bold;
background-color:limegreen;
} <form action = "" id = "bishopform" onsubmit = "return true;">
<div>
<fieldset>
<legend>Bishop score</legend>
<p>(modify one field to see the score)</p>
<div id = "bishopScore"></div>
<label><b>Cervical Dilatation</b></label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi1" onclick = "calculateTotalBishop()"/>0 cm</label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi2" onclick = "calculateTotalBishop()" checked/>1-2 cm</label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi3" onclick = "calculateTotalBishop()" />3-4 cm</label><br/>
<label class='radiolabel'><input type = "radio" name = "selectedcervicaldilatation" value = "cerdi4" onclick = "calculateTotalBishop()"/>5-6 cm</label><br/>
<br/>
</fieldset>
</div>
</form>Проблема в том, что calculateTotalBishop() должен быть глобальной функцией ... Но jsfiddle обертывает ваш код в window.onload ... И по этой причине регистрируется ошибка, в которой говорится, что Uncaught ReferenceError: calculateTotalBishop is not defined
Чтобы исправить это, просто измените «Тип загрузки» в настройках js в jsfiddle с «onLoad» на «Без переноса в теле» ... Это решит проблему.
Рабочая рабочий пример: https://jsfiddle.net/1oqxsw81/1/
PS:
Рекомендуется использовать addEventListener в js вместо onclick в html
и будет намного лучше, если вы используете событие onchange, потому что значение можно также изменить с клавиатуры
Почему вы используете массив, но относитесь к нему как к объекту.