Show a tip for Options with Javascript - javascript

I have the following code which adds a bit of text below the select box when an item is selected. However it I can only get it to show the value of the select box. Is there any way I could get this to show a 3rd value?
<script type="text/javascript">
function dropdownTip(value){
console.log(value);
document.getElementById("result").innerHTML = value;
}</script>
<select onChange="dropdownTip(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;">
<option selected="selected" value="1">Client 1</option>
<option value="2">Client 2</option>
<option value="3">Client 3</option>
<option value="4">Client 4</option>
</select>
<div id="result"></div>
For example, I would like to add something like "Always remember to ask for the full name" on client one, and "Never ask for last name" On client 2.

This should work:
<script type="text/javascript">
function dropdownTip(value){
var preamble = 'default preamble';
if(value == 'Client 2') {
preamble = 'Never ask for last name on ';
}
if (value == 'Client one') {
preamble = 'Always remember to ask for the full name';
}
console.log(value);
document.getElementById("result").innerHTML = preamble + value;
}</script>
<select onChange="dropdownTip(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;">
<option selected="selected" value="1">Client 1</option>
<option value="2">Client 2</option>
<option value="3">Client 3</option>
<option value="4">Client 4</option>
</select>
<div id="result"></div>

You could use html5 data-* attributes.
Working demo.
javascript:
window.dropdownTip = function (obj) {
console.log(obj);
console.log(obj.value);
var sel = obj.options[obj.selectedIndex];
console.log(sel.getAttribute('data-desc'));
document.getElementById("result").innerHTML = obj.value;
document.getElementById("result").innerHTML += sel.getAttribute('data-desc');
}
html:
<body>
<select onchange="dropdownTip(this);" name="search_type" id="selector">
<option selected="selected" value="1" data-desc="test 1">Client 1</option>
<option value="2" data-desc="test 2">Client 2</option>
<option value="3" data-desc="test 3">Client 3</option>
<option value="4" data-desc="test 4">Client 4</option>
</select>
<div id="result"></div>
</body>

Related

How do I create a list of the selected options from a dropdwon

I am trying to loop through a multiple select dropdown list and add all of the selected options to a comma separated list.
My dropdown code is:
<select name="testnameID" id="testnameID" multiple>
<option value="1">Test number 1</option>
<option value="2">Test number 2</option>
<option value="3">Test number 3</option>
<option value="4">Test number 4</option>
<option value="5">Test number 5</option>
<select>
In my tag I am using the following, but think it can be simplified or improved:
var testnameID = $('#testnameID').val();
var testnameText;
Array.from(document.querySelector("#testnameID").options).forEach(function(option_element) {
let option_text = option_element.text;
let is_option_selected = option_element.selected;
if (is_option_selected===true){
testnameText = testnameText + option_text +", ";
console.log("TestnameText: "+testnameText);
console.log("\n\r");
}
});
I need to generate a variable, testnameText, which if the first three items were selected, would return a value of "Test number 1, Test number 2, Test number 3"
I'm getting myself in a muddle!
You can try using Document.querySelectorAll() to target all the selected options like the following way:
Array.from(document.querySelectorAll("#testnameID option:checked")).forEach(function(option_element) {
let option_text = option_element.text;
var testnameText = option_text +", ";
console.log("TestnameText: "+testnameText);
console.log("\n\r");
});
<select name="testnameID" id="testnameID" multiple>
<option value="1" selected>Test number 1</option>
<option value="2" selected>Test number 2</option>
<option value="3" selected>Test number 3</option>
<option value="4">Test number 4</option>
<option value="5">Test number 5</option>
<select>
You can also try using Array.prototype.map() and Arrow function expressions which is more shorter.
The following example creates an array of the selected options:
var checkedOptions = Array.from(document.querySelectorAll("#testnameID option:checked"));
var res = checkedOptions.map(option_element => ("TestnameText: "+option_element.text));
console.log(res);
<select name="testnameID" id="testnameID" multiple>
<option value="1" selected>Test number 1</option>
<option value="2" selected>Test number 2</option>
<option value="3" selected>Test number 3</option>
<option value="4">Test number 4</option>
<option value="5">Test number 5</option>
<select>
In this case, jquery's each() can help. So getting selected options is pretty simple:
$('#testnameID :selected').each(function (index, el) {
console.log("TestnameText: " + $(el).text());
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<select name="testnameID" id="testnameID" multiple>
<option value="1" selected>Test number 1</option>
<option value="2" selected>Test number 2</option>
<option value="3" selected>Test number 3</option>
<option value="4">Test number 4</option>
<option value="5">Test number 5</option>
</select>
selectedOptions contains all the selected options of a select element. You can use it like this:
const select = document.querySelector('select');
select.addEventListener('change', e => {
// Option texts as an array
const texts = Array.from(e.target.selectedOptions).map(({text}) => text);
// Option texts as a comma-separated string
const textsStr = texts.join(', ');
console.log(texts);
console.log(textsStr);
});
<select multiple>
<option value="1">Test number 1</option>
<option value="2">Test number 2</option>
<option value="3">Test number 3</option>
<option value="4">Test number 4</option>
<option value="5">Test number 5</option>
</select>
This works outside of the event too, just refer the select element directly instead of e.target.

Show text based on option selected in dropdown

I have a dropdown like below.
<label for="form_name">Title</label>
<select class="bootstrap-select">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div><p>Text1</p></div>
<div><p>Text2</p></div>
<div><p>Text3</p></div>
<div><p>Text4</p></div>
I intend to show Text 1 when Feature 1 is selected, Text 2 when Feature 2 is selected and so on.
Any ideas on how can I do this with JS (or jQuery)?
P.S. Most existing solutions require input field rather than options field or maybe I am too noob. xD
Give the p tags the id as the value of the options, and show the p tag when selected option has the value which is equal to the id of p
$('p').hide();
$('#1').show();
$('select').change(function() {
$('p').hide();
var a = $(this).val();
$("#" + a).show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="form_name">Title</label>
<select class="bootstrap-select">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div>
<p id="1">Text1</p>
</div>
<div>
<p id="2">Text2</p>
</div>
<div>
<p id="3">Text3</p>
</div>
<div>
<p id="4">Text4</p>
</div>
function display(){
var e = document.getElementById("dropDownId");
var index = e.selectedIndex;
if(index==0){
document.getElementById("first").style.display = 'block'
document.getElementById("second").style.display = 'none'
}
else if(index==1){
document.getElementById("first").style.display = 'none'
document.getElementById("second").style.display = 'block'
}
}
<label for="form_name">Title</label>
<select class="bootstrap-select" id="dropDownId" onchange="display()">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
</select>
<div id="first"><p>Text1</p></div>
<div id="second" style="display: none;"><p>Text2</p></div>
Please run this snippet..and check out your solution..
With pure javascript
let select = document.querySelector("select");
let divs = document.querySelectorAll("div");
let result = document.querySelector("#result");
function func1(par){
result.innerText = divs[par - 1].innerText;
}
div:not(#result) {
display:none;
}
<label for="form_name">Title</label>
<select class="bootstrap-select" onchange="func1(this.value)">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div><p>Text1</p></div>
<div><p>Text2</p></div>
<div><p>Text3</p></div>
<div><p>Text4</p></div>
<div id="result"></div>
You can use ids on your div that you want to show and change the value of your select with the ids you choosed
$("#select-panel").change(function(){
updateDisplay();
})
function updateDisplay(){
var idToShow = $("#select-panel").find(":selected").val() || "div1";
$(".subcontent").each(function(){
$(this).css("display",$(this).is("#"+idToShow) ? 'block' : 'none');
})
}
updateDisplay();
.subcontent{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-panel">
<option value="div1">1</option>
<option value="div2">2</option>
</select>
<div id="div1" class="subcontent">Text 1</div>
<div id="div2" class="subcontent">Text 2</div>

update list of <select> from another <select multiple> using jquery

I am trying to update a <select> element when I select one or multiple values from another <select multiple> using jQuery. Here's my multiple select:
<select class="form-control" multiple>
<option value="1">company 1</option>
<option value="2">company 2</option>
<option value="3">company 3</option>
<option value="4">company 4</option>
</select>
I hope this is what you are looking for,
$('select#first').change(function() {
$("select#second option:not(:first-child)").remove();
$(this).find("option:selected").each(function() {
$("select#second").append($(this).clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first" class="form-control" multiple>
<option value="1">company 1</option>
<option value="2">company 2</option>
<option value="3">company 3</option>
<option value="4">company 4</option>
</select>
<select name="second" id="second">
<option value=''>Select 2</select>
</select>
Check this script https://jsfiddle.net/gpb5wx8h/5/
Jquery:
function chooseItems(item, placeholder){
$(item).change(function() {
var item = $(this);
console.log(typeof(item.val()));
if(typeof item.val() == 'object'){
$.each(item.val(), function(i,v){
var selectedItem = item.find('option[value="'+ v +'"]'),
selectedText = selectedItem.text();
selectedItem.detach();
$(placeholder).append('<option value="' + v +'">' + selectedText + '</option>')
})
}
})
}
$(document).ready(function() {
chooseItems('.choose-role','.placeholder-role');
chooseItems('.placeholder-role','.choose-role');
})
HTML:
<select class="form-control choose-role" multiple>
<option value="1">company 1</option>
<option value="2">company 2</option>
<option value="3">company 3</option>
<option value="4">company 4</option>
</select>
<select class="form-control placeholder-role" multiple>
</select>
If you want to update select options by fetching data from the server end regarding the selected values in multiple select box then you can perform ajax operation and insert the result to the another select box which is to be updated.

Jquery disallow same value from multiple select lists

I need to make sure that when a value is selected in one of the lists, it cannot be selected in any of the others. Can this be done with jQuery, or do I need to create a validator that does not allow selection of the same value?
I have multiple select lists which are basically numbers only, i.e.
<select id="101_1">
<option value="0">0</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
<option value="3"> 3</option>
<option value="4"> 4</option>
<option value="5"> 5</option>
<option value="6"> 6</option>
<option value="7"> 7</option>
....
<option value="50"> 50</option>
</select>
<select id="101_2">
<option value="0">0</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
<option value="3"> 3</option>
<option value="4"> 4</option>
<option value="5"> 5</option>
<option value="6"> 6</option>
<option value="7"> 7</option>
....
<option value="50"> 50</option>
</select>
<select id="101_1">
<option value="0">0</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
<option value="3"> 3</option>
<option value="4"> 4</option>
<option value="5"> 5</option>
<option value="6"> 6</option>
<option value="7"> 7</option>
....
<option value="50"> 50</option>
</select>
I have gotten the following code to work for one of my colleagues :
HTML :
<h3>List 1</h3>
<select id="select1">
<option value="null">-- select --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<h3>List 2</h3>
<select id="select2">
<option value="null">-- select --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<h3>List 3</h3>
<select id="select3">
<option value="null">-- select --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
JS with jQuery :
$(document).ready(function() {
var selectState = {
'select1': 'null',
'select2': 'null',
'select3': 'null'
};
$('select').change(function() {
var selectId = $(this).attr('id');
var selectedOptionValue = $(this).val();
// for each other select element
$('select[id!="' + selectId + '"]').each(function(index) {
// enable the old option
$(this).find('option[value="' + selectState[selectId] + '"]').removeAttr('disabled');
if (selectedOptionValue !== 'null') { // if selected a real option
// disable the new option
$(this).find('option[value="' + selectedOptionValue + '"]').attr('disabled', 'disabled');
}
});
selectState[selectId] = selectedOptionValue; // update the new state at the end
});
});
And here is a CodePen
I opted to hide the option tag instead of remove as I suggested. Here is a complete working html file. I was going to post it on jsfiddle, but for some reason it wouldn't work. Be very aware of copy/paste errors in the .change handlers. Spent some time myself wondering why it wasn't working, but it was a copy/paste error.
Note that this code only works if every select tag has the same options. But, it works dynamically if you add or remove options later, while keeping them in sync as noted.
If you need it to work with lists with only some of the same options, you will be stuck dealing with having IDs on the options and then working the hiding/unhiding based on that instead of indexing into the children, but the basic mechanics are the same.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<style type="text/css">
.gone {display: none;}
</style>
<script type="text/javascript">
$(document).ready(function() {
// hides the option selected in the others
var hideValue = function(oldval, val, options, others) {
var unhideChild = -1;
var hideChild = -1;
// find which child to hide in the others
// also find the value we change from and unhide it
for (var i=1; i<options.length; i++) {
var optval = $(options[i]).val();
console.log(optval);
if (optval == val) {
hideChild = i;
}
if (optval == oldval) {
unhideChild = i;
}
}
if (unhideChild == -1 && oldval != "None") {
console.log("uh oh");
return;
}
if (hideChild == -1 && val != "None") {
console.log("uh oh");
return;
}
// hide them using the passed in selectors
for (var j=0; j<others.length; j++) {
if (oldval != "None") {
console.log("unhiding: " + others[j] + " v: " + unhideChild);
$($(others[j]).children()[unhideChild]).removeClass("gone");
}
if (val != "None") {
console.log("hiding: " + others[j] + " v: " + hideChild);
$($(others[j]).children()[hideChild]).addClass("gone");
}
}
}
// we need to keep track of the old values so we can unhide them if deselected
var val1 = "None";
var val2 = "None";
var val3 = "None"
$('#101_1').change(function() {
var opts = $('#101_1').children();
var v = $('#101_1').val();
hideValue(val1, v, opts, ["#101_2", "#101_3"]);
val1 = v;
});
$('#101_2').change(function() {
var opts = $('#101_2').children();
var v = $('#101_2').val();
hideValue(val2, v, opts, ["#101_1", "#101_3"]);
val2 = v;
});
$('#101_3').change(function() {
var opts = $('#101_3').children();
var v = $('#101_3').val();
hideValue(val3, v, opts, ["#101_2", "#101_1"]);
val3 = v;
});
});
</script>
</head>
<body>
<select value="None" id="101_1">
<option value="None">None</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select value="None" id="101_2">
<option value="None">None</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select value="None" id="101_3">
<option value="None">None</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
</html>
Also, if you need the "None" value to not be there, remove it. Then just start the select ta 101_1 having 0 selected, 101_2 with 1 selected etc. Then make sure to trigger the change handler. Also, without the None option, the for loop needs to start with i=0.
So basically add this to the end of the script and make sure var i starts at 0 instead of 1.
$('#101_1').val('0');
$('#101_2').val('1');
$('#101_3').val('2');
$('#101_1').trigger('change');
$('#101_2').trigger('change');
$('#101_3').trigger('change');

onchange dropdown add parameters to url in inputbox

I am designing affiliate program, in which each user has his own link-code aka tracking URL.
I am willing to add extra parameters to it depending on the drop down selection which will be different landing pages.
e.g.
original URL:
http://www.google.com/tracker/blah1
and if user selects value from down the URL should be like:
http://www.google.com/tracker/blah1/queryid/1
I am using this code for displaying the URL to the end user in the input box set as readonly.
<input size="100" type="text" value="<?=$url;?>" readonly> - <a target="_blank" href="<?=$url;?>">Link</a></b>
There's gonna be two drop down like these.
<select name="niche">
<option value="0" label="choose one">choose one</option>
<option value="/queryid/1" label="option 1">option 1</option>
<option value="/queryid/2" label="option 2">option 2</option>
<option value="/queryid/3" label="option 3">option 3</option>
<option value="/queryid/4" label="option 4">option 4</option>
<option value="/queryid/5" label="option 5">option 5</option>
<option value="/queryid/6" label="option 6">option 6</option>
</select>
By selecting option 1 it should add /queryid/1 to the end of the url.
if none is selected then no change will be there.
<select name="landingpage">
<option value="0" label="choose one">choose one</option>
<option value="/cid/1" label="landing 1">landing 1</option>
<option value="/cid/2" label="landing 2">landing 2</option>
</select>
By selecting landing 1 will add /cid/1 to the end of the URL.
if none is selected then no change will be there.
So how do I do this?
Update: updated the values of dropdown as currently using htaccess rewrite rules.
update:
I am using as specified by "Rishi Php" demo is here http://jsfiddle.net/g6U4a/2/
but by default its not showing SourceUrl
it should show the source URL by default, in the box but it shows it when user changes drop down values.
How can I achieve this?
update:
"Rishi Php" fixed the issue of on load default url.
here is the code. http://jsfiddle.net/g6U4a/3/
Thanks to all of you guys.
Don't forget to add this in header:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
replaced
var SourceUrl = "http://www.google.com/?tracker=blah1";
with
var SourceUrl = "<?=$url;?>";
so each affiliate will have unique link
Try this... It 'll help. *UPDATED WORKING DEMO*
var SourceUrl = "http://www.google.com/?tracker=blah1";
var queryUrl = "";
var landingUrl = "";
$(function() {
$('#querySelct').on('change', function () {
if($(this).val() == 0) {
queryUrl = "";
} else {
queryUrl = $(this).val();
}
MakeUrl();
return false;
});
$('#landingSelect').on('change', function () {
if($(this).val() == 0) {
landingUrl = "";
} else {
landingUrl = $(this).val();
}
MakeUrl();
return false;
});
});
function MakeUrl() {
var finalUrl = SourceUrl + queryUrl + landingUrl;
$('#urlBox').val(finalUrl);
$('#MyLink').attr('href', finalUrl);
}
You can use getElementById to get the values from the <select> fields and set them into your textfield.
DEMO: http://jsfiddle.net/g6U4a/1/
HTML
<select id="queryid">
<option value="0" label="choose one">choose one</option>
<option value="&queryid=1" label="option 1">option 1</option>
<option value="&queryid=2" label="option 2">option 2</option>
<option value="&queryid=3" label="option 3">option 3</option>
<option value="&queryid=4" label="option 4">option 4</option>
<option value="&queryid=5" label="option 5">option 5</option>
<option value="&queryid=6" label="option 6">option 6</option>
</select>
<br>
<select id="cid" name="landingpage">
<option value="0" label="choose one">choose one</option>
<option value="&cid=1" label="landing 1">landing 1</option>
<option value="&cid=2" label="landing 2">landing 2</option>
</select>
<input type="button" id="change" value="Create URL" onclick="createUrl()" /><br>
<input type="text" id="result" placeholder="placeholder" readonly><br>
JAVASCRIPT
function createUrl() {
var google = "http://www.google.com/";
document.getElementById("result").value = google + document.getElementById("queryid").value + document.getElementById("cid").value;
}
You could do something like this:
<select id="yourSelect" name="landingpage">
<option value="" label="choose one">choose one</option>
<option value="www.yourdomain.com&cid=1" label="landing 1">landing 1</option>
<option value="www.yourdomain.com&cid=2" label="landing 2">landing 2</option>
</select>
$(function(){
$('#yourSelect').on('change', function () {
var url = $(this).val();
if (url) {
window.location = url;
}
return false;
});
});
Give selector for selectbox like
var urlToAppend1=$('#nicheId :selected').val();
originalurl='http://www.google.com/?tracker=blah1';
var url='';
url+=originalurl;
url+=urlToAppend;
Try it.
$(function(){
$('select').change(function() {
var arr = new Array();
$('select option:selected').each(function(){
var value = $(this).val();
if(value != "0"){
arr.push($(this).val());
}
});
// selected value are now concatenating here.
var str = arr.join('');
alert(str);
});
});

Categories