How to change content of a span based on Drop down selection - javascript

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;
}

Related

Dynamically append multiple options selected into one select jquery

I'm trying to add the options selected from one select element into another. I'm guessing it'll be something like this.
var selected = $("#selectWithOptions").append("<option'>" +
options[selectedIndex].value + "</option>");
This does not work.
The logic is pretty straight-forward and you can follow the inline comments in the JS function:
// Fire this function when a dropdown item is selected
$('#dd1').change(function() {
// Grab the text of the selected item
var selectedOption = $('#dd1 :selected').text();
// If it is not already in the second dropdown list, then append it
if( $('#dd2 option').filter(function () { return $(this).text() == selectedOption; }).length <= 0 ) {
$('#dd2').append('<option>'+selectedOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Dropdown 1:
<select id="dd1">
<option selected disabled>Select option</option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>xiyar</option>
</select>
</div>
<div>Dropdown 2:
<select id="dd2">
</select>
</div>
In Javascript(and jQuery), everything is an object. Get the selected option elements using the jquery :selected selector and then append them to the second select element.
I'm using clone() but if you don't want to copy, rather you want to move the elements from one select to the other, then get rid of clone() and that same object will be moved to the other select element.
$('button').on('click',function(e){
var opt = $('#first option:selected').clone();
$('#second').append(opt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="hello">Hello</option>
<option value="world">World</option>
</select>
<select id="second">
</select>
<button>
Copy
</button>

Remove the first select option

I'd like to remove the first option of an select tag when I click on the select tag. Is this possible?
I don't want to see the first option after that click.
Thanks for any help.
You can remove the first option on click with jQuery.
$(document).on('click', 'select', function() {
$(this).find('option').get(0).remove();
});
This simply removes the first option of a select tag on click. You need to add an if statement to check if it was already removed.
There's also a simple no-javascript solution:
<select>
<option style="display: none">--Choose--</option>
<option>Cheese Cake</option>
<option>Hot Pockets</option>
<option>Sausage</option>
<option>Cookies</option>
<option>Bacon</option>
</select>
(Copied from the comments from #chipChocolate.py)
If you use bootstrap add placeholder attribute in your select.
If your not
<select required>
<option value="" disabled selected>Select your option</option>
<option value="1">1</option>
</select>
// to remove first...
document.getElementById("element_id_str").options[0].remove();
//to remove the lot...
document.getElementById("element_id_str").options.length = 0;
<select required>
<option value="" disabled selected hidden>Select your option</option>
<option value="1">1</option>
</select>
Probably you just want this:
<select required>
<option value="" hidden>Select your option</option>
<option value="1">1</option>
</select>
A very naive way of doing this:
$("#selector").change(function(evt) { //listen to changes of selection
var theElement = $(this);
if (!theElement.data("selected")) { //check if flag is not set
theElement.children("option")[0].remove(); //remove 1st child
theElement.data("selected", true); //set flag, so it doesn't continue removing items for every change
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option>--Choose--</option>
<option>Apple</option>
<option>Banana</option>
<option>Papaya</option>
</select>
If you want to remove the first option use this
$(document).ready(function()
{
$("select").children().first().remove();
});
If you want to remove the first option after clicking on the select box use this
$(document).ready(function()
{
var removed=false;
$(document).on("click","select",function()
{
if(!removed)
{
$(this).children().first().remove();
removed=true;
}
});
});
Javascript:
document.getElementById("SelectId")[0].remove();
Get the first option in the select and remove it.
I had the same problem, but the solutions above just work with one form, not with many. I added some extra code in order to validate it for many in your form:
$(document).ready(function()
{
$(document).on("change","select",function()
{
var x = $(this).children().first().attr("name");
var n = x.localeCompare("todelete");
if (n == 0)
$(this).children().first().remove();
});
});
Where "todelete" is the name for all first elements [0] defined inside the
Please select value //all first elem must have the same name
"> //the others another name (can be the same BUT not "todelete")
You need the id or class to remove the item. While testing and debugging I found 'option:first' fails to remove the item. But 'option:first-of-type' always does the work. You can get more info about 'first-of-type' here :first-of-type
$("#ID_or_.CLASS option:first-of-type").remove();

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/

How to select dropdown list using jQuery

I have the dropdown below. I want to populate orange in the dropdown when the page loads. I made a function, PopulateDropDown, which runs the jQuery code to do so, but it is not working.
<select name="cboFruits" id="cboFruits">
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Pine">Pine</option>
</select>
<script type="text/javascript" src ="jquery.js"></script>
<script>
function PopulateDropDown(pFruitName)
{
$('cboFruits :selected').val(pFruitName);
}
$(document).ready(function(){
PopulateDropDown('Orange');
});
</script>
Well, there are a few problems with your code:
$('cboFruits :selected').val(pFruitName);
First of all, you're missing the # in front of cboFruits, since cboFruits is the ID property of your select list.
Also the correct way of setting the selected option would be something like this:
function PopulateDropDown(pFruitName)
{
$('#cboFruits option:contains("'+pFruitName+'")').prop('selected', true);
}
$(document).ready(function(){
PopulateDropDown('Orange');
});​
Ref this question How do you select a particular option in a SELECT element in jQuery?
You forgot to write ** # ** and remove selected
$('#cboFruits').val(pFruitName);
EDIT :
or you use
<option value="Orange" selected="true">Orange</option>
when page by default 'Orange' will be selected
It should work:
function PopulateDropDown(pFruitName)
{
$('#cboFruits').val(pFruitName);
}

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