How to implement local storage on html? - javascript

(Updated)Here is the View Source.
For Example: You have a list of Names..I have to use a foreach loop because are over 100 names. And once the user selects the name, I have there phone number appears once you click on the button. I need the selected name to stay selected.
<!DOCTYPE html> <!--Required in every html-->
<html>
<head>
<!--Force browser to use latest version-->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- link allows use of .css and script allows use of javaScript -->
<!--<link rel="stylesheet" href="index.css"/>
<script src="init.js"></script>-->
<script>
function doFirst(){
}
</script>
</head>
<body>
<!--<button id='button'>Click me!</button>-->
<!-- -->
<h1> Friday 11-04-2016<br></h1>
<form action='index.php' method='post'>
Afternoon Shift Supervisor:
<select name="name"> <!-- COMBO Box PLUS onchange="submit();return false; makes data appear on selection, refreshs page"-->
<!-- AMOUNT(PROID), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Declicious Apples!">Declicious Apples!</option>
<!-- AMOUNT(PROID), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Comfy">Comfy</option>
<!-- AMOUNT(PROID), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="GREEN">GREEN</option>
</select>
<script>
var select = document.querySelector("name")[0];
var SelectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected){
select.value = lastSelected;
}/*
select.onchange = function (){
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select',lastSelected);
}
function updateSelection(which) {
if (typeof localStorage != "undefined")
localStorage.setItem("select", which.value);
}
window.onload = function () {
if (typeof localStorage != "undefined")
document.querySelector("#sel").value = localStorage["select"];
};*/
</script>
phone # : Comfy
<br> On Call Supervisor:
<select name="name2"> <!-- COMBO Box -->
<!-- AMOUNT(PROID IS VALUE..ASSOCIATIVE ARRAY), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Declicious Apples!">Apples</option> <!-- ASSOCIATIVE ARRAY PRODDESC WILL BE OUTPUT-->
<!-- AMOUNT(PROID IS VALUE..ASSOCIATIVE ARRAY), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Comfy">Jeans</option> <!-- ASSOCIATIVE ARRAY PRODDESC WILL BE OUTPUT-->
<!-- AMOUNT(PROID IS VALUE..ASSOCIATIVE ARRAY), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="GREEN">VEGGIES</option> <!-- ASSOCIATIVE ARRAY PRODDESC WILL BE OUTPUT-->
</select>
<!-- TESTING TO VERIFY I GET VALUE OF WHAT WAS SELECTED WORKS! -->
Phone #: Declicious Apples! <br><input type='submit' id='click me' value='Submit'><br/>
I have also tried(neither are saving the selected value when the page refreshes):
<script>
var select = document.querySelector("name");
var SelectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected){
select.value = lastSelected;
}
select.onchange = function (){
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select',lastSelected);
}
</script>
<form action='index.php' method='post'>
Afternoon Shift Supervisor:
<select name="name">
<?php foreach($data as $i=>$rows): ?>
<option value="<?=$rows['PRODDESC']?>"><?=$rows['PRODDESC']?></option>
<?php endforeach; ?>
</select>
<?php $name = $_POST["name"];?>
phone # : <?php echo $name; ?>
<br><input type='submit' name='click me' value='Submit'><br/>
</form>

Instead of doing it in the server side, use the client side to make it possible.
function updateSelection(which) {
if (typeof localStorage != "undefined")
localStorage.setItem("select", which.value);
}
window.onload = function () {
if (typeof localStorage != "undefined")
document.querySelector("#sel").value = localStorage["select"];
};
<select id="sel" onchange="updateSelection(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>
If the Stack Snippets are sandboxed, see the live preview at JSBin.

Related

Insert text format from an editable <div> or textarea into the database

I am currently working on a personal project for my own website wherein I am trying to add in a feature of storing formatted text into the database. So far what I have done is able to change the font from italic to bold as a sample but I am completely clueless how I can pass this through to the database.
<style>
#fake_textarea {
width: 100%;
height: 200px;
border: 1px solid red;
}
#jBold {
font-weigth: bold;
}
#jItalic{
font-style:italic;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="jBold"><b>B</b></button><button id="jItalic"><i>I</i></button>
<div id='fake_textarea' contenteditable>
Select some text and click the button to make it bold...
<br>Or write your own text
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#jBold').click(function() {
document.execCommand('bold');
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#jItalic').click(function() {
document.execCommand('italic');
});
});
</script>
</body>
</html>
Sample work:
codepen
To access the content in that editable div, you can use:
let content = $('#fake_textarea').html();
Regarding sending the data through to PHP, the easiest solution would probably be to use Ajax.
Alternative
If you don't want to use Ajax but rather an ordinary form post, you could let the button trigger a function that get's the content and populates it into a hidden field in a form, which you then submit.
Something like this: (untested pseudo code)
HTML:
<form method="post" action="foo.php" id="some-form">
<input type="hidden" name="content" id="some-hidden-input" />
<div id="fake_textarea" ...></div>
<button id="submit-button"></button>
</form>
JS:
$('#submit-button').on('click', function (e) {
// Stop the default submission
e.preventDefault();
// Get the content from the div
let content = $('#fake_textarea').html();
// Store the content in a hidden input
$('#some-hidden-input').val(content);
// Submit the real form
$('#some-form').submit();
});
Note
I'm using jQuery in these examples since you show that you're using it. All this can of course be done in vanilla JS as well.
Alright so I have tweaked Magnus' code a bit and I do thank him a lot for helping me figure this out.
textarea.php
This is where you will write your own content, format the text and throw it to your php file that in turn would insert it to the database. I added comments for those that wants to learn from this as well.
<style>
#fake_textarea {
width: 100%;
height: 200px;
border: 1px solid red;
}
<!-- Add css to modify the text -->
#jBold {
font-weigth: bold;
}
#jItalic{
font-style:italic;
}
#jUnderline{
text-decoration: underline;
}
#jLT{
text-decoration: line-through;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<body>
<!-- Put buttons here to modify the format -->
<div>
<select id="select_font" onchange="changeFont(this);">
<option value="Arial">Arial</option>
<option value="Sans Serif" selected>Sans Serif</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Courier New">Courier New</option>
<option value="Verdana">Verdana</option>
<option value="Trebuchet MS">Trebuchet MS</option>
<option value="Arial Black">Arial Black</option>
<option value="Impact">Impact</option>
<option value="Bookman">Bookman</option>
<option value="Garamond">Garamond</option>
<option value="Palatino">Palatino</option>
<option value="Georgia">Georgia</option>
</select>
<select id="select-size" onchange="changeSize(this);">
<option value="4">4</option>
<option value="8">8</option>
<option value="12">12</option>
<option value="16">16</option>
<option value="20">20</option>
<option value="24">24</option>
<option value="28">28</option>
<option value="32">32</option>
<option value="36">36</option>
<option value="40">40</option>
<option value="44">44</option>
<option value="48">48</option>
<option value="52">52</option>
<option value="56">56</option>
<option value="58">58</option>
</select>
<button id="jBold"><b>B</b></button><button id="jItalic"><i>I</i></button><button id="jUnderline">U</button><button id="jSuperScript">A<sup>A</sup></button><button id="jSubScript">A<sub>A</sub></button>
<button id="jLT">A</button>
<div>
<!-- Add a form -->
<form method="post" action="postcontent.php" id="contentform">
<!-- Add some hidden input in order for the form to submit some sort of value -->
<input type="hidden" name="content" id="hiddeninput" />
<!-- Add a place to insert the content -->
<div id='fake_textarea' contenteditable>
Select some text and click the button to make it bold...
<br>Or write your own text
</div>
<!-- Add a submit button-->
<button id="submit">Submit</button>
</form>
<!-- Script to make a selected text bold-->
<script type="text/javascript">
$(document).ready(function() {
$('#jBold').click(function() {
document.execCommand('bold');
});
});
</script>
<!-- Script to make a selected text italic-->
<script type="text/javascript">
$(document).ready(function() {
$('#jItalic').click(function() {
document.execCommand('italic');
});
});
</script>
<!-- Script to make add an underline-->
<script type="text/javascript">
$(document).ready(function() {
$('#jUnderline').click(function() {
document.execCommand('underline');
});
});
</script>
<!-- Script to make make selected text a superscript-->
<script type="text/javascript">
$(document).ready(function() {
$('#jSuperScript').click(function() {
document.execCommand('superscript');
});
});
</script>
<!-- Script to make make selected text a subscript-->
<script type="text/javascript">
$(document).ready(function() {
$('#jSubScript').click(function() {
document.execCommand('subscript');
});
});
</script>
<!-- Script to add a line-through-->
<script type="text/javascript">
$(document).ready(function() {
$('#jLT').click(function() {
document.execCommand('strikeThrough');
});
});
</script>
<!-- Changes the font type -->
<script type="text/javascript">
function changeFont(font) {
var sel = window.getSelection(); // Gets selection
if (sel.rangeCount) {
// Creates a new element, and insert the selected text with the chosen font inside
var e = document.createElement('span');
e.style = 'font-family:' + font.value + ';';
e.innerHTML = sel.toString();
// https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt
var range = sel.getRangeAt(0);
range.deleteContents(); // Deletes selected text…
range.insertNode(e); // … and inserts the new element at its place
}
}
</script>
<!-- Changes the font size -->
<script type="text/javascript">
function changeSize(size) {
var sel = window.getSelection(); // Gets selection
if (sel.rangeCount) {
// Creates a new element, and insert the selected text with the chosen font inside
var e = document.createElement('span');
e.style = 'font-size:' + size.value + 'px;';
e.innerHTML = sel.toString();
// https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt
var range = sel.getRangeAt(0);
range.deleteContents(); // Deletes selected text…
range.insertNode(e); // … and inserts the new element at its place
}
}
</script>
<!-- Script to add value to the hidden input then submits it-->
<script type="text/javascript">
$( "#submit" ).click(function() {
var htmlString = $( "#fake_textarea" ).html();
$('#hiddeninput').val(htmlString);
// Submit the real form
$('#contentform').submit();
});
</script>
</body>
postcontent.php
This file will submit the value thrown from the hidden input to the database.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//grabs the name of the hidden input that was posted
$pcd= $_POST['content'];
$uid="";
$bid="";
$cnum="";
$cid="";
//connect to database
$mysqli = new mysqli("localhost","root","","nw");
//error checking the connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
//submits it
$stmt= $mysqli->prepare("INSERT INTO usercontent (userid, bookid, chapterid, chapternum,data) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $uid, $bid,$cid, $cnum,$pcd);
$stmt->execute();
$stmt -> close();
$mysqli -> close();
}
?>
Hopes this will help someone as much as this person helped me.

HTML & Javascript - make text appear when dropdown menu option selected

So I'm new to html/javascript and I'm trying to figure out how to make my dropdown menu work properly. Appearance wise it looks fine, but when I click on any of the options I'm trying to figure out how to change the layout of the page based on the option I picked. So for example if I select option 1 and click the 'select' button, I want regular text to appear saying "You clicked option 1." I tried to implement that but it's not doing anything. If I click 'select' without choosing an option, then an error message should pop up. I would really appreciate some help or a push in the right direction.
options.html:
<html>
<head>
<title>Welcome</title>
</head>
<body onload="init()">
<div><h1>Welcome</h1></div><br />
<div class="dropdown">
<form>
<select name="list" id="list" accesskey="target">
<option value="none">Pick an option</option>
<option value="one">Option 1</option>
<option value="two">Option 2</option>
<option value="three">Option 3</option>
</select>
<input type=button value="Select" onclick="goToNewPage()" />
</form>
</div>
</div>
<script src="options.js"></script>
<link rel="stylesheet" href="dropdown.css">
</body>
</html>
options.js:
function optionClicked(){
let userPicked = document.getElementById("dropdown").value;
if(userPicked == 'one'){
div.innerHTML = "You clicked option 1";
}else if(userPicked == 'two'){
div.innerHTML = "You clicked option 2.";
}else if(userPicked == 'three'){
div.innerHTML = "You clicked option 3.";
}else{
alert("You must pick an option.");
}
}
As pointed in a comment, you need to address the right id and function name like this:
function optionClicked(){
let userPicked = document.getElementById("list").value;
var div = document.getElementById("div");
if(userPicked == 'one'){
div.innerHTML = "You clicked option 1";
}else if(userPicked == 'two'){
div.innerHTML = "You clicked option 2.";
}else if(userPicked == 'three'){
div.innerHTML = "You clicked option 3.";
}else{
alert("You must pick an option.");
}
}
<html>
<head>
<title>Welcome</title>
</head>
<body>
<div><h1>Welcome</h1></div><br />
<div class="dropdown">
<form>
<select name="list" id="list" accesskey="target">
<option value="none">Pick an option</option>
<option value="one">Option 1</option>
<option value="two">Option 2</option>
<option value="three">Option 3</option>
</select>
<input type=button value="Select" onclick="optionClicked()" />
</form>
</div>
</div>
<div id="div"></div>
<script src="options.js"></script>
<link rel="stylesheet" href="dropdown.css">
</body>
</html>
You could use an Object literal to store your messages by select's value.
Don't use inline JS. It's hard to debug.
Use addEventListener()
Use the proper elements ID
const EL_list = document.querySelector('#list');
const EL_select = document.querySelector('#select');
const EL_response = document.querySelector('#response');
const messages = {
none: "You must pick an option.",
one: "You selected option 1",
two: "You selected option 2",
three: "You selected option 3",
};
EL_select.addEventListener('click', evt => {
const val = EL_list.value;
const msg = messages[val];
if (val==='none') alert(msg);
else EL_response.textContent = msg;
});
<div class="dropdown">
<select name="list" id="list">
<option value="none">Pick an option</option>
<option value="one">Option 1</option>
<option value="two">Option 2</option>
<option value="three">Option 3</option>
</select>
<input id="select" type="button" value="Select">
<div id="response"></div>
</div>
I solved the problem by using jquery. Also, your html code has a stray div end tag. You should check that out.
<html>
<head>
<title>Welcome</title>
</head>
<body>
<div><h1>Welcome</h1></div><br />
<div class="dropdown">
<form>
<select name="list" id="list" >
<option value="none">Pick an option</option>
<option value="one">Option 1</option>
<option value="two">Option 2</option>
<option value="three">Option 3</option>
</select>
<input type=button value="Select" onclick="optionClicked()" />
</form>
</div>
<div id="div"></div>
<script src='jquery.min.js'></script> <!-- include jquery-->
<script>
function optionClicked()
{
var userPicked = $(`#list`).children("option").filter(":selected").val().trim();
switch(userPicked)
{
case 'one': div.innerHTML = "You clicked option 1"; break;
case 'two': div.innerHTML = "You clicked option 2."; break;
case 'three': div.innerHTML = "You clicked option 3."; break;
default:
alert("You must pick an option."); break;
}
}
</script>
<link rel="stylesheet" href="dropdown.css">
</body>
</html>

update the selected option in select on a condition in php

I am new to programming, what I am trying is when a user selected option from a select, the next time user visit the page or refresh the page the user will see his last selected option as selected already.
<!DOCTYPE html>
<html>
<body>
<select id="Example">
<?php
$value = "<script>document.write(value)</script>";
$val = "1";
$val2 = "2";
?>
<option value="1" <?php if ($val == $value){ ?>selected <?php } ?> >One</option>
<option value="2" <?php if ($val2 == $value){ ?>selected <?php } ?> >Two</option>
<option value="3">Three</option>
</select>
<script>
var sel = document.getElementById('Example');
var value = sel.options[sel.selectedIndex].value;
</script>
</body>
</html>
I am using the above code but I am not getting the desired output, please help me I am really stuck. If this is possible in JavaScript I will also be appreciated. Thanks in Advance.
Database, Cookies or localStorage
window.onload=function() {
var val = localStorage.getItem("example");
if (val) { document.getElementById('Example').value = val }
document.getElementById('Example').onchange=function() {
localStorage.setItem("example",this.value);
}
}
<form action="" method="post">
<label>Country</label>
<select id="country" name="country" onchange="myFunction(this.value)">
<option value="india">India</option>
<option value="australia">Australia</option>
<option value="canada">Canada</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var val = localStorage.getItem("CountryValue");
document.getElementById('country').value = val;
// This function will store data in localstorage on client browser.
function myFunction(value) {
localStorage.setItem("CountryValue",value);
}
</script>

Update Textbox with Combobox value on ValueChange event

My ultimate goal with this is to make a dropdown that allows user input also. The best I can seem to do is an textbox next a dropdown that makes it look like they are similar, the issue I am running into is that I need the textbox to update whenever my dropdown value is changed. I have some code I've been playing with (below), but it doesn't seem to be getting me anywhere! Any pointers on how I can get this to work, or am I messing up the syntax? (fairly new to both jscript and html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<style type="text/css">
select
{
width:200px;
}
</style>
<head>
<title>Test</title>
<script type="text/JavaScript">
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
</script>
</head>
<body>
<form action="" method="">
<input name="stroke"/>
<select name="theItems" onchange="otherSelect()">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<div id="otherBox" style="visibility: hidden;">
If other: <input name="otherField" type="text" />
</div>
</form>
</body>
You should execute your script in the window.onload event. The elements are not available to your script when it is being executed. Change your script to this
<script type="text/JavaScript">
window.onload = function(){
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
}
</script>
This way the script will be executed after the HTML elements have been rendered by the browser.
Here's a simple pure JavaScript implementation of what you want. http://jsfiddle.net/24Xhn/
We're going to setup the markup so the select box and the other input box have similar name and id attributes. We'll use classes to setup/initialize the onchange events and make sure the inputs start off hidden and disabled. By toggling the "disabled" attribute, true or false we are making it so the input or select don't show up when the form is submitted, submit the form in the JSFiddle with different combinations and you'll see the output in the query string of the URL.
HTML
<select id="items1" name="items1" class="select-other">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<input id="items1-other" name="items1-other" class="input-other" />
JS
// setup
var inps = document.getElementsByClassName("input-other");
for(var i=0; i<inps.length; i++) {
var inp = inps[i];
// hide & disable the "other" input
inp.style.display = "none";
inp.disabled = true;
// set onchange, if input is empty go back to select
inp.onchange = function() {
var val = this.value;
if(val == "") {
this.style.display = "none";
this.disabled = true;
// get its associated select box
var sel = document.getElementById(this.id.replace(/-other$/i, ""));
sel.style.display = "";
sel.disabled = false;
}
};
}
var sels = document.getElementsByClassName("select-other");
for(var i=0; i<sels.length; i++) {
var sel = sels[i];
// set onchange if value is other switch to input
sel.onchange = function() {
var val = this.value;
if(val == "other") {
this.style.display = "none";
this.disabled = true;
// get associated input box
var inp = document.getElementById(this.id + "-other");
inp.style.display = "";
inp.disabled = false;
}
};
}
I just realized what was wrong. I didn't truly look at the html until I copied and pasted it into a test application and I figured out the issue.
You need to set the id tag to the stroke and theItems not the name tag. That's why it's not doing anything. There was, I'm guessing, a copy/paste issue as well because you didn't have a closing html tag, but I assumed you just missed copying that. Also, you don't really need global variables in order to retrieve the input and select you just need them inside the actual function, and you can actually pass the select into the function like so.
Your code corrected:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
<style type="text/css">
select
{
width:200px;
}
</style>
<script type="text/javascript">
function otherSelect(obj)
{
var input = document.getElementById('stroke');
input.value = obj.value;
}
</script>
</head>
<body>
<form action="" method="">
<input id="stroke" name="stroke"/>
<select id="theItems" name="theItems" onchange="otherSelect(this)">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<div id="otherBox" style="visibility: hidden;">
If other: <input name="otherField" type="text" />
</div>
</form>
</body>
</html>
I also wanted to create a combobox with an auto-updating text field next to it for new entries, and came up with this in less than an hour, based on simple html and javascript examples from w3schools.com. It works perfectly on my IE browser.
<!DOCTYPE html>
<html>
<head>
<script>
function updateField(name, value)
{
document.getElementById(name).value = value;
}
</script>
</head>
<body>
<select name='10' onchange='updateField(this.name, this.value)'>
<option value='volvo'>Volvo</option>
<option value='saab'>Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" id="10" value="volvo">
</body>
</html>

How to use onClick() or onSelect() on option tag in a JSP page?

How to use onClick() or onSelect() with option tag? Below is my code in which I tried to implement that, but it is not working as expected.
Note: where listCustomer domain object list getting in JSP page.
<td align="right">
<select name="singleSelect" ">
<c:forEach var="Customer" items="${listCustomer}" >
<option value="" onClick="javascript:onSelect(this);> <c:out value="${Customer}" /></option>
</c:forEach>
</select>
</td>
How do I modify it to detect that an option is selected?
Neither the onSelect() nor onClick() events are supported by the <option> tag. The former refers to selecting text (i.e. by clicking + dragging across a text field) so can only be used with the <text> and <textarea> tags. The onClick() event can be used with <select> tags - however, you probably are looking for functionality where it would be best to use the onChange() event, not onClick().
Furthermore, by the look of your <c:...> tags, you are also trying to use JSP syntax in a plain HTML document. That's just... incorrect.
In response to your comment to this answer - I can barely understand it. However, it sounds like what you want to do is get the value of the <option> tag that the user has just selected whenever they select one. In that case, you want to have something like:
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
Even more simplified: You can pass the value attribute directly!
<html>
<head>
<script type="text/javascript">
function changeFunc(i) {
alert(i);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc(value);">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
The alert will either return 1 or 2.
The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.
it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.
if you do this with the code below you will see that
var selectBox = document.getElementById("selectBox");
gets put in a box and stays there you don't do anything with it afterwards.
and
var selectBox = document.getElementById("selectBox");
is hard to debug and is confusing when you have a select id of selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag
your code works until you add to it or modify it then you can easily loose track and get all mixed up
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
a leaner way that works also is:
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.
<script type="text/javascript">
function Mapit(){
var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;
alert(actualPostcode);
// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map
}
</script>
<select id="getPostcodes" onchange="Mapit();">
<option>London North Inner</option>
<option>N1</option>
<option>London North Outer</option>
<option>N2</option>
<option>N3</option>
<option>N4</option>
// a lot more options follow
// with text in options to divide into areas and nothing will happen
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes
</select>
in this example de select tag is named as: aula_clase_cb
<select class="form-control" id="aula_clase_cb" >
</select>
document.getElementById("aula_clase_cb").onchange = function(e){
id = document.getElementById('aula_clase_cb').value;
alert("id: "+id);
};
<div class="form-group">
<script type="text/javascript">
function activa(){
if(v==0)
document.formulario.vr_negativo.disabled = true;
else if(v==1)
document.formulario.vr_negativo.disabled = true;
else if(v==2)
document.formulario.vr_negativo.disabled = true;
else if(v==3)
document.formulario.vr_negativo.disabled = true;
else if(v==4)
document.formulario.vr_negativo.disabled = true;
else if(v==5)
document.formulario.vr_negativo.disabled = true;
else if(v==6)
document.formulario.vr_negativo.disabled = false;}
</script>
<label>¿Qué tipo de vehículo está buscando?</label>
<form name="formulario" id="formulario">
<select name="lista" id="lista" onclick="activa(this.value)">
<option value="0">Vehiculo para la familia</option>
<option value="1">Vehiculo para el trabajo</option>
<option value="2">Camioneta Familiar</option>
<option value="3">Camioneta de Carga</option>
<option value="4">Vehiculo servicio Publico</option>
<option value="5">Vehiculo servicio Privado</option>
<option value="6">Otro</option>
</select>
<br />
<input type="text" id="form vr_negativo" class="form-control input-xlarge" name="vr_negativo"/>
</form>
</div>
You can change selection in the function
window.onload = function () {
var selectBox = document.getElementById("selectBox");
selectBox.addEventListener('change', changeFunc);
function changeFunc() {
alert(this.value);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Selection</title>
</head>
<body>
<select id="selectBox" onChange="changeFunc();">
<option> select</option>
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
<html>
<head>
<title>Cars</title>
</head>
<body >
<h1>Cars</h1>
<p>Name </p>
<select id="selectBox" onchange="myFunction(value);">
<option value="volvo" >Volvo</option>
<option value="saab" >Saab</option>
<option value="mercedes">Mercedes</option>
</select>
<p id="result"> Price : </p>
<script>
function myFunction($value)
{
if($value=="volvo")
{document.getElementById("result").innerHTML = "30L";}
else if($value=="saab")
{document.getElementById("result").innerHTML = "40L";}
else if($value=="mercedes")
{document.getElementById("result").innerHTML = "50L";}
}
</script>
</body>
</html>```
Other option, for similar example but with anidated selects, think that you have two select, the name of the first is "ea_pub_dest" and the name of the second is "ea_pub_dest_2", ok, now take the event click of the first and display the second.
<script>
function test()
{
value = document.getElementById("ea_pub_dest").value;
if ( valor == "value_1" )
document.getElementById("ea_pub_dest_nivel").style.display = "block";
}
</script>
Change onClick() from with onChange() in the . You can send the option value to a javascript function.
<select id="selector" onChange="doSomething(document.getElementById(this).options[document.getElementById(this).selectedIndex].value);">
<option value="option1"> Option1 </option>
<option value="option2"> Option2 </option>
<option value="optionN"> OptionN </option>
</select>
If you need to change the value of another field, you can use this:
<input type="hidden" id="mainvalue" name="mainvalue" value="0">
<select onChange="document.getElementById('mainvalue').value = this.value;">
<option value="0">option 1</option>
<option value="1">option 2</option>
</select>
example dom onchange usage:
<select name="app_id" onchange="onAppSelection(this);">
<option name="1" value="1">space.ecoins.beta.v3</option>
<option name="2" value="2">fun.rotator.beta.v1</option>
<option name="3" value="3">fun.impactor.beta.v1</option>
<option name="4" value="4">fun.colorotator.beta.v1</option>
<option name="5" value="5">fun.rotator.v1</option>
<option name="6" value="6">fun.impactor.v1</option>
<option name="7" value="7">fun.colorotator.v1</option>
<option name="8" value="8">fun.deluxetor.v1</option>
<option name="9" value="9">fun.winterotator.v1</option>
<option name="10" value="10">fun.eastertor.v1</option>
<option name="11" value="11">info.locatizator.v3</option>
<option name="12" value="12">market.apks.ecoins.v2</option>
<option name="13" value="13">fun.ecoins.v1b</option>
<option name="14" value="14">place.sin.v2b</option>
<option name="15" value="15">cool.poczta.v1b</option>
<option name="16" value="16" id="app_id" selected="">systems.ecoins.launch.v1b</option>
<option name="17" value="17">fun.eastertor.v2</option>
<option name="18" value="18">space.ecoins.v4b</option>
<option name="19" value="19">services.devcode.v1b</option>
<option name="20" value="20">space.bonoloto.v1b</option>
<option name="21" value="21">software.devcode.vpnfree.uk.v1</option>
<option name="22" value="22">software.devcode.smsfree.v1b</option>
<option name="23" value="23">services.devcode.smsfree.v1b</option>
<option name="24" value="24">services.devcode.smsfree.v1</option>
<option name="25" value="25">software.devcode.smsfree.v1</option>
<option name="26" value="26">software.devcode.vpnfree.v1b</option>
<option name="27" value="27">software.devcode.vpnfree.v1</option>
<option name="28" value="28">software.devcode.locatizator.v1</option>
<option name="29" value="29">software.devcode.netinfo.v1b</option>
<option name="-1" value="-1">none</option>
</select>
<script type="text/javascript">
function onAppSelection(selectBox) {
// clear selection
for(var i=0;i<=selectBox.length;i++) {
var selectedNode = selectBox.options[i];
if(selectedNode!=null) {
selectedNode.removeAttribute("id");
selectedNode.removeAttribute("selected");
}
}
// assign id and selected
var selectedNode = selectBox.options[selectBox.selectedIndex];
if(selectedNode!=null) {
selectedNode.setAttribute("id","app_id");
selectedNode.setAttribute("selected","");
}
}
</script>
In my case:
<html>
<head>
<script type="text/javascript">
function changeFunction(val) {
//Show option value
console.log(val.value);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunction(this)">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
focus clears value, so select any value is a change and fires myFunc(this) and blur defocus for reselect
<html>
<head>
<script type="text/javascript">
function myFunc(el) {
//Show option value
console.log(el.value);
}
</script>
</head>
<body>
<select id="selectBox" onchange="myFunc(this);this.blur();" onfocus="this.selectedIndex = -1;">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>

Categories