Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Пустое значение переменной (https://javascript.ru/forum/misc/58264-pustoe-znachenie-peremennojj.html)

Beegun 12.09.2015 18:55

Пустое значение переменной
 
В общем. Есть форма
<html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<title>js test</title>
        
		<script src="js/testscript.js"></script>
	</head>
	<body>
	<div id="header">
				<center>Тестовая страница</center>
			</div>
		<div class="wrapper">
			<div id="content">
					<input type="text" name="width" size="3" class="num_only" id="width" placeholder="Ширина" onkeyup="return svalue(this)"><br>
<input type="button" value="показать" onclick="alert(check_width)"
			</div>
		</div>
		<script>var check_width = document.getElementById("width").value;</script>	
	</body>
</html>


Переменная должна получать значение формы, но переменная пустая. Где я ошибся?

рони 12.09.2015 19:14

Beegun,
переменная check_width получает своё значение у вас только в момент загрузки страницы, а не по клику
<html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<title>js test</title>

		<script src="js/testscript.js"></script>
	</head>
	<body>
	<div id="header">
				<center>Тестовая страница</center>
			</div>
		<div class="wrapper">
			<div id="content">
					<input type="text" name="width" size="3" class="num_only" id="width" placeholder="Ширина" onkeyup="return svalue(this)"><br>
<input type="button" value="показать" onclick="fn()"
			</div>
		</div>
        </div>
		<script>
        function fn()
        {
           var check_width = document.getElementById("width").value;
           alert(check_width)
        }
        </script>
	</body>
</html>

Beegun 12.09.2015 19:25

Смеюсь. Дело в том, что когда я объявлял переменные в функции, появлялись ошибки, и так как знаком с javascript 5 день, решил что переменные объявляются не во время и поставил их черт знает куда. Сейчас объявил где надо. Вроде работает xD


Часовой пояс GMT +3, время: 06:22.