How to put a link in a drop list option? - javascript

I have a drop down list. I want the options to contain 2 parts. First part will contain the name of the option and the second part will contain a link which will open a dialog box, where user can edit the name of that particular option.
When the user clicks on the name, the option should get selected. When the user clicks on edit link, it should open the dialog box, the option should not get selected in this case.
Also, I want to have access to this option's name when the user clicks on the edit link. I searched a lot on this, but could not find any solution.
Thanks.
var elements = ['abc', 'def', 'ghi'];
$("[name='inputboxname']").textcomplete([{
match: /{(\w*)$/,
search: function (term, callback) {
callback($.map(elements, function (element) {
return element.indexOf(term) === 0 ? element : null;
}));
},
index: 1,
replace: function (element) {
return ['{' + element + '}', ' '];
},
template: function (value) {
return '<div class="onleft">' + value + '</div><div class="onright">Edit </div>';
}
}], {
header: '<button data-hook="addnew" class="wendda">Add new</button>',
maxCount: 5
});

I want the options to contain 2 parts. First part will contain the
name of the option and the second part will contain a link which will
open a dialog box
Basic html select tag won't help here, you need external plugin e.g. select2.

Like this,
<select onChange="window.location.href=this.value">
<option value="www.google.com">Google</option>
<option value="www.gmail.com">Gmail</option>
</select>

You can't add a href tag in option, but you can use like this-
<select>
<option> option1 </option>
<option> option1 </option>
<option onclick="window.location.href='your_page.html'"> Option 3</option>
</select>
I hope it will helps you.

Related

How to dynamically update select value?

Can anyone please help me how to accomplish following?
I have a dropdown field, which have flowers name.The default value is "Select your favorite flower". On tap or click, the dropdown opens and shows the list of options and when user selects a particular value, the field shows the selected flower name.
I need to append Favorite Flower: then the selected value. Can you guys please help me in how to accomplish this?
Please see the image:
All three states of dropdown
HTML Code
<select>
<list> Select your favorite flower</list>
<list>Rose</Rose> <list>Marigold </list>
<list>Lily</lily>
</select>
Use a change event, append a span with the text to the selected option:
$('select').on('change',function() {
$('option').find('span').remove();//remove previous selected span
var val = $(this).find(':selected').html();//get the text/html of the potion
$(this).find(':selected').html('<span>Favorite Flower: </span>'+val);//change the text with the option
});
https://jsfiddle.net/r5377h21/
or:
$('select').on('change',function() {
$('option').find('span').remove();
var selected = $(this).find(':selected'),
val = selected.html();
if(!selected.is('option:first')) {
$(this).find(':selected').html('<span>Favorite Flower: </span>'+val);
}
});
https://jsfiddle.net/r5377h21/1/
can you please try this.
let me know if you need any changes in it
Code :
<script>
function test(obj)
{
$("select option").each(function(){
$(this).text($(this).text().replace("favorite flower - ",""))
})
if($("option:selected",$(obj)).val() != -1){
$("option:selected",$(obj)).text("favorite flower - "+$("option:selected",$(obj)).text())
}
}
</script>
<select onchange="test(this)">
<option value="-1">Select your favorite flower</option>
<option>Rose</option>
<option>Marigold</option>
<option>Lily</option>
</select>

Automaticly setting default texts in select dropdown

I have a very simple select dropdown with urls that direct users to respective pages
<select>
<option value="url1">title1 </option>
<option value="url2">title2 </option>
<option value="url3">title3 </option>
.........
</select>
I will have this drop down in all these (url1, url2, url3...) serving for navigation. Would it be possible to set the default text in the selection box based on my urls? Say if I am currently on url2, my default text in the selection box will be title2. I know manually you can just use
<option selected="selected" value="url2">title2</option>
But is there a way I can use javascript to do because I have hundreds of pages? All the urls and titles are stored in an array that I can retrieve.
Thanks for your help!
Assuming you want to match the url in the window location (such as http://www.example.com/some/page.html) with the URL to the page found in your dropdown:
var dropdown = document.getElementById( 'dropdown' );
for ( var i = 0; i < dropdown.childElementCount; ++i ) {
if ( dropdown.children[i].value === document.location.href) {
dropdown.selectedIndex = i;
break;
}
}
Where 'dropdown' contains the ID of your <select> element. Jsfiddle: http://jsfiddle.net/RhZy6/
You should be able to use this:
var path = decodeURIComponent(window.location.pathname.replace(/\/$/, ""));
$("option").each(function () {
var url = $(this).val();
if (path.substring(0, url.length) === url) {
$(this).prop('selected', true);
}
});
Path is the end of the URL. The next block of code loops through the option elements and looks to see if the option value matches the path, and if it does, sets the selected property to true.
You can get the current URL using document.URL and on document ready you can use ,
$("#selectId option[value=" + document.URL + "]").prop('selected', true);
However document.URL contains full path , so you need to truncate the unnecessary part like http:// https:/ , if it is not present in value of select.
And , here is the working fiddle
P.S The Fiddle will work second time only. It is shwoing diffrent URL on first time. Gotta be a JSFiddle personal thing.
Say you have
<form name="MyForm">
<select name="SelectBox1">
<option>One
<option>Two
<option>Three
</select>
.. etc .. rest of form/page ..
then in your javascript code ..
var el=document.forms.MyForm.SelectBox1;
el.selectedIndex=2; // sets option to "Three" in Select box, because first option is number 0, second =1, third = 2 etc
Or to set it to a value use a function like this .. pass in the Select field name and the value it should be
function setSelect(sFieldName, sValue) {
var el=document.getElementsByName(sFieldName)[0] // returns array of all elements with that name so use [0] to get 1st one
for (var i=0;i<el.options.length;
if (el.options[i].value == sValue) { // if they match...
el.selectedIndex=i; // then this should be the default
}
}
call it usiong something like
setSelect("SelectBox1","http://ectetc")

customize java script function from particular page when that method is used by many pages

I have a drop down like
<select>
<option value="">Select</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
</select>
I have the same select box in more than 10 places in different pages.This is populating through ajax.But when i am calling this from a particular page i need to select ABC by default.But i don't want in remaining places.
I don't want to write the code again in my page.Is there any possibility for this.
Thanks in advance...
It's going to be a very generic answer that you'll have to modify for your needs, but if the select and all other markup is the same on all pages, which is very unlikely, you have to check the URL to see if you're on a certain page.
At the bottom of the page, before </body>, you can do something like :
if ( window.location.href.indexOf('/mysite.html') != -1 ) {
document.getElementsByTagName('select')[0].value = '1';
}
This will set the default value of the first select on the page to 1, and show ABC, if the URL contains mysite.html.
FIDDLE
Here you have another example (with JQuery) taking into account the comment you did about loading your combos with options obtained with ajax: Try if yourself
JQUERY:
var options = "<option value=\"\">Select</option><option value=\"1\">ABC</option><option value=\"2\">DEF</option>";
function test() {
// Populate select with ID destiny 1 without selecting a value
populate("#destiny1", null, options);
// Populate select with ID destiny 2, selecting the value of the first index
populate("#destiny2", 1, options);
}
function populate(destiny, indexOption, options) {
$(destiny).html(options);
if (indexOption != null) {
$(destiny + " option")[indexOption].selected = true;
$(destiny).trigger("change");
}
}
HTML:
<select id="destiny1"></select>
<select id="destiny2"></select>
<input type="button" onclick="test()" value="TEST"></input>

Get selected option data using Jquery or javascript

I have to get the selected option data whose option value is known. I have the selected option value and I want the data which is wrapped between the option.
For example in the following select:
<select name="oi_report_contact[sex]" id="oi_report_contact_sex">
<option value="1">Male</option>
<option value="2">Female</option>
<option value="3">Other</option>
</select>
I have value 1, I need to get the data "Male" through Jquery or Javascript.
Please note : $('#oi_report_contact_sex').val(); will give 1 and not male, when 1 is selected.
You just have to call
var content = $('#oi_report_contact_sex option:selected').html();
to get the inner content of the selected option.
You can use .text() method to get the text value. Like this.
$('#oi_report_contact_sex').on('change', function () {
alert($('#oi_report_contact_sex').val());
alert($('#oi_report_contact_sex option:selected').text());
});
$("#oi_report_contact_sex").find('option:selected').text();
You can try:
$("#oi_report_contact_sex option[value='" + $("#oi_report_contact_sex").val() + "']").text()
jsFiddle link: http://jsfiddle.net/ARBb2/1/

jQuery to update a div depending on the selection from dropdowns

We have two dropdowns that according to your selection it changes part of the string in some div containers. The purpose of this is to return URLs to give to clients.
This is a sample of the code
<select name="lstLanguage" id="lstLanguage">
<OPTION VALUE="">-- Generic default ---</OPTION>
<OPTION ID="Arabic" VALUE="AR">Arabic</OPTION>
<OPTION ID="German" VALUE="D">German</OPTION>
</select>
<select name="lstTemplate" id="lstTemplate">
<OPTION VALUE="">-- Generic default ---</OPTION>
<OPTION VALUE="1">Member</OPTION>
<OPTION VALUE="2">NonMember</OPTION>
</select>
<div id='Ind_URL'>http://example.com/Registration.asp?Language_Code=?Role=</div>
<div id='Ind_W_URL'>http://example.com/Registration.asp?Language_Code=?Role=</div>
<div id='Login_URL'>http://example.com/?Language_Code=</div>
And this is the jQuery we currently have, which was provided by irama.
$(function(){
divIDs = [
'Ind_URL',
'Ind_W_URL',
'Login_URL',
];
$('#lstTemplate').bind('change', function(){
role = $(this).find('option:selected').val();
updateURLDivs(langCode=null, role);
});
$('#lstLanguage').bind('change', function(){
langCode = $(this).find('option:selected').val();
updateURLDivs(langCode, role=null);
});
updateURLDivs = function (langCode, role) {
for (i in divIDs) {
currentDiv = $('#'+divIDs[i]);
if (langCode !== null) {
currentDiv.data('Language_Code', langCode);
}
if (role !== null) {
currentDiv.data('role', role);
}
// Cache original div contents, so that the select menu can be changed more than once.
if (typeof currentDiv.data('contents') == 'undefined') {
divContents = currentDiv .html();
currentDiv .data('contents', divContents);
} else {
divContents = currentDiv .data('contents');
}
currentDiv.empty().append(
divContents
.replace('role=','role='+currentDiv.data('role'))
.replace('Language_Code=','Language_Code='+currentDiv.data('Language_Code'))
);
}
}
});
This is working fine, but this morning we found a few issues
It is currently updating both parameters, no matter if you change one or both. We need it to update if you change the template, just the template and if you change the language just the language.
If nothing is selected we need it to replace it with a blank not with undefined as it is currently doing
If we change the Template it also needs to replace Registration.asp to PersonImport.asp from the URLs
This is how it should work
The div containers need to have the default URLs in them
If I change the language (lstLanguage) it should just change the Language_Code on the DIV containers. Then if I select the language option with no value ("Generic default") the Language_Code should be blank ''
If I change the template (lstTemplate) it should change the Role on the DIV containers. Also should change Registration.asp to PersonImport.asp. Then if I select the template option with no value ("Generic Default) the Role should be blank '' and PersonImport.asp should go back to Registration.asp.
I'm not a good coder on this, but it would be great if any of you can give me a hand with this.
Thanks in advance
Federico
I have create a fiddle with a lot of improvement in your code. Take a look.
Working demo

Categories

Resources