Запретить ввод букв в инпут формы поиска
Здравствуйте
Не получается сделать в проверке формы поиска запрет ввода любых букв (в инпут разрешается вводить только цифры) Пытался сделать так: if ($('#searchError').val().replace(/\D/,'') { $('.er').animate({width:'show'}, 500); // показать div с ошибкой return false; } вот вся форма с проверкой, в строках 32-36 запрет ввода букв (не работает): <script type="text/javascript"> jQuery(function($) { $("#keyword").focus(function() { // удаление текста в input при фокусе if ( $(this).val() == $(this).attr("data-placeholder") ) { $(this).val(""); $(this).css("color","#040404"); } }).blur(function() { if ( !$(this).val() ) { $(this).val( $(this).attr("data-placeholder") ); $(this).css("color","#858585"); } }).focus().blur(); $('#searchFormButton').click(function(){ // проверка заполненности поля input submitSearchForm(); }); $('#keyword').keydown(function(event) { if(event.keyCode==13) { // Enter event.preventDefault(); submitSearchForm(); } }); function submitSearchForm() { if($('#searchError').length){ $('#searchError').remove(); } if( !$.trim( $('#keyword').val() ) || $('#keyword').val() == $('#keyword').attr("data-placeholder") ) { $('.er').animate({width:'show'}, 500); // показать div с ошибкой return false; } // проверка инпут - запрет ввода любых букв (только цифры) как правильно сделать? if ($('#searchError').val().replace(/\D/,'') { $('.er').animate({width:'show'}, 500); // показать div с ошибкой return false; } // ???????????????????????? $('#searchForm').submit(); } $("#keyword").click(function(){ // спрятать div с ошибкой при клике в поле input $(".er").animate({width:'hide'}, 300); }); }); </script> <form action="<?php $sess->purl( $mm_action_url."index.php?page=shop.browse" )?>" method="post" id="searchForm" class="search"> <div style="float:left;"> <input name="keyword" type="search" class="input" id="keyword" data-placeholder="<?php echo $VM_LANG->_('PHPSHOP_SEARCH_TITLE_SKU') ?>" value="<?php echo $VM_LANG->_('PHPSHOP_SEARCH_TITLE_SKU') ?>"/> <input class="submit" type="button" name="" value="" id="searchFormButton" /> </div> </form> |
sashgera,
а где запрет-то ??? и что это значит if ($('#searchError').val().replace(/\D/,'') |
<html> <head> <title>example</title> </head> <body> <div> <input> </div> <script> var input = document.querySelector('input'); input.onkeypress = function (e) { return !(/\D/.test(String.fromCharCode(e.charCode))); } </script> </body> </html> |
Цитата:
Цитата:
|
sashgera,
<!DOCTYPE HTML> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> .er{ display: none; color: #FF0000; } </style> <script src='http://code.jquery.com/jquery-latest.js'></script> <script> jQuery(function($) { $("#keyword").focus(function() { // удаление текста в input при фокусе if ( $(this).val() == $(this).attr("data-placeholder") ) { $(this).val(""); $(this).css("color","#040404"); } }).blur(function() { if ( !$(this).val() ) { $(this).val( $(this).attr("data-placeholder") ); $(this).css("color","#858585"); } }).focus().blur(); $('#searchFormButton').click(function(){$('form').submit()}) $('form').submit(submitSearchForm) function submitSearchForm() { //if($('#searchError').length){ $('#searchError').remove();} if( !$.trim( $('#keyword').val() ) || $('#keyword').val() == $('#keyword').attr("data-placeholder") ) { $('.er').animate({width:'show'}, 500); // показать div с ошибкой return false; } var str = $('#keyword').val(); // проверка инпут - запрет ввода любых букв (только цифры) как правильно сделать? if (/\D/.test(str)) { $('.er').animate({width:'show'}, 500); // показать div с ошибкой return false; } // ???????????????????????? return true } $("#keyword").click(function(){ // спрятать div с ошибкой при клике в поле input $(".er").animate({width:'hide'}, 300); }); }); </script> </head> <body> <p class="er">ошибка</p> <form action="\" method="post" id="searchForm" class="search"> <div style="float:left;"> <input name="keyword" type="search" class="input" id="keyword" data-placeholder="тест" value="тест"/> <input class="submit" type="button" name="" value="" id="searchFormButton" /> </div> </form> </body> </html> |
sashgera,
$(this).attr("data-placeholder") лучше $(this).data("placeholder") |
рони, спасибо, скажите, в коде
if (/\D/.test(str)) {что такое .test ? .test нужно заменить на что-то свое? Я ничего не менял (оставил .test ) и все корректно работает еше раз спасибо! |
Цитата:
|
|
sashgera,
если вам нужно хранить или получать данные то лучше data() вернёт то что положили и расчитана на работу с подобными атрибутами -- attr() вернёт только строку но в вашем случае одинаково <!DOCTYPE HTML> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <script src='http://code.jquery.com/jquery-latest.js'></script> </head> <body> <div data-num="12345" ></div> <script> alert([$( "div" ).data( "num" ) === 12345,$( "div" ).attr( "data-num" ) === 12345,$( "div" ).attr( "data-num" ) === "12345"]); </script> </body> </html> |
Часовой пояс GMT +3, время: 01:19. |