I need jquery plugin which would transform my simple
<select>
<option>text</option>
</select>
In to fully customizable list something like a <lu> list or list of <div>, i have found quite a lot of this kind of plugins, but none of them have option to type something in and set it as an option.
Lets say i have kind of list:
<select>
<option value="text">text</option>
<option value="other">other</option>
</select>
Now i want other option transform into <input type="text" />, and i'm quite sure there has to be plugin which does just that.
I have made an example how should it look, on the left is my current plugin and on the right is what i need, i know i could edit my current plugin but it's just way to big for me and it would take to much time.
There is no jQuery plugin which does exactly that. However, there is a jQuery UI selectmenu plugin, which converts a select element to a html representation such that you can style the select menu. This plugin also offers a callback for formatting text, such that in our case, we could format our 'other' option into an input box.
Suppose we have the following select:
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
<option>Other</option>
</select>
We can create a selectmenu with this plugin using:
$(function(){
selectMenu = $('select#otherselect').selectmenu({
style:'popup',
width: 300,
format: otherFormatting
});
});
In here the function otherFormatting is a function which will format our Other option. This is our function:
var otherFormatting = function(text){
// if text contains 'Other' format into Other input box...
if ( text == "Other" ) {
var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
var input = $('<input class="other" type="text" value="Other..."/>');
return $('<span/>')
.append(input)
.append(button)[0].outerHTML;
}
return text;
}
The selectOther function that is called when the button is clicked, is a function we will extend the plugin with. This function, activated when the button is clicked, will set the values of our select, such that we can easily submit it using a form. But also, set the value which is displayed in the new selectmenu (instead of showing an input box in the select box).
We need to extend this plugin, which is a jQuery UI widget basically. However, since the plugin binds some events which make it impossible for us to get the input field and button working, we need to unbind some of these. We do this when we open the select menu. For this we need to override the open function of the widget, call our function that unbinds some events and then open the menu using the original open function.
Putting this all together:
<!DOCTYPE html>
<html>
<head>
<title>Demo Page for jQuery UI selectmenu</title>
<link type="text/css" href="../../themes/base/jquery.ui.all.css" rel="stylesheet" />
<link type="text/css" href="../../themes/base/jquery.ui.selectmenu.css" rel="stylesheet" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.position.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.selectmenu.js"></script>
<style type="text/css">
body {font-size: 62.5%; font-family: "Verdana",sans-serif; }
fieldset { border: 0; }
label, select, .ui-select-menu { float: left; margin-right: 10px; }
select { width: 200px; }
</style>
<script type="text/javascript">
// We need to able to call the original open method, save intoIf you need to call original method
var fn_open = $.ui.selectmenu.prototype.open;
$.widget("ui.selectmenu", $.extend({}, $.ui.selectmenu.prototype, {
open : function() {
// Every the selectmenu is opened, unbind some events...
this._unbindEvents();
fn_open.apply(this, arguments);
},
_unbindEvents : function() {
var el = $(this.list).find('li:has(input.other)').eq(0);
// unbind events, we need a different event here...
el.unbind('mouseup');
el.unbind('mousedown');
el.bind('mousedown', function() {
// We need to call focus here explicitly
$(this).find('input.other').eq(0).focus();
// Empty field on click...
if ( $(this).find('input.other').eq(0).val() == 'Other...' )
$(this).find('input.other').eq(0).val("");
});
// Unbind keydown, because otherwise we cannot type in our textfield....
this.list.unbind('keydown');
// We only need to return false on the mousedown event.
this.list.unbind('mousedown.selectmenu mouseup.selectmenu');
this.list.bind('mousedown', function() {
return false;
});
},
selectOther : function(el) {
var button = $(el);
// li item contains the index
var itemIndex = button.parent().parent().parent().data('index');
var changed = itemIndex != this._selectedIndex();
// Get the value of the input field
var newVal = button.prev().val();
this.index(itemIndex);
// Update the display value in the styled select menu.
this.newelement.find('.' + this.widgetBaseClass + '-status').html(newVal);
// Update the value and html of the option in the original select.
$(this.element[0].options[itemIndex]).val(newVal).html(newVal);
// Call the select, change and close methods
var e = jQuery.Event("mouseup");
this.select(e);
if ( changed )
this.change(e);
this.close(e);
}
}));
var selectMenu;
$(function(){
selectMenu = $('select#otherselect').selectmenu({
style:'popup',
width: 300,
format: otherFormatting
});
});
function selectOther(el) {
// Call our self defined selectOther function.
selectMenu.selectmenu('selectOther', el);
}
//a custom format option callback
var otherFormatting = function(text){
// if text contains 'Other' format into Other input box...
if ( text == "Other" ) {
var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
var input = $('<input class="other" type="text" value="Other..."/>');
return $('<span/>')
.append(input)
.append(button)[0].outerHTML;
}
return text;
}
</script>
</head>
<body>
<h2>Select with Other option input field</h2>
<fieldset>
<label for="otherselect">Select a value:</label>
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
<option>Other</option>
</select>
</fieldset>
<button onclick="console.log($('#otherselect').val());">Test</button>
</body>
</html>
To try this, download the plugin here and make sure the urls to the js/css files are correct. (I have put this html file into the demos/selectmenu folder and it works...). Ofcourse you can replace the button with an image.
Try this, this little script will create a text input after a select box if the select box value is other. The new text input as the same name of the select so that its value overwrite the one set by the select (as it is other)
If the value is something else than other we just check for the text input presence and remove it (so it doesn't overwrite the select value)
http://jsfiddle.net/cW725/1/
HTML
<form>
<p>
<select>
<option value="text">text</option>
<option value="text">text</option>
<option value="text">text</option>
<option value="other">other</option>
</select>
</p>
<p>
<select>
<option value="text">text</option>
<option value="text">text</option>
<option value="text">text</option>
<option value="other">other</option>
</select>
</p>
</form>
jQuery
$(function() {
// bind all select on change
$('select').on('change', function() {
// if value is other
if ($(this).val() == 'other') {
// add a text input we match the name so that this input overwrite the select one as after in the form
$(this).after('<input type="text" name="' + $(this).attr('name') + '" class="otherInput" />');
} else {
if ($(this).next().is('input.otherInput')) {
$(this).next().remove();
};
};
});
});
I was looking for a jquery 'select or edit' solution, and found this can be done with help of select2 plugin.
Turned out to be pretty simple solution that does exactly what I wanted.
HTML:
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
</select>
JS:
$('#otherselect').select2({tags: true});
Example:
https://jsfiddle.net/h0qp37jk/
You might check out chosen.js - it might fit your needs. Might be easier that making something from scratch. Good luck.
Related
I want to autoselect select box option on page load. Here is my code which is not working.
jQuery(document).ready(function(){
jQuery(".configure_supre_select_1 option:eq(1)")
.attr('selected',true)
.trigger('change');
});
You are triggering the selected option instead of the select - also use prop
$(function(){
$(".configure_supre_select_1 option:eq(1)").prop('selected',true);
$(".configure_supre_select_1").trigger('change');
});
Alternatively set the value
$(function(){
$(".configure_supre_select_1").val("firstOptionValue").change();
});
$(function() {
$(".configure_supre_select_1").on("change", function() {
$(".optdiv").hide();
var val = this.value;
if (val) {
$("#" + val.replace("OptionValue", "")).show();
}
});
$(".configure_supre_select_1").val("firstOptionValue").change();
$(".configure_supre_select_2 option:eq(1)").prop('selected',true);
$(".configure_supre_select_2").trigger('change');
});
.optdiv {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="configure_supre_select_1">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
<div class="optdiv" id="first">First is selected</div>
<div class="optdiv" id="second">Second is selected</div>
<hr />
Here I use your version <br/>
<select class="configure_supre_select_2">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
For make real time click by jquery i added below code. It used "Event".
For change select option on page load i use below code:
jQuery(".configure_supre_select_1").val(jQuery(".configure_supre_select_1 option:eq(1)").val()).change();
and then make it real time changing i use below code:
var dropdown = $("SelectAttributeId"); // Id of select box
var element = dropdown;
var event = 'change';
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);
I am using the jQuery multiselect api to select multiple values in my application,but what i want that,when i click on a button beside that multiselect box all the selected values should be fetched.But i am not able to do that ,Here i am posting my code.
<link rel="stylesheet" type="text/css" href="http://labs.abeautifulsite.net/archived/jquery-multiSelect/jquery.multiSelect.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://labs.abeautifulsite.net/archived/jquery-multiSelect/jquery.multiSelect.js">
</script>
<h1>Form Submission Test</h1>
<p>Testing to ensure the correct values are actually passed when the form is submitted.</p>
<select name="region" id="regionHome">
<option value="MDC">MDC</option>
<option value="LAC">LAC</option>
<option value="BRO/WPB">BRO/WPB</option>
<option value="NOE">NOE</option>
<option value="OTHER">OTHER</option>
</select>
<input type="button" value="Search" onclick="searchByDate()" class="searchButton">
<script>
$("#regionHome").multiSelect();
function searchByDate() {
alert("There are " + $('input[name="regionHome[]"]:checked').length + " boxes selected");
var foo = [];
$('input[name="regionHome[]"]:checked').each(function (i, selected) {
$( 'div.regionHome' ).replaceWith( "<p>Test</p>" );
foo[i] = $(selected).val();
alert(foo[i]);
});
}
</script>
Selection along with count is here i am trying to show the count of each selected values in the label with each select i.e when ever i will select a value the count will be updated in the label fiddle is here
working fiddle
Thanks for posting the link to the place where the plugin is located. After checking it, the error is a simple typographical mistake.
Use this:
// notice the capital S in multiSelect
$("#regionHome").multiSelect();
Instead of:
// all lower case = BAD
$("#regionHome").multiselect();
You can see it working with your code on this JSFiddle: http://jsfiddle.net/gbtceq2m/
Now that the multiSelect works, you need to realize that the initial select "doesn't exist anymore" (not in the same way). It has been replaced by a set of checkboxes that mimic a multiselect. So you need to update the selector to work with those checkboxes instead of with the select options:
$('input[name="regionHome[]"]:checked').each(function (i, selected) {
foo[i] = $(selected).val();
alert(foo[i]);
});
You can see it working here: http://jsfiddle.net/gbtceq2m/1/
I'm guessing drop down should allow multiple selection?
If so, you'd have to add multiple attribute to your select drop down like below:
<select class="js-region-list-box" name="region" id="regionHome" multiple="true">
<option value="MDC">MDC</option>
<option value="LAC">LAC</option>
...
</select>
Also, jQuery provides .val() method which can be used to get value out of any form field.
In case of select box (drop down allowing multiple selection) .val() will return all the selected values separated by a comma
More Info about val() is here
Based on above info.
You could approach it like this
html
<select class="js-region-list-box" name="region" id="regionHome" multiple="true">
<option value="MDC">MDC</option>
<option value="LAC">LAC</option>
<option value="BRO/WPB">BRO/WPB</option>
<option value="NOE">NOE</option>
<option value="OTHER">OTHER</option>
</select>
<button class="js-regions">Get Regions</button>
js
var $regionListBox = $(".js-region-list-box");
$(".js-regions").on("click", function(e) {
e.preventDefault();
var selectedRegions = $regionListBox.val();
alert(selectedRegions);
});
Fiddle link: http://jsfiddle.net/Varinder/zdb06jp8/
I am after a country select box with a text box below for state and provinces of countries. however, if US or Canada is chosen in the select box, the text box is replaced with a new corresponding select box with either US or Canada state or province options. (depending on the choice)
Basically, If United States is chosen, show a new select with the states...
If Canada is chosen, show a new select with Canadian Provinces...
If any other country is chosen, just show the text box where they can enter their area.
After bouncing around the site, I have came reasonably close with the code shown below. The Divs display properly, however if I put in a select box in either the United states div or the Canada Div, it breaks it.
So, for this display propose, I just left text in this example so as to have a working example. Any help in finding out why it breaks with a select box inside the US and Canada divs would be greatly appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Show Hide Using Selectbox</title>
<style type="text/css"></style>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="ca"){
$(".box").hide();
$(".ca").show();
}
else if ($(this).attr("value")=="us"){
$(".box").hide();
$(".us").show();
}
else if(($(this).attr("value")!="us") || ($(this).attr("value")=="ca")){
$(".box").hide();
$(".any").show();
}
});
}).change();
});
</script>
<div>
<select>
<option>choose country</option>
<option value="ca">Canada</option>
<option value="us">USA</option>
<option value="mx">Mexico</option>
<option value="Albania">Albania</option>
<option value="Aruba">Aruba</option>
</select>
</div>
<div style="display:none;" class="ca box"><strong>Canada Province Select Box...</strong></div>
<div style="display:none;" class="us box"><strong>United States State Select Box</strong></div>
<div style="display:none;" class="any box" >Enter your Region:<br><input name="state" type="text"></div>
</body>
</html>
It's because your javascript is targeting every single select element on the page.
Use a more unique selector
<select id="country">
<option>cho`enter code here`ose country</option>
<option value="ca">Canada</option>
<option value="us">USA</option>
<option value="mx">Mexico</option>
<option value="Albania">Albania</option>
<option value="Aruba">Aruba</option>
</select>
and target that
$("#country").change(function(){
$(".box").hide();
$("." + this.value).toggle(['ca','us'].indexOf(this.value)!=-1);
$(".any").toggle(['ca','us'].indexOf(this.value)==-1);
});
and yes, I just replaced your event handler with two lines !
FIDDLE
It's hard to tell without the exact code you were using that broke, but my guess would be because your select events would be hooked up with it, so basically you'd wind up running the change on itself as well, causing unexpected behavior.
If you were to throw the non-working version in to JSFiddle, it'd be easier to play around with and give a more exact answer.
i made a fiddle that fixes your code http://jsfiddle.net/DP2n2/1/
first you need to have .change() only 1 time
then you don't need each() on $( "select option:selected")
$( "select option:selected").val() will retrieve the value
and after show() the div with that value like this
var selectedCountry = $( "select option:selected").val();
$('.'+selectedCountry).show();
EDIT: updated fiddle http://jsfiddle.net/DP2n2/2/
fixed bug . sry ..
$('.box').hide(); // outside if()
Another way to do it:
$(document).ready(function(){
$('select').on('change', function(){
var with_select = ['ca', 'us']; // easy to manage values that
// require selects
var val = $(this).val(); // this kind of things makes it more
// easy
$('.box').hide(); // hide all boxes. the code runs fast
// enough
for( var i in with_select ){
if( with_select[i] == val ){ // we check through the array **if** the
$('.' + val).show(); // value matches. in that case we show
return false; // the required select and return false
} // to exit of method
}
$('.any').show(); // **else** we show the text input
});
});
http://jsfiddle.net/UBf8e/
I'm trying to figure out how to sync two multiple choice lists in javascript. Here's the code which works:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<script language="JavaScript">
<!--
function SelectEmail(name)
{
var listboxEmails = document.getElementById('emails');
for (var i=0;i<listboxEmails.length;i++)
{
listboxname = listboxEmails[i].innerHTML
if (listboxname == name)
{
listboxEmails.selectedIndex = i;
break;
}
}//end for
}//end function SelectEmail
// -->
</script>
<body>
<select id='names' name ='names' style = "width: 100" multiple="multiple" onClick="SelectEmail(this.value);">
<option value ="joe">joe</option>
<option value ="albert">albert</option>
<option value ="gary">gary</option>
<option value ="ace">ace</option>
</select>
<select id="emails" name ="emails" style = "width: 100;" multiple="multiple">
<option value ="joe#asds.com">joe</option>
<option value ="albert#asds.com">albert</option>
<option value ="gary#asds.com">gary</option>
<option value ="ace#asds.com">ace</option>
</SELECT>
</body>
</html>
However I want to make it show multiple choices. So for example if I choose albert and gary on the left list, I want the right list to select albert and gary as well. Please help me with this. Cheers.
Your function SelectEmail() can't work because it sets selectedIndex of your select, which selects one option and deselects the rest. Also, you are using the text content of the options in #emails in order to map them with the values of #names. That's not a good practice, because text nodes are supposed to show text and not to enable the identification of elements in your script.
Instead, you can access the selected attribute separately for each option you want to select. By adding an additional attribute to your #emails element's options, it could look like:
<select id="emails" name="emails" style="width: 100;" multiple="multiple">
<option value="joe#asds.com" data-name="joe">joe</option>
<option value="albert#asds.com" data-name="albert">albert</option>
<option value="gary#asds.com" data-name="gary">gary</option>
<option value="ace#asds.com" data-name="ace">ace</option>
</select>
You can now use the data-name attribute to map the options, for example in the following way:
function selectEmail() {
// deselect all
$('#emails option').removeAttr('selected');
var names = $('#names').val();
if (names == null) {
// none selected
return;
}
$.each(names, function (i, name) {
var selector = 'option[data-name="' + name + '"]';
$('#emails ' + selector).attr('selected', true);
});
}
Here's a working fiddle (you will notice that I also used the onchange event instead of onclick:
http://jsfiddle.net/H9hNH/2/
I have a select box and a label with a span, I want to replace span content as users change their selection on the drop down box.
<select class="text_select" id="field_6" name="field_6">
<option value="- Select -">- Select -</option>
<option value="Option One">Option One</option>
<option value="Option Two">Option Two</option>
<option value="Option Three">Option Three</option>
</select>
<label class="form_field">Your selected <span id="aggregator_name"></span>?</label>
I'm using this script
<script type="text/javascript">
function notEmpty(){
var e = document.getElementById("field_6");
var strUser = e.options[e.selectedIndex].value;
document.getElementById('aggregator_name').innerHTML = strUser;
}
notEmpty()
</script>
Problem with this is, whenever I refresh the page, span is replace with "- Select -" but when I change the dropdown to another option, it doesn't change content of the span?
Please help guys.
You need to call your function from the change event of the drop-down:
document.getElementById("field_6").onchange = notEmpty;
Demo: http://jsfiddle.net/Mj4Vj/
Or, since you've used the "jquery" tag, the following replaces all of your JS:
$(document).ready(function() {
$("#field_6").change(function() {
$('#aggregator_name').html($(this).val());
}).change();
});
Demo: http://jsfiddle.net/Mj4Vj/1/
(Note: if the above is included in a script block that appears after the "field_6" element, e.g., if your script is at the end of the body, then you don't need to wrap the code in a document ready handler.)
Working demo http://jsfiddle.net/GEfwE/1/
Behaviour: when ever you will change anything you will see the cahnge in span,
Hope this helps, please lemme know if I missed anything! `:)~
code
$('select').change(function(){
$('#aggregator_name').html($(this).val());
});
you can use onchange.
var e = document.getElementById("field_6");
e.onchange = function() {
var strUser = e.options[e.selectedIndex].value;
document.getElementById('aggregator_name').innerHTML = strUser;
}