I am trying to make dropdown enabling using jquery - javascript

I am trying to make dropdown enabling using jquery and click search then that category page should open.But I am uable to do it.When I am selecting any one option from "SEARCH BY MAKE" dropdown the next "SEARCH BY MODEL" dropdown should enable and this is same for other dropdown.Means next dropdown is depanded on previous.When I select option from last dropdown the search button should display,which I am hiding when page loads.I have lot of categories in "SEARCH BY MAKE".I want all the pages should open dynamically after clicking on search button.According to this three dropdowns the category or product page should open.Please help me out.Please check bellow code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<title>Untitled Document</title>
</head>
<body>
<form>
<select id="Make" name="Make" class="criterion">
<option value="">SEARCH BY MAKE</option>
<option value="1">ACURA</option>
<option value="2">INTEGRA</option>
<option value="3">MDX</option>
</select>
</form><br />
<form>
<select id="Model" name="Model" class="criterion">
<option value="">SEARCH BY MODEL</option>
<option value="1">XYZ</option>
</select>
</form><br />
<form>
<select id="Year" name="Year" class="criterion">
<option value="">SEARCH BY YEAR</option>
<option value="1">ABC</option>
</form>
<br />
<input type="submit" value="Search" class="CatsearchButton" />
<script type="text/javascript">
$(document).ready(function() {
$('.CatsearchButton').hide();
var $selects = $('select.criterion');
$selects.not("#Year").on('change', function() {
$selects.each(function() {
var $this = $(this);
var disable = $this.val() == '';
$this.closest('form').nextAll().find('select').prop('disabled', disable);
if (disable) return false;
})
}).eq(0).trigger('change');
$selects.filter('#Year').change(function() {
$('.CatsearchButton').show();
});
});
</script>
</body>
</html>

You are using jQuery 1.7.2 so use .prop() instead of .attr() to set the disabled property.
You were also using .removeAttr('disabled', false); wrong - it should have been .attr('disabled','false'); or just .removeAttr('disabled'), but it's irrelevant once you switch to .prop()
$('.go').hide();
var jSelect2 = $(".model");
jSelect2.prop('disabled', true);
var jSelect3 = $(".year");
jSelect3.prop('disabled', true);
$('.make').change(function() {
jSelect2.prop('disabled', $(this).val() == ' '); // disable if val == ' '
jSelect2.val(' ').change(); // set to default and trigger change
});
jSelect2.change(function() {
jSelect3.prop('disabled', $(this).val() == ' '); // disable if val == ' '
jSelect3.val(' ').change(); // set to default and trigger change
});
jSelect3.change(function() {
$('.go').toggle($(this).val() !== ' '); // show if val !== ' '
});
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.
http://jsfiddle.net/CE5VN/1/
EDIT:
Since you're using jQuery just remove teh inline code and bind the click event inside document.ready function
$('.go').click(function(e) {
e.preventDefault();
location = 'www.lightsmax.com/category_s/' + myform.make.options[myform.make.selectedIndex].value + '.htm' + myform.model.options[myform.model.selectedIndex].value + '/' + myform.year.options[myform.year.selectedIndex].value;
});
http://jsfiddle.net/CE5VN/2/

It is because you have spaces in the values so it does not go into the if statements.

$(document).ready(function() {
$("select").each(function(i){
$(this).addClass("class-" + i);
});
$("select").each(function(i){
$(this)[0].disabled = true;
$(this).change(function(){
if($(this).val()!=""){
$(".class-" + (i + 1))[0].disabled = false;
}
});
});
$("select:eq(0)")[0].disabled = false;
});
I am adding fiddle here

Related

How to display multiple dropdown value on another html fields using jquery

I have few dropdown with text fields.
I want to get all those values and display on a button.
The only condition is that button should be generate upto 5 time.
means -> if all the value of dropdown & text field are displaying on a button field so i want to generate another button and again i want to display my value on that by clicking on generate button.
Here is my code for reference.
$('#left_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#left_period_guider").html('(period,offset)');
}else if ($(this).val()=='ema') {
$("#left_period_guider").html('(close,period,offset)');
}
});
$('#right_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#right_period_guider").html('(period,offset)');
}else if ($(this).val()=='ema') {
$("#right_period_guider").html('(close,period,offset)');
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<select name="left_indicator" id="left_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator">
<option>select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
This button should generate by clicking above the button with the all field provided values.
example : sma(10.2) < ema(3.2)
<button type="button" id="generated1" name="generated1" value="">value will display here</button>
<button type="button" id="removethis" name="removethis">removethis</button>
</div>
</body>
</html>
As you can see here,
I'm just expecting the solution like all the dropdown and text field value should display on a button and generate the button so i can do the same strategies on another button upto 5 time.
so value should display on each generated button like. sma(10.2) < ema(3.2).
The following code would do the Job !
To perform better validation, I added a class name 'chk' to check all input fields.
This would be used to validate and generate the buttons' data.
Notice that I also added an empty value property to your select boxes, that's required for this code.
var data='';
var btnid=0;
function generateBtn(data){
btnid++;
var btns='<button type="button" id="generated'+btnid+'" name="generated'+btnid+'" value="" data-id="'+btnid+'">'+data+'</button><button type="button" id="removethis" class="removethis" data-id="'+btnid+'">removethis</button>';
$('#container').append(btns);
}
function check_inputs() {
var i=0;
//validation to check for empty inputs
//Same loop used to generate valid Button' Data
data='';
//we reset Data
$('.chk').each(function(){
if( $(this).val() === "" ){
$(this).css({'border-color':'red','border-size':'3px'});
} else{
$(this).css({'border-color':'green','border-size':'3px'});
if($(this).is('input')){
data+='('+$(this).val()+')';
} else {
data+=' '+$(this).val();
}
i++;
}
});
if(i==$('.chk').length){
//We gernerate the button
generateBtn(data);
} else{
return;
}
}
//Dynamically generated buttons are non-Dom, so we base selction on the parent container
//Data-id attribute is used to match targeted buttons
$("#container").on('click','.removethis', function() {
$('button[data-id='+$(this).data('id')+']').remove();
});
$("#generateButton").on('click', function() {
//Because we can remove buttons
//We count generated buttons before generating more than 5
if($("[id^=generated]").length<5){
check_inputs();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<select name="left_indicator" id="left_indicator" class="chk">
<option value="">select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)" class="chk">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator" class="chk">
<option value="">select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator" class="chk">
<option value="">select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)" class="chk">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
</div>
I commented the code, but I suggest you revise your HTML code for the small (Non standard) mistakes. Just to pay attention to What's unique and what's not! I don't know if this is meant to be in <form> or not, repeating name property in buttons for example should be taken care of.
From your question, I'm not sure where to put the buttons, so I assumed to place it at the end of the document. To make it even simple I added a div at the end before the closing of the body.
<div id="displayButtons" style="display:block;">
Then you can add the following code in the script tag to achieve what you are looking for.
var buttonCount = 0;
$('#generateButton').click(function () {
if (buttonCount < 5) {
// Get all values
let left_indicator = $("#left_indicator").val();
let left_PeriodAndOffset = $("#left_PeriodAndOffset").val();
let comparator = $("#comparator").val();
let right_indicator = $("#right_indicator").val();
let right_PeriodAndOffset = $("#right_PeriodAndOffset").val();
// Define Button to display
let buttonText = left_indicator + " (" + left_PeriodAndOffset + ") " + comparator + " " + right_indicator + " (" + right_PeriodAndOffset + ")";
let button = '<button id="' + buttonCount + '">' + buttonText + '</button>';
// Display button inside Div
$("#displayButtons").append(button);
buttonCount++;
} else {
alert("Limit of 5 reached");
}
})
$("#removethis").click(function () {
if (buttonCount > 0) {
$("#displayButtons > button:last-child").remove();
buttonCount--;
}
else {
alert("No more buttons to remove.");
}
})
Another additional thing I would like to mention is ;
$('#left_indicator').on('change', function (event) {
event.preventDefault();
/* Act on the event */
if ($(this).val() == 'sma') {
$("#left_period_guider").text('(period,offset)'); <== I think you need to replace html with text to display what you require..
} else if ($(this).val() == 'ema') {
$("#left_period_guider").text('(close,period,offset)');
}
});
I hope that's what you were looking for...
Complete working Code:
var buttonCount = 0;
$('#generateButton').click(function () {
if (buttonCount < 5) {
// Get all values
let left_indicator = $("#left_indicator").val();
let left_PeriodAndOffset = $("#left_PeriodAndOffset").val();
let comparator = $("#comparator").val();
let right_indicator = $("#right_indicator").val();
let right_PeriodAndOffset = $("#right_PeriodAndOffset").val();
// Define Button to display
let buttonText = left_indicator + " (" + left_PeriodAndOffset + ") " + comparator + " " + right_indicator + " (" + right_PeriodAndOffset + ")";
let button = '<button id="' + buttonCount + '">' + buttonText + '</button>';
// Display button inside Div
$("#displayButtons").append(button);
buttonCount++;
} else {
alert("Limit of 5 reached");
}
})
$("#removethis").click(function () {
if (buttonCount > 0) {
$("#displayButtons > button:last-child").remove();
buttonCount--;
}
else {
alert("No more buttons to remove.");
}
})
$('#left_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#left_period_guider").text('(period,offset)');
}else if ($(this).val()=='ema') {
$("#left_period_guider").text('(close,period,offset)');
}
});
$('#right_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#right_period_guider").text('(period,offset)');
}else if ($(this).val()=='ema') {
$("#right_period_guider").text('(close,period,offset)');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="left_indicator" id="left_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator">
<option>select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
This button should generate by clicking above the button with the all field provided values.
example : sma(10.2) < ema(3.2)
<button type="button" id="generated1" name="generated1" value="">value will display here</button>
<button type="button" id="removethis" name="removethis">removethis</button>
</div>
<div id="displayButtons" style="display:block;">

Textbox value to check multiselect parameter based on values JS

Trying to assign ticks to a checkbox and have options selected if the value matches the values in the textbox. This a multi-select parameter.
E.g. if the textbox contains 1,2 when the page refreshes I want to ensure Cheese and Tomatoes is selected. If the textbox contains 1,5,6 then I want to ensure Cheese, Pepperoni and Onions are selected. If the textbox contains 1,2,3,4,5,6 then I want to ensure all checkboxes are selected.
Trying to write some javascript to do this. I tried to use local storage but can't get it working. See code example: https://www.codeply.com/go/rupzwTzBMY
ASPX:
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
Currently when the page refreshes, even if the textbox has values assigned - the checkboxes clear and nothing is selected.
I am trying to ensure when users select items from the multi-parameter when the page refreshes those values are not gone and still remain on the page.
Javascript functionality that works so far. This puts values in a textbox when you select items from the drop-down. However, when the page refreshes the text box keeps these selected values but the multi-select parameter doesn't:
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
document.getElementById("txt1").value = selectedOptions;
},
});
Firstly, you must reload the select once after populating default values as below
$('#basic').multiselect('refresh')
Secondly, try to use onInitialized method as described here
Finally, You're trying to assign back values from TextBox to Dropdown as below, where you're trying to assign the value as such with a comma 1,2 which actually doesn't exist as a value in dropdown.
External Fiddle
$('#basic').children("option[value=" +
document.getElementById("txt1").value + "]").prop("selected", true);
Split the values as 1 and 2 and then assign and it works.
$(document).ready(function () {
document.getElementById("txt1").value = "1,2,3"
$('#basic').multiselect({
includeSelectAllOption: true,
numberDisplayed: 5,
onInitialized: function(select, container) {
console.log("Init");
selectListValues();
}
});
$("#basic").multiselect('refresh');
});
function selectListValues()
{
var txtValue = document.getElementById("txt1").value;
var selectedValues = txtValue.split(",");
for(var i = 0; i < selectedValues.length; i++)
{
var val = selectedValues[i];
if (val == null || val == "") continue;
$('#basic').children("option[value=" + val + "]").prop("selected", "selected");
}
}
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
</head>
<body>
<input type="text" runat="server" id="txt1" visible="true" value="" onchange="selectListValues()" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
</body>
</html>
You can get and populate the value using local storage and split the item.
Note
I had to comment out the local storage so the demo code will work as local storage won't work cross domain. You will need to test this locally.
$(function() {
//$("#txt1").val(localStorage.getItem('topping'));
var str = $("#txt1").val().split(",");
$('#basic').val(str);
$('#basic').on('change', function(){
var list = $("#txt1").val($(this).val());
//localStorage.setItem('topping', list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="1,2,4" />
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
you can store input value in local storage, then get inputvalue from local storage then iterate on option set and set selected attribute to true of option if value is present in localstorage.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple>
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
<script>
$(document).ready(function () {
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
console.log(selectedOptions);
setInputAndLocatStorage();
}
});
function onLoad() {
if(!localStorage.getItem('selectedItems')) return false;
var selItems = localStorage.getItem('selectedItems').split(',');
document.getElementById('txt1').value = selItems.join(',');
$('#basic').multiselect('select',selItems);
}
function setInputAndLocatStorage() {
var selItems = $('#basic').val();
var val = selItems == null ? '': selItems.join(',');
document.getElementById('txt1').value = val;
localStorage.setItem('selectedItems', val);
}
onLoad();
});
</script>

Hide all but 1 dif on document ready and unhide divs after "change"

I am creating a business options form (rough description I know, but here goes). I want the first select that pops up to be to choose an Entity Type (IE: Corporation, LLC, LLP, etc). Once one of these is chosen, I want to .show() the next form. Here is what I've tried so far:
HTML FILE
<head>
<link rel="stylesheet" type="text/css" href="hide.css">
<script src="//code.jquery.com/jquery-1.10.2.js">
function getEntityType(sel) {
var openingEntityType = sel.value;
$("#basicOpeningEntityInformation").show();
}
</script>
</head>
<body>
<select id="oet" onchange="getEntityType(this)">
<option value="">Select an Option</option>
<option value="inc">Corporation</option>
<option value="llc">Limited Liability Company</option>
<option value="llp">Limited Liability Partnership</option>
<option value="lp">Limited Partnership</option>
<option value="gp">General Partnership</option>
<option value="jv">Joint Venture</option>
<option value="dba">Sole Proprietorship</option>
</select>
<br/>
<br/>
<form id="basicOpeningEntityInformation">
Entity Name:
<input type="text" id="openingEntityName">
<br/>
</form>
</body>
CSS FILE:
#basicOpeningEntityInformation {
display: none;
}
When the page loads, #basicOpeningEntityInformation is hidden. I want it to be unhide when a select from above is chosen. I tested my console and the select is passing it's value to var openingEntityType as it should; however, it is not making the other form visible. I tired with both .basicOpeningEntityInformation and #basicOpeningEntityInformation and neither seem to work (both in the CSS and the Script.
Thank you!
You need to check if the selected value is one of the required values:
$('#oet').on('change', function() {
var selectedItem = $(this).val();
if (selectedItem == 'inc' || selectedItem == 'llc' || selectedItem == 'llp') {
$('#basicOpeningEntityInformation').show();
} else {
$('#basicOpeningEntityInformation').hide();
}
});
Demo: https://jsfiddle.net/tusharj/L4b0wpts/1/
Try adding this..it will work
<head>
<link rel="stylesheet" type="text/css" href="hide.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"> </script>
<script>
function getEntityType(sel) {
var openingEntityType = sel.value;
jQuery("#basicOpeningEntityInformation").show();
}
</script>
</head>
you are using $(".basicOpeningEntityInformation").show();
so change the
id="basicOpeningEntityInformation" to class="basicOpeningEntityInformation"
OR
$(".basicOpeningEntityInformation").show(); to $("#basicOpeningEntityInformation").show();

Syncing 2 multiple choice lists in javascript

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/

Jquery selectmenu plugin with text input option

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.

Categories

Resources