• 🔥 Бесплатный курс от Академии Кодебай: «Анализ защищенности веб-приложений»

    🛡 Научитесь находить и использовать уязвимости веб-приложений.
    🧠 Изучите SQLi, XSS, CSRF, IDOR и другие типовые атаки на практике.
    🧪 Погрузитесь в реальные лаборатории и взломайте свой первый сайт!
    🚀 Подходит новичкам — никаких сложных предварительных знаний не требуется.

    Доступ открыт прямо сейчас Записаться бесплатно

Скрипт теста на Javascript

  • Автор темы Автор темы -
  • Дата начала Дата начала
Статус
Закрыто для дальнейших ответов.
?

-

Появилась необходимость сделать тест. Ввиду того, что JavaScript я практически не знаю полез в Google, после недолгих поисков было найдено следующие :

Код:
<head>
<script type="text/javascript">
function showById(id, visible) {
document.getElementById(id).style.display =
visible ? 'block' : 'none'
}
function processForm(f) {
var i, s='', el
var questions = new Object()
var answers = new Object()
for (i=0; i<f.length; i++) {
el = f.elements[i]
if (el.type=='radio' && el.name.indexOf('question')==0) {
questions[el.name] = 0
if (el.checked)
answers[el.name] = parseInt(el.value)
}
}
s = '\n'
var asked = 0, answered = 0, score = 0
for (i in questions) asked++
for (i in answers) {
s += '\n' + i + ' = ' + answers[i]
answered++
score += answers[i]
}
alert(
'Answered '+ answered + ' of ' + asked + ' questions'
+ '\n--------------answers:-----------------'
+ s
+ '\n ---------------------------------------'
+ '\nScore = ' + score
)
if (answered < asked) {
alert('Вы ответили на '+answered+' вопросов из '+asked+'. Для получения достоверного результата нужно ответить на все воросы')
}
else {
showById('questionsForm', false)
el = document.getElementById('score')
el.innerHTML = (score>0) ? '+'+score : score
showById('results', true)
if (score > 0)
showById('explain-positive', true)
else if (score < 0)
showById('explain-negative', true)
else if (score == 0)
showById('explain-zero', true)
}
}
function resetTest() {
showById('results', false)
showById('questionsForm', true)
document.forms['opros'].reset()
}
</script>
</head>
<body>
<h2>Опрос</h2>
<div id="questionsForm">
<form name="opros">
<p/>
<strong>1.</strong><br/>Ты ежик.<br/>
<input type="radio" name="question1" value="1" id="q1a1"/><label for="q1a1">Скорее "да"</label>
<input type="radio" name="question1" value="-1" id="q1a2"/><label for="q1a2">Скорее "нет"</label>
<br/>
<hr/>
<p/>
<strong>2.</strong><br/>У нормального ежика 3 головы.<br/>
<input type="radio" name="question2" value="1" id="q2a1"/><label for="q2a1">Скорее "да"</label>
<input type="radio" name="question2" value="-1" id="q2a2"/><label for="q2a2">Скорее "нет"</label>
<hr/>
<p/>
<strong>3.</strong><br/>А если подумать?<br/>
<input type="radio" name="question3" value="1" id="q3a1"/><label for="q3a1">Скорее "да"</label>
<input type="radio" name="question3" value="-1" id="q3a2"/><label for="q3a2">Скорее "нет"</label>
<hr/>
<p/>
<strong>4.</strong><br/>Хочешь три яблочка?<br/>
<input type="radio" name="question4" value="1" id="q4a1"/><label for="q4a1">Скорее "да"</label>
<input type="radio" name="question4" value="-1" id="q4a2"/><label for="q4a2">Скорее "нет"</label>
<hr/>
<p/>
<input type="button" value="Отправить" onClick="processForm(this.form)"/>
<input type="reset" value="Очистить"></input>
</form>
</div>
<hr/>
<div id="results" style="display: none;">
<h3>Ваш результат: <span id="score" style="font-size: 160%"></span></h3>
<div id="explain-positive" style="display: none;">
<!-- Здесь расшифровка для положительного результата -->
<p>Поздравляем! Положительный результат говорит, что вы, как минимум, ежик.</p>
</div>
<div id="explain-negative" style="display: none;">
<!-- Здесь расшифровка для отрицательного результата -->
<p>Блеск! Никогда не видел, чтоб ежики так здорово отвечали.</p>
</div>
<div id="explain-zero" style="display: none;">
<!-- Здесь расшифровка для нулевого результата -->
<p>Удивительно! Нулевой результат - редкость.
Одно из двух: вы либо еж-зануда, либо зубная щетка!</p>
</div>
<hr/>
<p>Спасибо за участие в тестировании, йооожик :0)</p>
<input type="button" value="Начать заново" onClick="resetTest()"/>
</div>
</body>

Немного подправил под свои запросы:

Код:
<head>
<script type="text/javascript">
function showById(id, visible) {
document.getElementById(id).style.display =
visible ? 'block' : 'none'
}
function processForm(f) {
var i, s='', el
var questions = new Object()
var answers = new Object()
for (i=0; i<f.length; i++) {
el = f.elements[i]
if (el.type=='radio' && el.name.indexOf('question')==0) {
questions[el.name] = 0
if (el.checked)
answers[el.name] = parseInt(el.value)
}
}
var asked = 0, answered = 0, score = 0
for (i in questions) asked++
for (i in answers) {
answered++
score += answers[i]
}
if (answered < asked) {
alert('Вы ответили на '+answered+' вопросов из '+asked+'. Для получения достоверного результата нужно ответить на все воросы')
}
else {
showById('questionsForm', false)
el = document.getElementById('score')
el.innerHTML = (score>0) ? '+'+score : score
showById('results', true)
if (score == 0)
showById('1-', true)
else if (score == 1)
showById('1-', true)
else if (score == 2)
showById('1', true)
else if (score == 3)
showById('1+', true)
else if (score == 4)
showById('2-', true)	
else if (score == 5)
showById('2', true)	
else if (score == 6)
showById('2+', true)
else if (score == 7)
showById('3-', true)
else if (score == 8)
showById('3', true)
else if (score == 9)
showById('3+', true)
else if (score == 10)
showById('4-', true)
else if (score == 11)
showById('4', true)
else if (score == 12)
showById('4+', true)
else if (score == 13)
showById('5-', true)
else if (score == 14)
showById('5', true)
else if (score == 15)
showById('5+', true)
}
}
function resetTest() {
showById('results', false)
showById('questionsForm', true)
document.forms['opros'].reset()
}
</script>
</head>
<body>
<br>
<hr width="100%" size=2>
<h3 align="center">Тест “0” по английскому разговорному языку для самых начинающих на употребление основных глаголов “быть” и “иметь”:</h3>
<hr width="100%" size=2>
<br>
<div id="questionsForm">
<form name="opros">
<p/>
<strong><font color="#FF0000">1.</font> Вопрос:</strong> <font color="#0000FF">Какое слово указывает на неопределённую форму глагола?</font>
<br/><br/>
<input type="radio" name="question1" value="0" id="q1a1"/><label for="q1a1">1. too</label>
<br/>
<input type="radio" name="question1" value="0" id="q1a2"/><label for="q1a2">2. be</label>
<br/>
<input type="radio" name="question1" value="1" id="q1a3"/><label for="q1a3">3. to</label>
<br/>
<input type="radio" name="question1" value="0" id="q1a4"/><label for="q1a4">4. are</label>
<br/><br/>
<strong><font color="#FF0000">2.</font> Вопрос:</strong> <font color="#0000FF">Какая форма глагола <strong>to be</strong> указывает на 3 лицо единственного числа?</font>
<br/>
<br/>
<input type="radio" name="question2" value="0" id="q2a1"/><label for="q2a1">1. am</label>
<br/>
<input type="radio" name="question2" value="1" id="q2a2"/><label for="q2a2">2. is</label>
<br/>
<input type="radio" name="question2" value="0" id="q2a3"/><label for="q2a3">3. as</label>
<br/>
<input type="radio" name="question2" value="0" id="q2a4"/><label for="q2a4">4. has</label>
<br/><br/>
<strong><font color="#FF0000">3.</font> Вопрос:</strong> <font color="#0000FF">Отрицательная форма инфинитива: Какой вариант правильный?</font>
<br/><br/>
<input type="radio" name="question3" value="0" id="q3a1"/><label for="q3a1">1. will not</label>
<br/>
<input type="radio" name="question3" value="0" id="q3a2"/><label for="q3a2">2. to not have</label>
<br/>
<input type="radio" name="question3" value="0" id="q3a3"/><label for="q3a3">3. are not</label>
<br/>
<input type="radio" name="question3" value="1" id="q3a4"/><label for="q3a4">4. not to have</label>
<br/><br/>
<strong><font color="#FF0000">4.</font> Вопрос:</strong> <font color="#0000FF">Сокращённая форма <strong>to be</strong>: Какой вариант правильный?</font>
<br/>
<br/>
<input type="radio" name="question4" value="0" id="q4a1"/><label for="q4a1">1. I haven’t English.</label>
<br/>
<input type="radio" name="question4" value="0" id="q4a2"/><label for="q4a2">2. I amn’t English.</label>
<br/>
<input type="radio" name="question4" value="1" id="q4a3"/><label for="q4a3">3. I’m not English</label>
<br/>
<input type="radio" name="question4" value="0" id="q4a4"/><label for="q4a4">4. I isn’t English.</label>
<br/><br/>
<strong><font color="#FF0000">5.</font> Вопрос:</strong> <font color="#0000FF">Усилительный глагол для <strong>to have</strong>: Какой вариант правильный?</font>
<br/>
<br/>
<input type="radio" name="question5" value="1" id="q5a1"/><label for="q5a1">1. got</label>
<br/>
<input type="radio" name="question5" value="0" id="q5a2"/><label for="q5a2">2. had</label>
<br/>
<input type="radio" name="question5" value="0" id="q5a3"/><label for="q5a3">3. will</label>
<br/>
<input type="radio" name="question5" value="0" id="q5a4"/><label for="q5a4">4. am</label>
<br/><br/>
<strong><font color="#FF0000">6.</font> Вопрос:</strong> <font color="#0000FF">Разговорный стиль языка: Какой вариант правильный?</font>
<br/><br/>
<input type="radio" name="question6" value="0" id="q6a1"/><label for="q6a1">1. They all are my friends.</label>
<br/>
<input type="radio" name="question6" value="0" id="q6a2"/><label for="q6a2">2. All they are my friends.</label>
<br/>
<input type="radio" name="question6" value="0" id="q6a3"/><label for="q6a3">3. They are my friends all.</label>
<br/>
<input type="radio" name="question6" value="1" id="q6a4"/><label for="q6a4">4. They’re all my best friends.</label>
<br/><br/>
<strong><font color="#FF0000">7.</font> Вопрос:</strong> <font color="#0000FF">Разговорный стиль для <strong>to have</strong>: Какой вариант правильный?</font>
<br/>
<br/>
<input type="radio" name="question7" value="0" id="q7a1"/><label for="q7a1">1. He got have a car.</label>
<br/>
<input type="radio" name="question7" value="1" id="q7a2"/><label for="q7a2">2. He’s got a car.</label>
<br/>
<input type="radio" name="question7" value="0" id="q7a3"/><label for="q7a3">3. He has a car.</label>
<br/>
<input type="radio" name="question7" value="0" id="q7a4"/><label for="q7a4">4. He have a car.</label>
<br/><br/>
<strong><font color="#FF0000">8.</font> Вопрос:</strong> <font color="#0000FF">Какой вспомогательный глагол указывает на будущее время?</font>
<br/><br/>
<input type="radio" name="question8" value="1" id="q8a1"/><label for="q8a1">1. will</label>
<br/>
<input type="radio" name="question8" value="0" id="q8a2"/><label for="q8a2">2. shall</label>
<br/>
<input type="radio" name="question8" value="0" id="q8a3"/><label for="q8a3">3. would</label>
<br/>
<input type="radio" name="question8" value="0" id="q8a4"/><label for="q8a4">4. were</label>
<br/><br/>
<strong><font color="#FF0000">9.</font> Вопрос:</strong> <font color="#0000FF">Официальный стиль языка: Какой вариант правильный?</font>
<br/><br/>
<input type="radio" name="question9" value="0" id="q9a1"/><label for="q9a1">1. We’ve got three English classes a week.</label>
<br/>
<input type="radio" name="question9" value="0" id="q9a2"/><label for="q9a2">2. We got have three English classes a week.</label>
<br/>
<input type="radio" name="question9" value="1" id="q9a3"/><label for="q9a3">3. We have three English classes a week.</label>
<br/>
<input type="radio" name="question9" value="0" id="q9a4"/><label for="q9a4">4. We have got three English classes a week.</label>
<br/><br/>
<strong><font color="#FF0000">10.</font> Вопрос:</strong> <font color="#0000FF">Глаголы множественного числа: Какой вариант правильный?</font>
<br/><br/>
<input type="radio" name="question10" value="0" id="q10a1"/><label for="q10a1">1. are – will</label>
<br/>
<input type="radio" name="question10" value="1" id="q10a2"/><label for="q10a2">2. are – were</label>
<br/>
<input type="radio" name="question10" value="0" id="q10a3"/><label for="q10a3">3. have – were</label>
<br/>
<input type="radio" name="question10" value="0" id="q10a4"/><label for="q10a4">4. are – has</label>
<br/><br/>
<strong><font color="#FF0000">11.</font> Вопрос:</strong> <font color="#0000FF">Какой вспомогательный глагол указывает на сослагательное наклонение?</font>
<br/><br/>
<input type="radio" name="question11" value="0" id="q11a1"/><label for="q11a1">1. were</label>
<br/>
<input type="radio" name="question11" value="0" id="q11a2"/><label for="q11a2">2. will</label>
<br/>
<input type="radio" name="question11" value="1" id="q11a3"/><label for="q11a3">3. would</label>
<br/>
<input type="radio" name="question11" value="0" id="q11a4"/><label for="q11a4">4. shall</label>
<br/><br/>
<strong><font color="#FF0000">12.</font> Вопрос:</strong> <font color="#0000FF">Какие глаголы <strong>to be</strong> выражают прошедшее время?</font>
<br/><br/>
<input type="radio" name="question12" value="1" id="q12a1"/><label for="q12a1">1. was – were – had</label>
<br/>
<input type="radio" name="question12" value="0" id="q12a2"/><label for="q12a2">2. will – was – had</label>
<br/>
<input type="radio" name="question12" value="0" id="q12a3"/><label for="q12a3">3. had – are – were</label>
<br/>
<input type="radio" name="question12" value="0" id="q12a4"/><label for="q12a4">4. be – were - had</label>
<br/><br/>
<strong><font color="#FF0000">13.</font> Вопрос:</strong> <font color="#0000FF">Какое предложение является неправильным?</font>
<br/><br/>
<input type="radio" name="question13" value="0" id="q13a1"/><label for="q13a1">1. You haven’t got in Moscow any business.</label>
<br/>
<input type="radio" name="question13" value="0" id="q13a2"/><label for="q13a2">2. You has not any business in Moscow.</label>
<br/>
<input type="radio" name="question13" value="0" id="q13a3"/><label for="q13a3">3. In Moscow you had not any business.</label>
<br/>
<input type="radio" name="question13" value="1" id="q13a4"/><label for="q13a4">4. You hadn’t got any business in Moscow.</label>
<br/><br/>
<strong><font color="#FF0000">14.</font> Вопрос:</strong> <font color="#0000FF">В каком варианте все отрицательные формы правильные?</font>
<br/><br/>
<input type="radio" name="question14" value="0" id="q14a1"/><label for="q14a1">1. isn’t – haven’t – won’t be – amn’t – hasn’t – wouldn’t be</label>
<br/>
<input type="radio" name="question14" value="1" id="q14a2"/><label for="q14a2">2. isn’t – haven’t – won’t be – aren’t – hasn’t – wouldn’t be</label>
<br/>
<input type="radio" name="question14" value="0" id="q14a3"/><label for="q14a3">3. isn’t – haven’t – wouldn’t be – aren’t – hasn’t – willn’t be</label>
<br/>
<input type="radio" name="question14" value="0" id="q14a4"/><label for="q14a4">4. isn’t – havn’t – won’t be – aren’t – hasn’t – wouln’t be</label>
<br/><br/>
<strong><font color="#FF0000">15.</font> Вопрос:</strong> <font color="#0000FF">Разговорный стиль: Какой вариант правильный?</font>
<br/><br/>
<input type="radio" name="question15" value="0" id="q15a1"/><label for="q15a1">1. She have two children. They’re in America now.</label>
<br/>
<input type="radio" name="question15" value="0" id="q15a2"/><label for="q15a2">2. She’s got two children. They were in America now.</label>
<br/>
<input type="radio" name="question15" value="1" id="q15a3"/><label for="q15a3">3. She’s got two children. They’re in America now.</label>
<br/>
<input type="radio" name="question15" value="0" id="q15a4"/><label for="q15a4">4. She got two children. They are in America now.</label>
<br/><br/>
<input type="button" value="Отправить" onClick="processForm(this.form)"/>
<input type="reset" value="Очистить"></input>
</form>
</div>
<hr/>
<div id="results" style="display: none;">
Количество правильных ответов: <span id="score"></span>
<div id="1-" style="display: none;">
<p>Ваша оценка: 1-</p>
</div>
<div id="1-" style="display: none;">
<p>Ваша оценка: 1-</p>
</div>
<div id="1" style="display: none;">
<p>Ваша оценка: 1</p>
</div>
<div id="1+" style="display: none;">
<p>Ваша оценка: 1+</p>
</div>
<div id="2-" style="display: none;">
<p>Ваша оценка: 2-</p>
</div>
<div id="2" style="display: none;">
<p>Ваша оценка: 2</p>
</div>
<div id="2+" style="display: none;">
<p>Ваша оценка: 2+</p>
</div>
<div id="3-" style="display: none;">
<p>Ваша оценка: 3-</p>
</div>
<div id="3" style="display: none;">
<p>Ваша оценка: 3</p>
</div>
<div id="3+" style="display: none;">
<p>Ваша оценка: 3+</p>
</div>
<div id="4-" style="display: none;">
<p>Ваша оценка: 4-</p>
</div>
<div id="4" style="display: none;">
<p>Ваша оценка: 4</p>
</div>
<div id="4+" style="display: none;">
<p>Ваша оценка: 4+</p>
</div>
<div id="5-" style="display: none;">
<p>Ваша оценка: 5-</p>
</div>
<div id="5" style="display: none;">
<p>Ваша оценка: 5</p>
</div>
<div id="5+" style="display: none;">
<p>Ваша оценка: 5+</p>
</div>
<hr/>
<p>Спасибо за участие в тестировании</p>
<input type="button" value="Начать заново" onClick="resetTest()"/>
</div>
<br><br>
</body>

Суть того, что мне надо было: есть 15 вопросов, у каждого вопроса есть 4 варианта ответа, неправильный ответ = 0 балов, правильный = 1 бал, после нажатия кнопки «Отправить» скрипт показывает количество правильных ответов и оценку.
Нужна ваша помощь в следующим:
1) количество правильных ответов выводится как «+10», нужно «+» убрать, в маём тесте он не нужен ибо количество балов всегда > 0
2) после нажатия кнопки «Начать заново» и повторном прохождении теста в качестве результата скрипт ставит оценку дважды, тоесть показывает ещё результат предыдущей попытки. Это надо исправить, мне нужен только один результат.
3) по возможности скрипт надо упростить

Знающие люди помогите пожалуйста.
 
Добрый день!
Мне кажется, что даже знающие люди не будут лопатить такую кучу кода...

Могу помочь вот чем:
У меня есть прога, которая по текстовому файлу в определенном формате (простом и интуитивно понятном), создает тест на хтмл и javascript (т.е. получается страничка с тестом). Работает корректно.
Может быть тебе будет проще создать свой тест там, и если нужно будет, отредактировать его.

Заинтересовало? оставь мыло
 
Для: Temir kiber-nik@ya.ru. Заранее спасибо :)

А кода в принципе не так много как кажется на первый взгляд, там просто одно и тоже повторяется.
Могу сократить в 10 раз.
Там надо вобщем-то только 2 небольших момента подправить:
1) <span id="score"> чтобы ответ без знака выходил.
2) и тут:
}
function resetTest() {
showById('results', false)
showById('questionsForm', true)
document.forms['opros'].reset()
}
чтобы при повторном прохождение теста предыдущий результат не появлялся.

Оптимизация для меня не столь важна как эти два момента.
 
Спасибо Temir
Эту программу я уже видел к сожалению не помогло.
 
Статус
Закрыто для дальнейших ответов.
Мы в соцсетях:

Взломай свой первый сервер и прокачай скилл — Начни игру на HackerLab