I have a question concerning the Syntax of outerHTML. It is also possible that I am thinking in the wrong direction.
My html file is as follows:
<!DOCTYPE html>
<html lang="en">
<body>
<label for="language">Choose a language:</label>
<select name="language" id="language" value="val1">
<option value="val1">English</option>
<option value="val2">German</option>
</select>
<p>You selected: <span id="language"></span></p> <!-- shall display either "English" or "German" -->
<p>You selected the following option: <span id="language"></span></p> <!-- shall display either "val1" or "val2" -->
<script src="./script.js"></script>
</body>
</html>
I am referring to a script where for the moment the only content is
var selectedlang = document.getElementById("language").outerHTML;
Within the html file it shall show the value and variable for it. I don't know how to proceed.
You can't have more than one element in a document with the same id value; your current markup uses id="language" on three different elements. You'll need to change two of them at least.
I think you're asking how to:
Show the currently-selected option's text and value in the two spans, and
How to update what you show if the user changes the selection.
If you just wanted the selected value, you could use the value property of the select element. But for both text and value, you'll want the selectedIndex property and the options collection:
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
In that example, I've had it accept the select and spans as parameters to the function.
You'd call that function on page load, and then again whenever the select's input event fired.
Here's an example:
const select = document.getElementById("language-select");
const textSpan = document.getElementById("text-span");
const valueSpan = document.getElementById("value-span");
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
// Show on page load
showTextAndValue(select, textSpan, valueSpan);
// Hook the `input` event
select.addEventListener("input", () => {
// Update the contents of the elements
showTextAndValue(select, textSpan, valueSpan);
});
<label for="language">Choose a language:</label>
<select name="language" id="language-select" value="val1">
<option value="val1">English</option>
<option value="val2">German</option>
</select>
<p>You selected: <span id="text-span"></span></p> <!-- shall display either "English" or "German" -->
<p>You selected the following option: <span id="value-span"></span></p> <!-- shall display either "val1" or "val2" -->
<script src="./script.js"></script>
(Note that I changed all three ids.)
Related
I'm trying to select a drop-down value using js. In my case, I need to select "DRAW PORTRAIT" drop-down option after the plugin loads.
I tried two methods but I'm not getting anywhere. This is a part of the frontend found in Bookly WordPress plugin. I added an id id="category" to the dropdown so that I can select a value.
HTML:
<div class="bookly-js-chain-item bookly-table bookly-box" style="display: table;">
<div class="bookly-form-group">
<label>Service Type</label>
<div>
<select id="categorydraw" class="bookly-select-mobile bookly-js-select-category">
<option value="">Select category</option>
<option value="6">DRAW PORTRAIT</option>
<option value="7">DRAW DUMMY FIGURE</option>
<option value="8">DESIGN WAX SCULPTURE</option></select>
</div>
</div>
</div>
Method 01
document.getElementById("categorydraw").value = "DRAW PORTRAIT";
Method 02
var objSelect = document.getElementById("categorydraw");
setSelectedValue(objSelect, "DRAW PORTRAIT");
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
Please see the full code where the js doesn't work: https://jsfiddle.net/3z5hcv62/
I would really appreciate if someone can correct my cranky code. Thanks in advance!
One line of jQuery will allow you to select the item necessary:
$('#categorydraw option[value="7"').prop("selected", true);
https://jsfiddle.net/fLc1p5mq/
Edit: In order to activate on a WordPress page load, use:
jQuery( document ).ready(function() {
jQuery('#categorydraw option[value="7"').prop("selected", true);
});
First, i want to make sure. Do you want to select the value of the dropdown or set the value to the dropdown?. Maybe this will help your problem.
HTML
<!-- I set the "categories" id to the dropdown -->
<select class="bookly-select-mobile bookly-js-select-category" id="categories">
<option value="">Select category</option>
<option value="1">Cosmetic Dentistry</option>
<option value="2">Invisalign</option>
<option value="3">Orthodontics</option>
<option value="4">Dentures</option>
</select>
<p>
Selected value: <strong id="selected"></strong>
</p>
JavaScript
var dropdown = document.getElementById('categories');
var datas = [];
var select = 3;
/* Get value with text from dropdown */
for(var i=0;i<dropdown.options.length;i++) {
datas.push({
id: dropdown.options[i].value,
text: dropdown.options[i].text,
});
}
/* For set the value */
dropdown.value = select; // after page loaded,, default value will selected is "Orthodontics"
/* For select current value with the text */
var dataSelected = datas[select];
document.getElementById('selected').innerHTML = "ID: "+dataSelected.id+", TEXT: "+dataSelected.text;
The result will show like this https://jsfiddle.net/65jnzLko/1/
You can improve that code. Like selecting datas by id of the dropdown value.
Or if you just want to set the value for your dropdown, you can do this
// using pure js
document.getElementById('yourdropdown').value = 3 // or other values
// using jquery
$("#yourdropdown").val(5) // 5 can replace with other values
How do I modify a value of <option>?
I've tried:
var example = document.getElementById("test"); // This is the <option>
example.value = "Test";
The code above doesn't modify anything.
However, if the code above modifies a value of <select>'s displayed value, the value goes blank;
Use example.textContent to change the value that's displayed. The value that is displayed when an option element is selected is its text content.
However, as indicated in Oriol's answer, changing the value property is meaningful, even if it is not immediately visible.
document.getElementById("change").onclick = function () {
var option = document.getElementById("test");
option.textContent = "bon soir";
option.value = "les étoiles sont belles, hein?";
}
document.getElementById("selector").onchange = function() {
// in this line "this" refers to the <select> element
document.getElementById("selection").textContent = this.value;
}
<select id="selector">
<option></option>
<option id="test" value="good to see you">hello</option>
<option value="see you again">goodbye</option>
</select>
<input type="button" id="change" value="Change value" />
<div id="selection"></div>
The value of an option and its text are different things.
Its value will become, when selected, the value of the select, and will be sent to the server when submitting the form. Analogously, when you set select's value, the selected option will be the one that has that value.
What you want to change is its text, e.g. with one of these:
option.textContent = "Test";
option.innerHTML = "Test";
In realy, you need to see how option element sintax.
<option value="my_value">The Label</option>
So, you need to change the textContent instead value. See the sample below.
document.getElementById('change').onclick = function () {
document.getElementById('my_option').textContent = 'My New Label';
document.getElementById('my_option').value = 'my_new_value';
}
<select>
<option id="my_option" value="my_value">My Label</option>
</select>
<button id="change" type="button">change</button>
The first changes the label (a nicename for the user) and the second changes the value sended to server.
I'm having an issue writing some code for a website. It's written in HTML/Javascript. I've managed to write a large chunk of code that seems to work alright, but this issue is now I can't seem to have multiple line strings within Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Multiline test</title>
</head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<p id="selection"></p>
<script type="text/javascript">
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now, get a reference to the <p> where we'll show the result:
var selectionP = document.getElementById('selection');
// This Array will hold the labels. label[0] will be 'Text1', labels[1] 'Text2', etc.
var labels = [
"Multiline test \n Multiline test",
"Text2",
"Text3"
];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
selectionP.innerHTML = text;
};
</script>
</body>
This is the updated code. Now all I need is a multiline work around.
This
document.form001.choice
"Text" + choice + "Text"}
Doesn't make any sense, does it? You need to do something like
var choice = document.form001.choice
"Text" + choice + "Text"}
By the way to follow the flow of your JavaScript program you should use Google Chrome's JavaScript Console. It really help understanding what's going on.
i noticed you wrote:
Now what I believe to be happening is that when it's not calling the
Javascript function as it is supposed to.
Inside your function either:
write:
console.log('this function is being executed');
// this will make a line show up in the chrome document inspector / firebug console (just google those)
or
alert('This function is being executed!')
That should help with troubleshooting a lot.
Note: I've put up a working example of this code here: http://jsfiddle.net/F87tJ/
Let's take the following HTML:
<html>
<head></head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<script type="text/javascript">
// JavaScript goes here
</script>
</body>
</html>
Now, I'm going to assume you want to respond to the user changing the selection of the dropdown box. This is pretty easy in JavaScript. Just get a reference to the <select> element and attach an event handler to it. An event handler is just a function that will be called when the given event occurs. In this case:
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
// Do something
};
With me so far? Good.
Now, you wanted to show 'Text1', 'Text2' or 'Text3', based on the selection, right? So, we have to know which <option> is selected. That, too, is easy:
var optionIndex = choice.selectedIndex;
This will just give you a zero-based index of the selected <option>. So, if the first option is selected, optionIndex will have value 0.
To show some text based on the selection, we need some strings. Since we're dealing with a collection here, let's put it in an array:
var labels = [
"Text1",
"Text2",
"Text3"
];
Arrays in JavaScript are also zero-based, so label[0] will be 'Text1', labels[1] 'Text2', etc.
If we bring it all together, we get something like this:
var choice = document.getElementsByName('choice')[0];
var labels = [
"Text1",
"Text2",
"Text3"
];
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
alert(text);
};
I hope this helps. :-)
I rewrote problem areas in your code, and added comments to show what was changed.
<!DOCTYPE html> <!-- HTML pages should have a DOCTYPE header, as well as html, head, and body tags. -->
<html>
<head>
<title></title>
</head>
<body>
Text
Text
Text
Text
<br/>
<br/>
Select variable value below:
<br/>
-
<div>
<form name="form001">
<select name="choice">
<!-- <size=3> Don't think there's a such thing as a size tag -->
<option value=1 selected="selected">1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<script type="text/javascript">
function js001(){ //This was missing paranthesis
var v1 = "Text1"
var v2 = "Text2"
var v3 = "Text3"
var choice = document.form001.choice; //choice wasn't defined
alert("Text" + choice + "Text");
}
</script>
<script type="text/javascript">
//js001();
</script> <!-- The S needed to be lowercase here -->
<div class="pagetext">
<br/>
<br/>
Text
<br/>
<br/>
Text
<div>
</body>
</html>
Here's another version which I think will do what you need.
When the user selects an item from the dropdown, it displays a text string below the dropdown that corresponds to the item that the user selected.
<html>
<body>
<form name="form001">
<!-- when the user changes the selected item in this dropdown, -->
<!-- the JavaScript function "js001()" will get called -->
<select name="choice" onchange="js001()">
<option value=0 selected="selected">1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
</form>
<!-- This is the div in which the selected item's related text will be shown -->
<div id="selectedStuff"/>
<script type="text/javascript">
function js001()
{
// Rather than use separate variables for each value,
// it is simpler if we store them in an array
var values = ["Text1", "Text2", "Text3"];
// The value of the selected item in the dropdown maps to the index in the values
// array for the text we want to show
var valueIndex = document.form001.choice.value;
var text = "Text" + values[valueIndex] + "Text"
document.getElementById("selectedStuff").innerHTML = text;
}
// When the page loads it makes sense to call the js001() function,
// so that the text for initially-selected dropdown value gets shown
js001();
</script>
</body>
</html>
a friend asked me to help him with a form, a client of his wants to make a form a bit more dynamic...my javascript is minimal at best since i just started learning.
He asked me something along the lines of " how can i make a form show another pull down ONLY WHEN a certain option is selected "
in the example he gave me, by default when page loads,he has a pull down menu which has 2 options, MANHATTAN and option two is BROOKLYN.
If Manhattan is chose, that reveals another pull down with zips for manhattan, if Brooklyn is chosen the same for BK.
in sample html, something along the lines like this:
<div>
<form>
<select name="boro" id="boro">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
i want to target/capture the option chosen by the user above on the pull down menu, to then activate this function(below).
according to his request what i guess id do is,(as a newbie), then as far as the .js goes (pseudo code):
<script type="text/javascript">
function valBoro (){
if( brook is chosen){ document.getElementById('empty2fill').innerHTML=" new dropdown code here")
}
}
</script>
aside from not knowing, my main problem is i dont know how to target the option chosen in the menu to thereafter, apply the function (which will be written later)
any ideas, tips etc are greately appreciated.
thanks in advance
Another option is to create the two dropdown lists and set the style display to "none". Then you can catch the onChange event and set display to "" based on the value of the select element.
function showZip() {
var boro = document.getElementById("boro");
if (boro.value == "manhattan") {
var zipManhattan = document.getElementById("zipManhattan");
zipManhattan.style.display = "";
}
}
And in the html
<div>
<select name="boro" id="boro" onchange="javascript:showZip();">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<br/>
<select name="zipManhattan" id="zipManhattan" style="display:none;">
<option value="zip1" id="zip1">1111</option>
<option value="zip2" id="zip2">2222</option>
</select>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Here is a link to a jsfiddle showing example code.
http://jsfiddle.net/WKqth/
Example markup:
<div>
<form>
<select name="boro" id="boro">
<option value="" id="none">Select a boro.</option>
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Example js
// include this js below the form in the body, or wrap it in a function and assign that to window.onload, or use a library that provides onDomReady (in jQuery, $(document).ready(function () ... });
var selectElement = document.getElementById('boro');
var showBoroSelect = function () {
// find the selected element
var selectedOption = selectElement.options[selectElement.selectedIndex].id,
// find the element that will contain the new drop down
containerElement = document.getElementById('empty2fill'),
// define the html for the manhattan drop down
manhSelectInnerHTML = '<select name="secondary"><option value="derp">manh derp?</option><option value="herp!">manh herp!</option></select>',
// define the html for the brooklyn drown down
brookSelectInnerHTML = '<select name="secondary"><option value="derp">brook derp?</option><option value="herp!">brook herp!</option></select>',
newInnerHTML;
// determine which html to use based on the selection
if (selectedOption === 'manh') {
newInnerHTML = manhSelectInnerHTML;
} else if (selectedOption === 'brook') {
newInnerHTML = brookSelectInnerHTML;
} else {
// no boro was selected, hide the menu
newInnerHTML = '';
}
// set the container to the new innerHTML
containerElement.innerHTML = newInnerHTML;
};
// when the boro select changes, show the new menu
selectElement.onchange = function () {
showBoroSelect();
};
// if you select a boro and reload the page, the boro may already be selected (for example, firefox might do this)
// this will set the boro menu initially before the user changes it
showBoroSelect();
You want to handle the change event of your "boro" select element.
I've put a plain-JS example solution on jsfiddle at http://jsfiddle.net/FHArd/1/
This creates three select lists - one is your "boro" and the other two are the zip code lists, but they are hidden via CSS until a selection is made.
The change event handler simply adds and/or removes classes from the zip code select elements; the CSS hides or shows the lists based on the class "active" that is attached to the zip code select list.
Note - being there in jsfiddle the way you start things up is a little different than normal. You'd really run your setup function at the onload or ondomready event.
This should do it.
<select name="boro" id="boro" onchange="valBoro(this)">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<script type="text/javascript">
function valBoro(dropDown) {
if (dropDown.options.[dropDown.selectedIndex].value.equals("manhattan")) document.getElementById('empty2fill').innerHTML = "newHTMLCode";
//change "manhattan" to whatever option you want to use
}
</script>
<td>
<select name="ad_category" id = "ad_category" onchange="select_sub_cat(this.value)" >
<option value="#"></option>
<option value="jobs" id="jobs">Jobs</option>
<option value="sales" id="for_sale">For sale</option>
<option value="services" id="services">Services</option>
<option value="real_estate" id="real_e">Real estate/housing</option>
</select>
<span id="cat_help">Help</span>
</td>
IN the above code , in <a href=""> I want to pass the id or any information of the option selected , so that clicking on help will show only the help for the particular option . But my question is is it possible to get the id of the option selected ?
You should be using a button or some other element that doesn't suggest navigation. An inline handler might be:
<... onclick="alert(document.getElementById('ad_category').value);" ...>
More generally, once you have a reference to the select element:
var select = document.getElementById('ad_category');
you can access various properties defined by the HTMLSelectElement interface:
select.selectedIndex // index of selected option
select.options // collection of all options
select.options[select.selectedIndex] // the selected option (if there is one)
and so on.
Edit
You might also want to implement a more generic help system based on class values. Give your form controls a class depending on the help that should be shown. Then the help button can just get the previous form control, grab its class and show it.
e.g.
<style type="text/css">
.helpLink {
color: #CC00FF;
cursor: pointer;
}
</style>
<script type="text/javascript">
var showHelp = (function() {
var help = {
firstName: 'Enter your first name',
lastName: 'Enter your last name'
}
return function (el) {
var helpType;
var node;
do {
el = el.previousSibling;
} while (el && el.nodeType != 1)
if (el) {
helpType = el.className.match(/(^|\s)help-\w+/);
if (helpType) {
helpType = helpType[0].replace('help-','');
// Show help
alert(help[helpType]);
}
}
}
}());
</script>
<form name="form0" action="">
first name: <input type="text" class="help-firstName" name="firstName">
<span class="helpLink" onclick="showHelp(this)">?</span>
<br>
last name: <input type="text" class="help-lastName" name="lastName">
<span class="helpLink" onclick="showHelp(this)">?</span>
<br>
</form>
The above is just a trivial demo.
Yes, you can get the selected option's id:
//Place in event handler
var element = document.getElementById("ad_category");
element.options[element.selectedIndex].id
Related SO post.
If you are using jQuery, you can use the change() function on the selector, to let you know when the selector changes, and capture the ID of the selected item.
Once you have that, you can use jQuery's attr on the anchor to change the href.
Yes it is and you even have several options how to get the job done.
Since the select has an ID, you can get the value like this:
var select = document.getElementByID('ad_category'),
value = select.value;
alert(value);
But also, since the select is a sibling to the parent of the a element, you can also find it like this:
// This example is assuming quite a lot, so it's not really the best option and is
// provided merely for entertainment or trivia.
// Namely, this code requires that it is run in context of the a-element
// (means: 'this' refers to the 'a' -element)
// and also that the markup is exactly as in the example because of traversal.
var select = this.parentNode.previousElementSibling,
value = select.value;
alert(value);