Валидация формы
Здравствуйте.Я создал форму,проверка котороый должна осуществляться на javascript при нажатии на "отправить".Вот мой код:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Форма</title> <style> body { background: #f6e8d7; } #helpMe { background: #f0f0f0; width: 400px; padding: 10px; /* Iiey border: 2px solid #000; } input[type="submit"] { border: 4px inset #100; cursor: url(WorldOfWarCraft/arrow.cur),pointer; } p b { color:orange; border: 1px inset #100; box-shadow: 0 0 10px rgba(0,0,0,0.5); background: #808080; outline-style: outset; } img.rightfoto { float:right; margin: 4px 750px 2px 0px; } </style> </head> <body> <form method="GET" action="handler.php" class="formWithValidation"> <img class="rightfoto" src="image.png" alt="aeuoa?iaoeaiue oaeno" > <fieldset style="width: 400px;"> <p><b name="textX"> X</b></p> <div id="helpMe"> <input type="checkbox" class='checkboxxx field' name="InputX" value="2"> 2 <input type="checkbox" class='checkboxxx field' name="InputX" value="-1.5">-1.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="-1">-1 <input type="checkbox" class='checkboxxx field' name="InputX" value="-0.5">-0.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="0">0 <input type="checkbox" class='checkboxxx field' name="InputX" value="0.5">0.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="1">1 <input type="checkbox" class='checkboxxx field' name="InputX" value="1.5">1.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="2">2 </div> <Br> <p><b> Y</b></p> <p><input type="text" class="Y" maxlength="5" size="6" name="InputY" placeholder=" от -3 до 3"></p> <p><b> R</b></p> <p> <input name="InputR" class='RRR field' type="radio" value="1">1 <input name="InputR" class='RRR field' type="radio" value="1.5"> 1.5 <input name="InputR" class='RRR field' type="radio" value="2"> 2 <input name="InputR" class='RRR field' type="radio" value="2.5"> 2.5 <input name="InputR" class='RRR field' type="radio" value=" 3"> 3 </p> <p><input type="submit" onclick="validate(this.form)" class="validateBtn" ></p> </fieldset> </form> <script> var SMSx; var SMSy; var SMSr; function showError(container, errorMessage) { container.className = 'error'; var msgElem = document.createElement('span'); msgElem.className = "error-message"; msgElem.innerHTML = errorMessage; container.appendChild(msgElem); } function resetError(container) { container.className = ''; if (container.lastChild.className == "error-message") { container.removeChild(container.lastChild); } } function validate(form) { event.preventDefault(); var elems = form.elements; resetError(document.body); if (elems.InputY.value) { SMSy="" } else { SMSy=" Введите Y <Br>" } resetError(document.body); if ((elems['InputX'][0].checked==true)||(elems['InputX'][1].checked==true)|| (elems['InputX'][2].checked==true)||(elems['InputX'][3].checked==true)|| (elems['InputX'][4].checked==true)||(elems['InputX'][5].checked==true)|| (elems['InputX'][6].checked==true)||(elems['InputX'][7].checked==true) ||(elems['InputX'][7].checked==true)) { SMSx="" } else { SMSx="<p style="font-size: 120%; font-family: monospace; color: #cd66cc">Введите X </p> "; } if ((elems['InputR'][0].checked==true)||(elems['InputR'][1].checked==true)|| (elems['InputR'][2].checked==true)||(elems['InputR'][3].checked==true)|| (elems['InputR'][4].checked==true)) { SMSr="" } else { SMSr="Введите R <Br>"; } showError(document.body, SMSx+SMSy+SMSr); } </script> </body> </html> event.preventDefault(); По идее эта функция должна отключать действие по умолчанию,т.е переход к скрипту на php,но этого не происходит.Почему? |
1) откуда переменная event?
2) поменять type на button 3) https://stackoverflow.com/questions/...194739#7194739 4) повесить "слушатель" ) |
Потому, что нет у кнопки с событием click действия по умолчанию. Удалите у нее обработчик и добавьте форме onsubmit="validate(this)", проверьте после этого (то есть, в обеих случаях вывести в консоль event).
|
Цитата:
|
Цитата:
1)Так вроде ж объект события автоматически появляется при срабатывании нажатия,автоиматически в качестве параметра в функцию добавляется |
Я повесил слушатель,Но не работает
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Ôîðìû</title> <style> body { background: #f6e8d7; } #helpMe { background: #f0f0f0; /* Oaao oiia */ width: 400px; /* Oe?eia aeiea */ padding: 10px; /* Iiey */ border: 2px solid #000; /* Ia?aiao?u ?aiee */ } input[type="submit"] { border: 4px inset #100; cursor: url(WorldOfWarCraft/arrow.cur),pointer; } p b { color:orange; border: 1px inset #100; box-shadow: 0 0 10px rgba(0,0,0,0.5); background: #808080; outline-style: outset; } img.rightfoto { float:right; margin: 4px 750px 2px 0px; } </style> </head> <body> <form method="GET" action="handler.php" class="formWithValidation"> <img class="rightfoto" src="image.png" alt="aeuoa?iaoeaiue oaeno" > <fieldset style="width: 400px;"> <p><b name="textX"> X</b></p> <div id="helpMe"> <input type="checkbox" class='checkboxxx field' name="InputX" value="2"> 2 <input type="checkbox" class='checkboxxx field' name="InputX" value="-1.5">-1.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="-1">-1 <input type="checkbox" class='checkboxxx field' name="InputX" value="-0.5">-0.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="0">0 <input type="checkbox" class='checkboxxx field' name="InputX" value="0.5">0.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="1">1 <input type="checkbox" class='checkboxxx field' name="InputX" value="1.5">1.5 <input type="checkbox" class='checkboxxx field' name="InputX" value="2">2 </div> <Br> <p><b> Y</b></p> <p><input type="text" class="Y" maxlength="5" size="6" name="InputY" placeholder=" от -3 до 3"></p> <p><b> R</b></p> <p> <input name="InputR" class='RRR field' type="radio" value="1">1 <input name="InputR" class='RRR field' type="radio" value="1.5"> 1.5 <input name="InputR" class='RRR field' type="radio" value="2"> 2 <input name="InputR" class='RRR field' type="radio" value="2.5"> 2.5 <input name="InputR" class='RRR field' type="radio" value=" 3"> 3 </p> <p><input type="submit" class="validateBtn" ></p> </fieldset> </form> <script> var SMSx; var SMSy; var SMSr; var form=document.querySelector('.formWithValidation'); function showError(container, errorMessage) { container.className = 'error'; var msgElem = document.createElement('span'); msgElem.className = "error-message"; msgElem.innerHTML = errorMessage; container.appendChild(msgElem); } function resetError(container) { container.className = ''; if (container.lastChild.className == "error-message") { container.removeChild(container.lastChild); } } form.addEventListener('submit', function (event) { event.preventDefault() ; var elems = form.elements; resetError(document.body); if (elems.InputY.value) { SMSy="" } else { SMSy=" Введите Y <Br>" } resetError(document.body); if ((elems['InputX'][0].checked==true)||(elems['InputX'][1].checked==true)|| (elems['InputX'][2].checked==true)||(elems['InputX'][3].checked==true)|| (elems['InputX'][4].checked==true)||(elems['InputX'][5].checked==true)|| (elems['InputX'][6].checked==true)||(elems['InputX'][7].checked==true) ||(elems['InputX'][7].checked==true)) { SMSx="" } else { SMSx="<p style="font-size: 120%; font-family: monospace; color: #cd66cc">Введите X </p> "; } if ((elems['InputR'][0].checked==true)||(elems['InputR'][1].checked==true)|| (elems['InputR'][2].checked==true)||(elems['InputR'][3].checked==true)|| (elems['InputR'][4].checked==true)) { SMSr="" } else { SMSr="Введите R <Br>"; } showError(document.body, SMSx+SMSy+SMSr); } </script> </body> </html> |
Потому, что ошибки:
строка 142 должно быть - SMSx="<p style=\"font-size: 120%; font-family: monospace; color: #cd66cc\">Введите X </p> ";, либо в одинарных кавычках двойные. строка 157 должно быть }), и точка с запятой если далее есть код. А то что ранее я писал, это не способ, а для уяснения почему не работает - выведите в консоль event в обеих случаях (для onclick и onsubmit) и просмотрите его свойства, ответ на вопрос будет дан практически в самом начале его. |
Цитата:
|
Часовой пояс GMT +3, время: 09:35. |