I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information.
With the help of a few online tutorials, I've managed to get the Javascript to display a hidden div just fine. My problem is I can't seem to localise the event to the Option tag, only the Select tag which is no use really.
At the moment the code looks like (code simplified to aid clarity!):
<select id="transfer_reason" name="transfer_reason onChange="javascript:showDiv('otherdetail');">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
What I would like is if they choose "Other Reason" it then displays the div. Not sure how I achieve this if onChange can't be used with the Option tag!
Any assistance much appreciated :)
Note: Complete beginner when it comes to Javascript, I apologise if this is stupidly simple to achieve!
Setup the onchange event handler for the select box to look at the currently selected index. If the selected index is that of the 'Other Reason' option, then display the message; otherwise, hide the division.
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 2) {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</body>
</html>
Personally, I'd take it a step further and move the JavaScript into an external file and just include it in the header of the page; however, for all intents and purposes, this should help answer your question.
After reading Tom's great response, I realised that if I ever added other options to my form it would break. In my example this is quite likely, because the options can be added/deleted using a php admin panel.
I did a little reading and altered it ever so slightly so that rather than using selectedIndex it uses value instead.
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.value === "Other") {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
Hope this helps someone else in the future!
Tom's answer is elegant, and neatly puts the JS away from the HTML markup. As mentioned, it could be even moved to an external file. However it adds quite much "nonsense" to the code, like multiple anonymous function assignments etc.
If you want quick solution, you can put it all in the onchange() inside the select tag as well. Pick the one you see more fit.
<select id="transfer_reason" name="transfer_reason" onchange="document.getElementById('otherdetail').style.display = (this.selectedIndex === 2) ? 'block' : 'none';">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
Related
I'm pretty new to webpage and HTML, and I'm not sure what the easiest way to solve this program is. I have a basic webpage that I get data from a tag, and then I have a button to push it to a part on the webpage.
HTML
<div id="footer">
<p id="selectedEvent">Event</p>
</div>
<select id="currentEvent">
<option value="" disabled selected>Current Event</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<button type="button" onclick="GetSelectedText()">Push Changes</button>
JS
function GetSelectedText() {
var e = document.getElementById("currentEvent");
var result = e.options[e.selectedIndex].text;
document.getElementById("selectedEvent").innerHTML = result;
}
What I want this to do is update text on another instance of this code running in another tab, so that both webpages display the selected option after it is pushed on one of them. What's the easiest way to do this?
EDIT
I'm gonna briefly explain my use case just to get more useful responses. I'm using this as an overlay and interface for OBS as a browser source, so the solution needs to basically be able to sync across different browsers (ex Chrome and Firefox)
Thanks in advance!
Is this what you want?
var e = document.getElementById("currentEvent");
function GetSelectedText() {
var selected = e.options[e.selectedIndex];
document.getElementById("selectedEvent").innerHTML = selected.text;
if (typeof(Storage) !== "undefined") {
localStorage.setItem("s_option", selected.text);
localStorage.setItem("s_option_value", selected.value);
}
}
function show_result() {
document.getElementById("selectedEvent").innerHTML = localStorage.getItem("s_option");
document.getElementById("currentEvent").value = localStorage.getItem("s_option_value");
}
window.addEventListener("storage", show_result);
e.addEventListener("change", GetSelectedText);
I have some javascript in one of my survey questions that changes the formatting of a certain field. It works great, but I would like to apply the same code to several other questions. Obviously, I can simply copy and paste onto each question, but is there any way to have the code set in a single location so that it is more maintainable? I've looked on a number of forums but haven't been able to find a solution. Thanks in advance for your help.
EDIT:
Here is the JavaScript code that I would like to be repeated for multiple questions:
{
/*Place your JavaScript here to run when the page is fully displayed*/
jQuery("#"+this.questionId+" select option:first-child").text("Select one");
jQuery("#"+ this.questionId + " option").each(function () {
if (jQuery(this).text().includes("\"\"")) {
jQuery(this).hide();
}else{
title = jQuery(this).text()
title = title.match(/".*"/)
if(title != null && title[0].length > 30){
newTitle = title[0].match(/^.{30}.*?\s/)[0]
if(newTitle != title){
newTitle = newTitle + "...\""
}
text = jQuery(this).text()
jQuery(this).text(text.replace(title[0],newTitle))
}
}
});
});
Basically, there is some embedded data preloaded for each contact, and several questions involve a dropdown menu that allows users to select which of their data elements was relevant to a project. This code ensures that blank or missing data does not get included in the dropdown, and also if the option is too many characters long, it gets truncated. Multiple questions include the same dropdown options, but differ in other ways.
Make your code a function and put it in the Qualtrics header. Call the function from each question where it applies.
In the header:
<script>
myFunction(qobj) {
jQuery("#"+qobj.questionId+" select option:first-child")...etc...
}
</script>
Then in your questions:
Qualtrics.SurveyEngine.addOnload(function() {
myFunction(this);
});
Add the same class to each of your question (I chose myQuestion class) then query it.
Loop through each select and find the option:first-child and then find the options and loop through each of them.
$('.myQuestion select').each(function(selectIndex, select){
// loop through each select
// for each select find all the options
$(this).find("option:first-child").text("Select one");
$(this).find('option').each(function(optionIndex, option){
console.log(`select (${selectIndex}) | option (${optionIndex})`);
// your code here
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myQuestion">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
<div class="myQuestion">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
I am working on a form. One of my colleagues have used the are_you_sure.js which confirms to leave before saving a form.
Now the problem is if I have a dropdown say like this
<script type="text/javascript">
function get_cpc(cst_type)
{
if(cst_type==0 || cst_type==1)
{
$("#camp_cpc").show();
$("#camp_cpc").val("'.(!empty( $html['camp_cpc'] )?(double)$html['camp_cpc']:'').'");
}
else
{
$("#camp_cpc").hide();
$("#camp_cpc").val("0");
}
}
</script>
<select name="cost_type" id="cost_type" onchange="get_cpc(this.value);" class="ultra-select">
<option value="0">CPC</option>
<option value="1" selected="selected">CPA</option>
<option value="2">Do Not Track</option>
</select>
When I am switching from non-selected options to selected option, then the change of state takes too much time
This means if I am selecting CPC/Do Not Track from CPA, then the dropdown works fast. But if I am selecting CPA from CPC/Do Not Track, then the state change takes almost 4 seconds..
That's due to the jquery.are-you-sure.js. So, I need to remove the select from the dropdown. How can I achieve this?
I put this code, $("select option").prop("selected", false);
but it doesn't even let me select any other option.
I'm not sure what you mean exacly, but can you share the are_you_sure.js file?¿
Also I have change your code maybe it helps and it´s a better way to do it. because it´s not a good practice use onchange(), so remove onchange from your html and do this, link: http://jsfiddle.net/hg5nz1w6/1/
js:
$(document).ready(function(){
$('#cost_type').on('change', function(){
var cst_type = $(this).val();
if(cst_type==0 || cst_type==1)
{
$("#camp_cpc").val("'.(!empty( $html['camp_cpc'] )?(double)$html['camp_cpc']:'').'");
$("#camp_cpc").show();
}
else
{
$("#camp_cpc").hide();
$("#camp_cpc").val("0");
}
});
});
html:
<select name="cost_type" id="cost_type" class="ultra-select">
<option value="0">CPC</option>
<option value="1" selected="selected">CPA</option>
<option value="2">Do Not Track</option>
</select>
Below you can see some examples to remove the selected:
document.getElementById('myselect').selectedIndex = -1;
you can deselect all the options:
$("select").val([]);
or
$("select option").prop("selected", false);
Hope it´s helps!
I have two select boxes like so:
<select id="one">
<option value="default">Select File</option>
<option value="path/to/file1">File One</option>
<option value="path/to/file2">File Two</option>
<option value="path/to/file3">File Three</option>
</select>
<select id="two">
<option value="default">Select File</option>
<option value="path/to/file4">File Four</option>
<option value="path/to/file5">File Five</option>
<option value="path/to/file6">File Six</option>
</select>
<p class="button_image">
<a onclick="download(document.getElementById("one").value)"></a>
</p>
Here is my download function:
function download(file) {
if (file == 'default') return;
window.location = 'http://www.mysite.com/download/' + file;
}
This works fine for one select box, but I can't seem to figure out how to use the same button image. Oh yah, the p.class=button_image has background image that is a button with hover effects.
The reason I want these select boxes to be separate is because they each represent a group of files, eg, 32-bit versus 64-bit. So they cannot be combined, because it won't flow with the page design.
I've tried some if/else blocks in PHP using the getElementById but I'm getting stuck. This is what I tried and it seems to only partially work:
<?php
if ('document.getElementById(\"one\")' == 'one') {
echo "<a onclick='download(document.getElementById(\"one\").value)'></a>";
}
else if ('document.getElementById(\"two\")' == 'two') {
echo "<a onclick='download(document.getElementById(\"one\").value)'></a>";
}
?>
I should note that I don't necessarily need to use PHP in this case to solve this problem. It was just an option I tried because I'm using PHP for the server-side programming. I could be happy with any number of options, so long as they work.
Thanks.
** EDIT **
This design might be flawed. But the intention is that either a file from box one is downloaded OR a file from box two is downloaded. If one selection is made, then the other should be rest to default and vice versa. This is what I'm working on now.
** EDIT **
I ended up goign with Dawson Loudon's answer for one part and I created another function based on Barmar's comment that looks like this:
// resets other select box when selected
function reset_index(id) {
document.getElementById(id).selectedIndex = 'default';
}
An A element as a button doesn't seem appropriate, just use an img.
Anyhow, a function to use the first select with a selected option other than the first can be something like:
function getPath() {
var select;
var args = arguments;
for (var i=0, iLen=args.length; i<iLen; i++) {
select = document.getElementById(arg[i]);
if (select && select.selectedIndex > 0) {
window.location = 'http://www.mysite.com/download/' + select.value;
}
}
}
The above expects the first option to be the default selected, so if it's selected, or no option at all is selected, the select's selectedIndex will be 0 or -1 respsectively. I would ensure one option is selected by adding the selected attribute to the first one:
<option value="default" selected>Select File</option>
and the call is:
<img src="buttonImage.jpg" onclick="download('one', 'two');">
though you might want to add a class to the select elements and get them using getElementsByClassName or similar and loop over that collection, rather than hard code the ids.
Try replacing this:
<p class="button_image">
<a onclick="download(document.getElementById('one').value)"></a>
</p>
with:
<p class="button_image">
<a onclick="download(document.getElementById('one').value, document.getElementById('two').value)"></a>
</p>
and then replace your download function with this:
function download(file1,file2) {
if (file1 == 'default' && file2 == 'default'){
return;
}
else if(file1 != 'default'){
window.location = 'http://www.mysite.com/download/' + file1;
}
else{
window.location = 'http://www.mysite.com/download/' + file2;
}
}
I want to select a value in a select/option dropdown using javascript only.
Revised
sorry for confusion. Here is revised code.
document.getElementById("sel_activity").value = activity;
This will also work, but is a bit longer..
<select id='sel_activity'>
<option value='CYC'>Cycle Count</option>
<option value='INV'>Inventory Count</option>
<option value='INVDROP'>Inventory Drop off</option>
<option value='INVPICK'>Inventory Pick up</option>
<option value='TRAIN'>Training</option>
</select>
<script type="text/javascript">
var select = 'CYC';
var myselect=document.getElementById("sel_activity")
for (var i=0; i<myselect.options.length; i++){
if (myselect.options[i].value == select)
{
myselect.options[i].selected = true;
}
else
{
myselect.options[i].selected = false;
}
}
</script>
var myselect=document.getElementById("sel_activity")
myselect.options[myselect.options.length]=new Option("text","value");
http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/option.html
using jQuery
$("#sel_activity").val("CYC")
jQuery is a lightweight javasscript library which is very helpful in DOm traveral,event handling and ajax intearactions.
http://jquery.com/
Adding jQuery to your page is simple as adding one line of code in the head section to include the jQuery library
<head>
<script type="text/javascript" src="h ttp://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>