Country / State Javascript - 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/

Related

Stop dropdown from redirecting to homepage

sI am using the following code to remove text starting from the "+" character from dropdown menu choices:
$("select").each(function(){
var $wrapper=$(this);
var $options=$wrapper.find("option");
$(this).empty();
$options.each(function(index){
$wrapper.append(new Option($(this).text().split("+")[0]))
})
})
So if a menu original choices would be:
Audi
BMW
Mercedes + Trailer
The dropdown only shows:
Audi
BMW
Mercedes
THE PROBLEM:
I also have dropdowns that need to refresh the page when a choice is made. When not using the above code this works fine, but when adding the code above the webpage redirects to the homepage instead. How I can ensure that when the user makes a dropdown choice the user stays on the same page?
Following the jquery spirit "write less, do more" you could also do the text replacement operation like this:
$("select.cars option").each(function(){
with ($(this)) {
text(text().split("+")[0].trim());
val(val().split("+")[0].trim());
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="cars">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes + Trailer">Mercedes + Trailer</option>
</select>
To limit the effect of the script on the selects you want to change and protect all the others I also added the class "cars" into the picture. Maybe something along those lines can be helpful for your project?
But this will not touch your current problem, that you leave the current page as soon as a select option has been selected. I suspect there must be another piece of (as yet unpublished) script that is responsible for that behaviour.
You just need to add value to newly created option.
Try this:
$("select").each(function(){
var $wrapper=$(this);
var $options=$wrapper.find("option");
$(this).empty();
$options.each(function(index){
var text = $(this).text().split("+")[0].trim();
var newOption = new Option(text);
// get value from previous option
newOption.value= $(this).val();
$wrapper.append(newOption)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes + Trailer">Mercedes + Trailer</option>
</select>
So this works!
$("select option").each(function(){
with ($(this)) text(text().split("+")[0].trim());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="cars">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes + Trailer">Mercedes + Trailer</option>
</select>

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/

Create drop down on the fly

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

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

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

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