@mortnes

Как установить option в selected?

Добрый день. Нужно чтобы выбранный option оставался выбранным. Вот код, но там идёт reload страницы и значение селекта сбрасывается

<select style="width:200px;float:left;" name="store" required class="form-control" onchange="javascript: window.location.href=this.options[this.selectedIndex].value">
    	<?
    		while($resStore = mysqli_fetch_array($resultStore))
    		{
				echo "<option value='view.php?store=".$resStore["storeID"]."'>".$resStore["name"]."</option>";
			}

    	?>
	</select>
  • Вопрос задан
  • 1091 просмотр
Пригласить эксперта
Ответы на вопрос 1
@fixeri
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<!-- <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script> -->
</head>
<body>
	<select id="select">
		<option value="view.php?store=1">some1</option>
		<option value="view.php?store=2">some2</option>
		<option value="view.php?store=3">some3</option>
		<option value="view.php?store=4">some4</option>
	</select>
	<script type="text/javascript">
		"use strict";

		let select = document.getElementById("select");
		
		if (localStorage.getItem("indexSelected")) {
			select.options[localStorage.getItem("indexSelected")].selected = true;
		}

		select.addEventListener("change", function() {
			localStorage.setItem("indexSelected", this.selectedIndex);
			window.location.href = this.options[this.selectedIndex].value;
		});
	</script>
</body>
</html>


Второй вариант.

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<!-- <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script> -->
</head>
<body>
	<select id="select">
		<option value="view.php?store=1">some1</option>
		<option value="view.php?store=2">some2</option>
		<option value="view.php?store=3">some3</option>
		<option value="view.php?store=4">some4</option>
	</select>
	<script type="text/javascript">
		"use strict";

		let select = document.getElementById("select");

		let selectedOption = window.location.href.match(/store=\d+/);
		let fineded = [...select.querySelectorAll("option")].find((it) => it.value.includes(selectedOption));
		if (fineded) fineded.selected = true;

		select.addEventListener("change", function() {
			window.location.href = this.options[this.selectedIndex].value;
		});
	</script>
</body>
</html>
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы