How to set default countries and show respected states in countries.js? - javascript

I am using Countries.js to populate countries and states to a website. I need to set default a country on load and show respective states in select state input. How can it be done?
I have tried Couple of things from the internet.
1.
<script>populateCountries("us", "state");</script>;
2.
In Core file -->
if (stateElementId) {
countryElement.onchange = function() {
populateStates(countryElementId, stateElementId);
//populateStates( "us", stateElementId );
};
}
But it is not working.

To set a default country onload, first populate the countries select element with countries using the load document event listener, then get the country select element object by id e.g. countryElement. Using that, set the value to a default country e.g. 'USA', and trigger onchange() on the element to populate the states select box. The below example does this, and then triggers a new country selection after 5 seconds to showcase further the state select box changing.. You selected jQuery tag for this question, but I didn't see any jQuery in your example so I kept it to straight vanilla JS for the example.
$(document).ready(function() {
populateCountries("country", "state");
$countryElement = $('#country');
$stateElement = $('#state');
$countryElement.val('USA').trigger('change');
$stateElement.val('Florida');
setTimeout(function() {
$countryElement.val('American Samoa').trigger('change');
$stateElement.val('Eastern');
}, 5000);
});
/*
document.addEventListener("load",
populateCountries("country", "state")
);
var countryElement = document.getElementById('country');
var stateElement = document.getElementById('state');
// Set default country
countryElement.value = 'USA';
// Triggers state select population..
countryElement.onchange();
// Set state for country selected..
stateElement.value = 'Florida';
// 5 seconds later, select a different country..
setTimeout(function() {
countryElement.value = 'American Samoa';
countryElement.onchange();
stateElement.value = 'Eastern';
}, 5000);
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-toggle-group="location">
<div class="form-group">
<label>Country</label>
<select class="form-control" name="country" id="country" data-toggle="country" data-country=""></select>
</div>
<div class="form-group">
<label>State</label>
<select class="form-control" name="state" id="state" data-toggle="state" data-state=""></select>
</div>
</div>
<script type="text/javascript" src="https://www.cssscript.com/demo/generic-country-state-dropdown-list-countries-js/countries.js"></script>

you can use the Jquery document ready function like below. But you have to include the jquery.
<script type="text/javascript">
$(document).ready(function() {
populateCountries("us", "state");
});
</script>
you can see the more detail here at below link.
http://learn.jquery.com/using-jquery-core/document-ready/

You should be able to get it right by setting its value:
$('select').val('stateElementId')
or by the text inside the <option></option>
$('select option:contains("us")').prop('selected',true);

Related

Bootstrap selectpicker title is not sorted by user' selection order

I am using Bootstrap-select plugin and I created an event to store user's selection by order in an array which works fine.
But the title of the bootstrap select is not updated based on the selection order. The selected options are sorted based on the HTML order.
I checked previous threads here but it was just about getting user's selection order which is fine for me. I need the title of the dropdown select to be updated by selection order as well.
My approach was getting the array which stores the selected options by order and do a join then updated the title and refresh the selectpicker as below, but it's not updating the title.
You can see that I selected Name then Country then City but the tile shows Country, City, Name which is the default order of the HTML. It should be Name, Country, City
Any suggestions please what I am doing wrong in code ? I commented my code in case something is not clear. Thank you.
$(document).ready(function() {
// Initialize the selectpicker
$(".selectpicker").selectpicker();
// Declare the array which will include the selected options by order
var orderSelection = new Array();
// fire the event on every change in the select
$('.selectpicker').on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue) {
// get current selected option
var selected = $("#mySelect")[0].options[clickedIndex].value;
// check if selected exists in array, if yes then remove, if no then add it to the array
if (orderSelection.indexOf(selected) == -1) { orderSelection.push(selected); }
else { orderSelection.splice(orderSelection.indexOf(selected), 1); }
console.log(orderSelection);
// update the title of the select with user's selection order
$('#mySelect').prop('title', orderSelection.join() );
// refresh the selectpicker to see the new title
$('#mySelect').selectpicker('refresh');
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>
<select id="mySelect" class="selectpicker" data-live-search="true" multiple>
<option>Country</option>
<option>City</option>
<option>Street</option>
<option>zip code</option>
<option>email</option>
<option>mobile</option>
<option>Name</option>
<option>Surname</option>
</select>

How to log what's being typed on the select2 input field and eventually updating another input field?

I'm having trouble logging in real time what's being typed on the select2 input field
My goal is to update another input field while the user in typing on the select2 search box
I tried many things but it's not working:
nothing is appearing in my console
$('.mySelect2').on("change",function(e){
console.log("mySelect2 text", e.target.value)
console.log("mySelect2 text $(this).val()", $(this).val())
// #location is my other field that I want to update
$("#location").text(e.target.value);
});
According to the documentation, you need to use different event:
$('#mySelect2').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
Update: the following method allows to capture everything that the user types into the select2 input
// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
var $select2 = $('.js-example-basic-single')
$select2.select2();
$('body').on('input', '.select2-search__field', function() {
console.log(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<select class="js-example-basic-single" name="state">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>

jQuery Mobile: applying method selectmenu on multiple select fields

On my jQuery Mobile page I would like to implement multiple filter select menus. It works totally fine with only one select menu and an id, but not with multiple.
JSFiddle with my problem:
http://jsfiddle.net/asvyY/40/
(By contrast, my fiddle with ONLY ONE select menu and a select menu id works: http://jsfiddle.net/asvyY/41/)
Error message:
Uncaught Error: cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'
My code:
HTML:
<div data-role="page" id="page1">
<div data-role="header">
<h1>My page</h1>
</div>
<div role="main" class="ui-content">
<form>
<select class="filter-menu" data-native-menu="false">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="filter-menu" data-native-menu="false">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="filter-menu" data-native-menu="false">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
</div>
JS:
$(document).on("pagecreate", "#page1", function(){
$(".filter-menu").selectmenu( "refresh", true );
});
$.mobile.document
.on("listviewcreate", "#filter-menu-menu", function (e) {
var input,
listbox = $("#filter-menu-listbox"),
form = listbox.jqmData("filter-form"),
listview = $(e.target);
if (!form) {
input = $("<input data-type='search'></input>");
form = $("<form></form>").append(input);
input.textinput();
$("#filter-menu-listbox")
.prepend(form)
.jqmData("filter-form", form);
}
listview.filterable({
input: input
});
})
// The custom select list may show up as either a popup or a dialog,
// depending how much vertical room there is on the screen. If it shows up
// as a dialog, then the form containing the filter input field must be
// transferred to the dialog so that the user can continue to use it for
// filtering list items.
//
// After the dialog is closed, the form containing the filter input is
// transferred back into the popup.
.on("pagebeforeshow pagehide", "#filter-menu-dialog", function (e) {
var form = $("#filter-menu-listbox").jqmData("filter-form"),
placeInDialog = (e.type === "pagebeforeshow"),
destination = placeInDialog ? $(e.target).find(".ui-content") : $("#filter-menu-listbox");
form.find("input")
// Turn off the "inset" option when the filter input is inside a dialog
// and turn it back on when it is placed back inside the popup, because
// it looks better that way.
.textinput("option", "inset", !placeInDialog)
.end()
.prependTo(destination);
});
Here is my working JSFiddle: http://jsfiddle.net/asvyY/46/
I deleted the following lines, because jqm automatically transforms the select-tag into a select-menu
$(document).on("pagecreate", "#page1", function(){
$(".filter-menu").selectmenu( "refresh", true );
});
The correct syntax for the listviewcreate event is:
$( ".selector" ).on( "listviewcreate", function( event ) {} );
In the listviewcreate event i changed the id's to classes and initiated the listbox
listbox = $("<ul class='.filter-menu-listbox'></ul>");
I hope i could help you and sry for my bad english :)
You are running into problems because with multiple selectmenus you are using class names and no ids.
Give your selectmenus unique ids as well as the common class name. For the listviewcreate you can use the classnames and find other dom elements using closest()/find().etc.
$.mobile.document.on("listviewcreate", ".ui-selectmenu-list", function (e) {
var input,
listbox = $(this).closest(".ui-selectmenu"),
form = listbox.jqmData("filter-form"),
listview = $(this);
if (!form) {
input = $("<input data-type='search'></input>");
form = $("<form></form>").append(input);
input.textinput();
listbox
.prepend(form)
.jqmData("filter-form", form);
}
listview.filterable({
input: input
});
})
In the case of a long list showing as a dialog. I am retrieving the base ID of the selectmenu and then using it to build selectors as needed:
.on("pagebeforeshow pagehide", ".ui-selectmenu.ui-dialog", function (e) {
var id=$(this).prop("id").replace("-dialog","");
var form = $("#" + id + "-listbox").jqmData("filter-form"),
placeInDialog = (e.type === "pagebeforeshow"),
destination = placeInDialog ? $(this).find(".ui-content") : $("#" + id + "-listbox");
form.find("input")
// Turn off the "inset" option when the filter input is inside a dialog
// and turn it back on when it is placed back inside the popup, because
// it looks better that way.
.textinput("option", "inset", !placeInDialog)
.end()
.prependTo(destination);
});
Updated FIDDLE

jQuery - Each loop to select all items by data attribute, but also dependent on select (option) values

I am in the process of building an e-Commerce shop and have hit a small bump in the road for my actual product page. Based on any product options set that would add to the price if selected, I would like to be able to update the price on the page live when these options have been added. I have managed to iterate through every element with a "data-price-effect" attribute attached to them, HOWEVER, when it comes to a select element, I would need to check if the item is selected as an option, each option has their respective price change attribute of course, but the value would only update to the actual select element.
Here is my code upto now:
function updatePrice(){
$('[data-price-effect]').each(function( index ) {
// do something
});
}
Basic HTML set-up to explain further:
<form>
<input type="text" name="foo" onchange="updatePrice();" data-price-effect="10.00" />
<select name="bar" onchange="updatePrice();">
<option selected value="Item1" data-price-effect="5.00">Item 1</option>
<option selected value="Item2" data-price-effect="8.00">Item 2</option>
<option selected value="Item3" data-price-effect="10.00">Item 3</option>
</select>
</form>
I have NO idea how to even logically do this, not even with some huge messy code. Any pointers here from someone more experienced with Javascript?
Instead of having "updatePrice()" on each element, you could have a listener for all form elements for the function:
var EffectElements = $('form input[data-price-effect], form select');
EffectElements.on('change', function() {
var PriceEffect = 0;
EffectElements.each(function() { // Loop through elements
if ($(this).is('select')) { //if this element is a select
$(this).children().each(function() { //Loop through the child elements (options)
if ($(this).is(':selected')) { //if this option is selected
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
} else {
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
});
You could then use the PriceEffect variable to update your price on the website.
Ultimately it's the IS function doing the dirty work you needed ~_o
Working Example

JQuery On Select change assign value to variable and reload script

Is it possible at all to be able to assign the selected value of a select and assign it to the variable of a script and re-run the script?
Here is my current code sample:
<select onchange="reload_script;">
<option value="123">Select 123</option>
<option value="456">Select 456</option>
<select>
<div id="123">
link title
<br/><br/>
Link
</div>
<script language="javascript" type="text/javascript">
var code = '123' // <-- THIS VARIABLE WOULD BE THE VALUE OF THE SELECTED DROPDOWN VALUE
</script>
See: var code = '123' .... That's what's changed when the select box is changed ... then I would need the script to re-run...
Is this possible at all?
If you use jQuery you can always bind change event:
var code = "123";
$("#mySelect").on("change", function() {
code = this.value;
reload_script();
});
Otherwise, in plain JavaScript it may look like this:
var code = "123";
document.getElementById("mySelect").onchange = function() {
code = this.value;
reload_script();
};
Try this
<select onchange="reload_script();">
<option value="123">Select 123</option>
<option value="456">Select 456</option>
<select>
<div id="123">
link title
<br/><br/>
Link
</div>
<script language="javascript" type="text/javascript">
var code = '123' // <-- THIS VARIABLE WOULD BE THE VALUE OF THE SELECTED DROPDOWN VALUE
function script_to_run()
{
//do code here
}
// Call the script one time on page load (only if you need it on page load)
script_to_run();
function reload_script()
{
script_to_run();//run again
}
</script>

Categories

Resources