Create drop down on the fly - javascript

I have looked all over for an answer to this, but cant seem to find a definitive answer.
I want to be able to display a dropdown, populated from MySQL with PHP and have next to it a '+' or something that will, when clicked on, create another dropdown with the same data as the first.
In this way, the user can add as many dropdowns as they want. There will be around 25 items in each dropdown. I'm open to JS,JQuery etc. - just need to get it done!
I'd appreciate any and all help.
Rob
Edit
Had a night sleep - so let's try again!
Based on #adeno code I cam up with this:
?>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form action = 'testselectprocess.php' method='POST'>
<div>
<select id='test' name='test0'>
<option name='first' value = '1'>option 1</option>
<option name='second' value = '2'>option 2</option>
<option name='third' value = '3'> option 3</option>
</select>
<select id='counting' name='count0'>
<option name='first' value = '1'>1</option>
<option name='second' value = '2'>2</option>
<option name='third' value = '3'>3</option>
</select>
</div>
<button type='button' class="more">Add another...</button>
<script>
var c=0;
$('.more').on('click', function() {
//alert(c);
$(this).before( $(this).prev().clone());
$('#test').attr('name', 'test'+ c)
$('#counting').attr('name', 'count'+ c)
c++;
});
</script>
<input type="submit" value="Add this." name="what">
</form>
</body>
</html>
Trouble is - after the first 'Add another...' press, the id numbers don't increment. Looking at it with IEs DOM explorer the id increments once only. Wish I knew how to cut and paste in the DOM explorer but I only seem to be able to copy one element.

Depends on the markup, but in principle it's pretty straight forward, you create a button that when clicked clones the select and inserts the clone
$('.more').on('click', function() {
$(this).before( $(this).prev().clone() )
});
FIDDLE

Related

How to select id and class in select options at same time

I have implemented jquery chosen in my blog The problem is i have changed the code <select id="cmbColumn" name="cmbColumn"> to
<select class="chosen-select" name="chosen-select">
I have assign the class because to achieve like below
<script>
$(function(){
$(".chosen-select").chosen();
});
</script>
But the problem is the value is not filtering because the class is not taking by ID document.getElementById("chosen-select").value;
<script type="text/javascript">
function getValue() {
var valchosen-select = document.getElementById("chosen-select").value;
var valcmbSidebar = document.getElementById("cmbSidebar").value;
valOutput = "label:"+valchosen-select+"|label:"+ valcmbSidebar;
window.open("/search/?q=" + valOutput, "_self");
}
</script>
Can i give id and class to the same select option like the below <select class="chosen-select" id="chosen-select" name="chosen-select"> Does it works or any other solution.
You can have the same class name as an ID, but I wouldn't recommend it - an ID has to be unique in your code, and a class name doesn't have to be.
If you removed the id attribute, you can't use getElementById and query the DOM for it.
Instead, use getElementsByClassName - notice this returns a collection, so assuming you only have one element with this class name, you will need to use getElementsByClassName("chosen-select")[0].value.
.chosen() is not a standard jQuery method, it's from a plugin.
There's 2 <script> tags for the plugin. One of them doesn't work, see fig1..
<option> tags should be closed, see fig2..
As Mr. Gel Boy has already stated: avoid hyphenating variables. The hyphen - will be confused for a minus -.
As Mr.(Ms.?) charlietfl has already stated: id is not needed when using the Chosen API, see fig3..
fig1.
<script src="//harvesthq.github.io/chosen/chosen.jquery.js"></script>
<link href="//harvesthq.github.io/chosen/chosen.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script>
Notice the 2 <script> blocks on the top and bottom. The plugin needs jQuery loaded before it can function. Also, in this instance (and in most common instances), you don't need to load 2 of the same script. Remove the top one.
Fig2.
WRONG: <option value="apple"/>Apple
CORRECT: <option value="apple">Apple</option>
Fig3.
$('.chosen-select').chosen();
This is correct, BUT in your circumstances it would be better if you use camelCase like so:
$('.chosenSelect').chosen();
The following Snippet shows a single and a multiple select using the chosen plugin. I'm assuming your problem is that you are not aware or do not know how to use the plugin, or it's because of the hyphenated variable, so in short:
Set the class of your selects to an arbitrary name without any -, and invoke the plugin targeting that class name. Keep your variables simple without -. The plugin will handle the events and will allow you to do other things that would take a lot of work and coding to do.
SNIPPET
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Chosen Plugin</title>
<link href="https://harvesthq.github.io/chosen/chosen.css" rel="stylesheet">
<style>
fieldset {
max-width: 300px;
font-family: 'Verdana';
}
fieldset * {
font-family: inherit;
}
</style>
</head>
<body>
<fieldset>
<legend>Chosen Plugin</legend>
<b><label for="sel1">Single Select</label></b>
<select id="sel1" class="chosenSelect" name="sel1" data-placeholder="Columns">
<option value=""></option>
<option value="apple+">Apple</option>
<option value="berries+">Berries</option>
</select>
<br/>
<br/>
<b><label for="sel2">Multiple Select</label></b>
<select id="sel2" class="chosenSelect" name="sel2" data-placeholder="Sidebars" multiple>
<option value=""></option>
<option value="grapes+">Grapes</option>
<option value="mango+">Mango</option>
<option value="pear+">Pear</option>
<option value="cherries+">Cherries</option>
</select>
<input onclick="getValue()" value="Filter" type="button">
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<script>
function getValue() {
var valchosenSelect = document.getElementById("sel1").value;
var valcmbSidebar = document.getElementById("sel2").value;
valOutput = "label:" + valchosenSelect + "|label:" + valcmbSidebar;
window.open("https://blogupdatesmyme.blogspot.in/search/?q=" + valOutput, "_self");
}
$(function() {
$(".chosenSelect").chosen({
width: "95%"
});
});
</script>
</body>
</html

How to show the count selected values in the label of select box(i.e Select Option)

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/

Form select not saving in localStorage

I'm working on an HTML view for iAd Producer. I'm trying to add a list of sentences which have alternative words students can choose and to save those values to localStorage as they change and repopulate the selects with those values when the page is revisited.
I'm adapting some code I wrote which works fine to save multiple input boxes on a page. But I have strange behaviour when trying to use it with multiple selects. Basically, no matter which order the answers are completed in, only the last chosen value is being stored. When the page is revisited, the code attempts to put that value in each select. This, of course, fails for the two selects which do not have corresponding values.
I cannot see why this is happening and hope someone can spot the obvious. Thanks.
<div>
<script type="text/javascript">
var uniqueId = "FC2-U2-A-P29";
$(document).ready(function () {
function onStartup() {
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) {
$(this).val(localStorage[$(this).attr("value")+uniqueId]);
}
});
}
onStartup();
});
$('.drop').change(function () {
localStorage[$(this).attr("value")+uniqueId] = $(this).val();
});
</script>
<form>
<label class="number">1.</label>
<label class="text">Breakfast is the </label>
<select name="select1" class="drop">
<option value="blank">Choose a word</option>
<option value="one1">one</option>
<option value="first1">first</option>
</select>
<label class="text"> meal of the day.</label>
<br>
<label class="number">2.</label>
<label class="text">I always eat </label>
<select name="select2" class="drop">
<option value="blank">Choose a word</option>
<option value="three2">three</option>
<option value="third2">third</option>
</select>
<label class="text"> meals a day.</label>
<br>
<label class="number">3.</label>
<label name="select3" class="text">My football team is in</label>
<select class="drop">
<option value="blank">Choose a word</option>
<option value="two3">two</option>
<option value="second3">second</option>
</select>
<label class="text"> place in the league.</label>
<br>
<button class="clearButton" onclick="clearAnswers()">Clear </button>
<script type="text/javascript">
function clearAnswers() {
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) {
localStorage.removeItem($(this).attr("value")+uniqueId);
$(this).val("blank");
}
location.reload();
});
}
</script>
</form>
</div>
The probable reason for which this code fails in select is because of the following :
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) { //select doesn't have any attribute value.
$(this).val(localStorage[$(this).attr("value")+uniqueId]);
}
});
Select tag doesn't have any value attribute. I think .val() is what you need here. If you look at the code, you are basically iterating on select tag and checking value attribute(which doesn't exist) of select. Try changing it to .val() and then try.
To save and load stuff from localstorage use:
localStorage.setItem(<key>, <value>);
and
localStorage.getItem(<key>);
There are multiple problems with your code.
The first one is that you should use .val() instead of .attr('value').
The second one is that the code to add the values in localStorage is executed before the DOM is created fully, so the selects dont exist yet. To overcome this you need to bind the change event on document.ready ( aka $(function() { }); ).
I've made a pastebin with the modified code: http://jsbin.com/jubijuyatu/2/
Your selector is invalid.
Change $(this).attr("value")+uniqueId with $("option:selected",this ).text()+uniqueId; in all occurrences.

Country / State Javascript

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/

Making HTML5 datalist visible when focus event fires on input

As some might know already styling select element is a nightmare, literally impossible without some javascript trickery. The new datalist in HTML5 could serve the same purpose since the user is presented with a list of options and the value is recorded in an input text field.
The limitation here is the list does not appear until the user start typing something in the text field and even then is only shown possible matches based on their input. The behavior I want is that as soon as there is focus on the field the entire list of options become visible.
So I have this code - view on jsbin
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Input - Datalist</title>
</head>
<body>
<input list="categories">
<datalist id="categories">
<option value="Breakfast">Breakfast</option>
<option value="Brunch">Brunch</option>
<option value="Lunch">Lunch</option>
<option value="Dinner">Dinner</option>
<option value="Desserts">Desserts</option>
</datalist>
</body>
</html>
and I'm trying to get that to show with this Javascript:
var catVal = document.getElementsByTagName("input")[0],
cat = document.getElementById("categories");
catVal.style.fontSize = "1.3em";
catVal.addEventListener("focus", function(event){
cat.style.display = "block";
}, false);
Any help would be appreciated,
Cheers
I use the following code:
<input name="anrede"
list="anrede" value="Herr"
onmouseover="focus();old = value;"
onmousedown = "value = '';"
onmouseup="value = old;"/>
<datalist id="anrede">
<option value="Herr" selected></option>
<option value="Frau"></option>
<option value="Fraulein"></option>
</datalist>
mouseover:
Set focus and memorize old value in a -- g l o b a l -- variable
mousedown:
Delete value and show datalist (built in functionality)
mouseup:
Restore old value
Then select new value.
Find this an acceptable workaround towards a combobox.
I hope you like this solution:
I added a “temp” attribute to the input field for storage and once the mouse hovers over the input filed it will save its current value in temp and then delete the value so as to allow the datalist to open.
On mouseout it will restore the field’s value from the variable temp. This solution works great under Chromium that I tested.
As a bonus you can add a placeholder="Click to see all your options"
<input value="Classic" list="myDatalist" temp="" onmouseover="this.temp=this.value; this.value='';" onmouseout="this.value=this.temp;">
<datalist id="myDatalist" open="open">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
In the "Ulrich Berth" response, when clicking on the input, the value in the input will be reset and it will not be possible to select the text inside. You can use this to avoid the problem:
<input id = "input" name="anrede"
list="anrede" value="Herr"
onmouseover="focus();old = value;"
onmousedown = "inputFocus();"
onmouseup="value = old;"/>
<datalist id="anrede">
<option value="Herr" selected></option>
<option value="Frau"></option>
<option value="Fraulein"></option>
</datalist>
function inputFocus(){
var input = document.getElementById("input");
if(input.value == ""){
value = '';
}else{
old = value = input.value;
}
}
Question is pretty old, but it's top search on google and there are no answers to be found so I'll add it here.
To expand datalist on first click you need to set
dataListElement.style.display = "block";
and immediately hide it in next line, so it does not appear as element in your DOM, but it will only expand it under input element.
dataListElement.style.display = "none";
As of today it's not expanded on first click only in Firefox.
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<meta charset=utf-8 />
<title>Input - Datalist</title>
</head>
<body>
<input list="categories" id="categories2" type="text">
<div id="result"></div>
<datalist id="categories">
<option value="Breakfast">Breakfast</option>
<option value="Brunch">Brunch</option>
<option value="Lunch">Lunch</option>
<option value="Dinner">Dinner</option>
<option value="Desserts">Desserts</option>
</datalist>
</body>
</html>
jQuery:
var result='';
$(document).ready(function(){
$('input[type=text]').focus(function(){
$('#categories option').each(function(){
result=result+" "+$(this).val();
});
$('#result').show().html(result);
$('input[type=text]').unbind('focus');
});
$('input[type=text]').blur(function(){
$('#result').hide();
$('input[type=text]').focus(function(){
$('#result').show();
});
});
});
Working JS bin
http://jsbin.com/urupit/4/watch

Categories

Resources