I want just to get only country code with plus in html input, this intl-tel-input now working, that showing specific country code number example. I don`t want this , what i need is just to show automatically iti__dial-code (country code) .
How can i solve this issue ?
var input = document.querySelector("#phone");
intlTelInput(input, {
customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
return "(201) 555-0123" ;
},
});
window.intlTelInput(input, {
initialCountry:"auto",
geoIpLookup: function(success, failure){
$.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
var countryCode = ('+' && resp && resp.country) ? resp.country : "";
success(countryCode);
});
},
dropdownContainer: document.body,
utilsScript: "Project A_files/utils.js",
});
You need to get instance of input and then get it's country data.
var iti = window.intlTelInputGlobals.getInstance(input);
var countryData = iti.getSelectedCountryData();
Country data will return something like:
{
name: "Afghanistan (افغانستان)",
iso2: "af",
dialCode: "93"
}
Get the dialcode by:
var dialCode = countryData["dialCode"];
Refered from the official documentation of the library at https://github.com/jackocnr/intl-tel-input
Related
I am very new to web development and I've been searching around for a while now and I can't seem to find a solution to this. I am using razor pages in asp.net core 2.0 and I want to fill a drop down box based on another drop down box's selection. I set up the below javascript to hit a procedure in my razor page when the value of the first drop down box changes. When I run the code though, I can't get it to work. I think it is due to my return value but I can't seem to get that to be a json value as it keeps throwing an error at me when I try to. The error is that "JSON is not valid in this context". Can anyone suggest to me how to return JSON from razor pages to a javascript call?
Any help would be appreciated!
#section Scripts {
<script type="text/javascript">
$('#Department').change(function () {
var selectedDepartment = $("#Department").val();
var cardSelect = $('#Card');
cardSelect.empty();
if (selectedDepartment != null && selectedDepartment != '') {
$.getJSON('#Url.Action("GetCardsByDivisionAndStatus")', { divisionID: selectedDepartment }, function (cards) {
if (cards != null && !jQuery.isEmptyObject(cards)) {
cardSelect.append($('<option/>', {
Card_ID: null,
Card_Number: ""
}))
$.each(cards, function (index, card) {
cardSelect.append($('<option/>', {
Card_ID: card.Card_ID,
Card_Number: card.Card_Number
}));
});
};
});
}
});
</script>
}
And here is my C# code (I tried used JsonResult but that's not working either):
// If the user selects a division then make sure to get the cards for that division only
[HttpGet]
public ActionResult GetCardsByDivisionAndStatus(string divisionID)
{
int checkinStatus;
int intdivisionID;
if (divisionID != "0" && divisionID != null)
{
// Retrieve a status of checked in so that only cards with a checked in status can
// be checked out.
checkinStatus = linqQuery.GetCardStatusByStatusDesc("Checked In", _Context);
intdivisionID = Convert.ToInt32(divisionID);
// Retrieve list of cards that have the checkin status ID
CardList = linqQuery.GetCardListByStatusIDandDeptID(checkinStatus, intdivisionID, _Context);
// Create the drop down list to be used on the screen.
carddropdown = new List<CardDropDown>();
carddropdown = loaddropdowns.ReturnDropDownList(CardList);
return new JsonResult(CardList);
}
return null;
}
EDIT----------------------------------------------------------------------
So I changed the code as below and now I'm getting a parse error "JSON.parse: unexpected character at line 1 column 1 of the JSON data" I can't figure out what is going on as I can't see what the data is coming back that it can't parse. Is my code below not converting to JSON and if not, what am I missing?
#section Scripts {
<script type="text/javascript">
$('#Department').change(function () {
var selectedDepartment = $("#Department").val();
var cardSelect = $('#Card');
cardSelect.empty();
if (selectedDepartment != null && selectedDepartment != '') {
$.getJSON('#Url.Action("/CheckOutCard?handler=CardsByDivisionAndStatus")', { divisionID: selectedDepartment }, function (cards) {
if (cards != null && !jQuery.isEmptyObject(cards)) {
cardSelect.append($('<option/>', {
Card_ID: null,
Card_Number: ""
}))
$.each(cards, function (index, card) {
cardSelect.append($('<option/>', {
Card_ID: card.Card_ID,
Card_Number: card.Card_Number
}));
});
};
});
}
});
</script>
And here is my C# code for the procedure that I updated:
// If the user selects a division then make sure to get the cards for that division only
[HttpGet]
public JsonResult OnGetCardsByDivisionAndStatus(string divisionID)
{
int checkinStatus;
int intdivisionID;
if (divisionID != "0" && divisionID != null)
{
// Retrieve a status of checked in so that only cards with a checked in status can
// be checked out.
checkinStatus = linqQuery.GetCardStatusByStatusDesc("Checked In", _Context);
intdivisionID = Convert.ToInt32(divisionID);
// Retrieve list of cards that have the checkin status ID
CardList = linqQuery.GetCardListByStatusIDandDeptID(checkinStatus, intdivisionID, _Context);
// Create the drop down list to be used on the screen.
carddropdown = new List<CardDropDown>();
carddropdown = loaddropdowns.ReturnDropDownList(CardList);
var converted = JsonConvert.SerializeObject(carddropdown);
return new JsonResult(converted);
}
return null;
}
Rename your method to OnGetCardsByDivisionAndStatus (note "OnGet" prefix) and in jquery code change the url to
$.getJSON('/{PageRoute}?handler=CardsByDivisionAndStatus'
e.g.
$.getJSON('/About?handler=CardsByDivisionAndStatus'
Notice the handler querystring parameter name will be your method name without OnGet prefix.
So I figured out what the problem was. Apparently I did not need to have the #URL.Action in my code. It was causing me to not hit my C# code which in return caused a null response back to my call. I have modified my javascript code to be as below to show what I am talking about. Thanks Mohsin for trying to help me out.
#section Scripts {
<script type="text/javascript">
$('#Department').change(function ()
{
var selectedDepartment = $("#Department").val();
var cardSelect = $('#Card');
cardSelect.empty();
if (selectedDepartment != null && selectedDepartment != '')
{
$.getJSON("/CheckOutCard?handler=CardsByDivisionAndStatus", { divisionID: selectedDepartment }, function (cards)
{
$.each(cards, function (index, card)
{
cardSelect.append($('<option/>',
{
value: card.card_ID,
text: card.card_Number
}));
});
});
}
});
</script> }
How could I create a search form that will search for the entered term inside a JSON file?
So if the search term is equal to a title inside the location object, it should return that object info. If there is no match, give the user feedback that there are no items found
I created a search input:
<form action="" method="get">
<input id="search" type="text" placeholder="Search term">
<input type="submit" class="button">
</form>
My JSON looks like this:
{
"title": "Locations",
"locations": [
{
"title": "New York",
"url": "api/newyork.js"
},{
"title": "Dubai",
"url": "api/dubai.js"
},{
"title": "Netherlands",
"url": "api/netherlands.js"
},{
"title": "Lanzarote",
"url": "api/lanzarote.js"
},{
"title": "Italy",
"url": "api/italy.js"
}
]
}
Update:
I came up with the following, using jQuery:
$("#search").change(function() {
var arrival = $(this).val();
$.getJSON( "api/videoData.js")
.done(function(data) {
// update your ui here
console.dir(data.pages);
var dataArr = data.pages;
// Iterate over each element in the array
for (var i = 0; i < dataArr.length; i++){
// look for the entry with a matching `code` value
if (dataArr[i].title == arrival){
// we found it
console.log(dataArr[i].title);
} else {
console.log('Houston, we have a problem');
}
}
}).fail(function(data) {
// handle error here
console.log('no results found');
});
});
This is working, only it should be entered exactly as stored in the JSON.
So when you search for "Italy" and you use lowercase type, it will not find the object. Also it will not give any entries when you search for example: ne. I would like to get Netherlands and New York as search results.
Here is a snippet that demonstrates how the lookup could be done. It only loads the JSON once. I have included the test data for when the JSON request fails, which it will in this demo. At every change of the input value a short list of matches is shown in a div below the input. The submit button is not included, as the search is immediate.
Try it.
// testData is defined for demo only. Can be removed
var testData = [
{
"title": "New York",
"url": "api/newyork.js"
},{
"title": "Dubai",
"url": "api/dubai.js"
},{
"title": "Netherlands",
"url": "api/netherlands.js"
},{
"title": "Lanzarote",
"url": "api/lanzarote.js"
},{
"title": "Italy",
"url": "api/italy.js"
}
];
// Variable to hold the locations
var dataArr = {};
// Load the locations once, on page-load.
$(function() {
$.getJSON( "api/videoData.js").done(function(data) {
window.dataArr = data.pages;
}).fail(function(data) {
console.log('no results found');
window.dataArr = testData; // remove this line in non-demo mode
});
});
// Respond to any input change, and show first few matches
$("#search").on('keypress keyup change input', function() {
var arrival = $(this).val().toLowerCase();
$('#matches').text(!arrival.length ? '' :
dataArr.filter(function(place) {
// look for the entry with a matching `code` value
return (place.title.toLowerCase().indexOf(arrival) !== -1);
}).map(function(place) {
// get titles of matches
return place.title;
}).join('\n')); // create one text with a line per matched title
});
// submit button is not needed really
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text" placeholder="Search term">
<div id="matches" style="height:70px; overflow-y:hidden; white-space:pre"></div>
The solution has a few steps, let us know which step you can't do:
Call a JS function when the user clicks the button
Read the file from disk on the server into a JS variable in the browser
Use lodash.js to get the url from the JS variable for the search term
Display results to the user
But taking a stab at the simplest answer, the way I'd do it:
Load your JSON file with the page, like any Javascript file.
Load lodash.js.
Call your JSON file towns.js and make it look like this:
var cities =
{
"title": "Locations",
"locations":
[
{
"title": "New York",
"url": "api/newyork.js"
},
{
"title": "Dubai",
"url": "api/dubai.js"
}
]
}
And then your HTML is something like this:
<input type="" class="button" onclick='go()'>
<script src='towns.js' />
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js' />
<script>
function go()
{
var name = document.getElementById('search').value;
var result = _.find(cities.locations, {'title': name});
if (!result)
window.alert('Nothing found');
else
window.alert('Go to ' + result.url);
}
<script>
If you intend your json file as static and not very huge one then you better load it at once on page load event(preventing sending the same requests dozens of times). Try this approach:
var xhr = new XMLHttpRequest(),
locations = {};
xhr.overrideMimeType("application/json");
xhr.open('GET', 'locations.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == "200") {
var content = JSON.parse(this.response),
locations_arr, i, count, title;
locations_arr = content['locations'];
for (i = 0, count = locations_arr.length; i < count; i++) {
title = locations_arr[i]['title'].toLowerCase();
locations[title] = locations_arr[i];
}
console.log(locations);
}
};
xhr.send(null);
Add some identifier to your form element (id="myForm") and 'name' attribute to your input field (name="search");
document.getElementById('myForm').onsubmit = function() {
var search_value = this.search.value.trim().toLowercase();
if (search_value && location[search_value]) {
console.log(location[search_value]);
} else {
alert("Object with specified title not found!");
}
// You must return false to prevent the default form behavior
return false;
}
As you said in your update with this code:
So when you search for "Italy" and you use lowercase type, it will not find the object. Also it will not give any entries when you search for example: ne. I would like to get Netherlands and New York as search results.
$("#search").change(function() {
var arrival = $(this).val();
$.getJSON( "api/videoData.js", { arrivalDate: arrival })
.done(function(data) {
// update your ui here
console.dir(data.pages);
var dataArr = data.pages;
// Iterate over each element in the array
for (var i = 0; i < dataArr.length; i++){
// look for the entry with a matching `code` value
if (dataArr[i].title == arrival){
// we found it
console.log(dataArr[i].title);
} else {
console.log('Houston, we have a problem');
}
}
}).fail(function(data) {
// handle error here
console.log('no results found');
});
});
Replace this line:
if (dataArr[i].title == arrival){
for
if (dataArr[i].title.toLowerCase().contains(arrival.toLowerCase())){
And now it will match all the string that contains the string that you are searching...
In this piece of code:
var disable = { inputLabelBox : false, nodeIpInput: false, checkBox: false};
var checkDeviceNameExists = function(devices, form) {
return devices.some(function(element) {
nameExists = deviceNameMap(form, element);
if (nameExists) {
form.address.$setViewValue(nameExists);
form.address.$render();
if (!disable.checkBox || !disable.nodeIpInput) {
disable.checkBox = true;
disable.nodeIpInput = true;
checkBox.checked = false;
}
console.log(disable.checkBox);
return true;
} else {
return false;
}
});
}
Everything works out as it should, but I can't get the expect(disable.checkBox).toBe(true); to work. I get Expected false to be true instead. I have verified the console.log(disable.checkBox); is true. Any suggestions?
beforeEach(function() {
form = {};
form.label = {};
form.address = jasmine.createSpyObj("address", ["$setValidity", "$setViewValue", "$render"]);
form.$setValidity = jasmine.createSpy("$setValidity");
disable = { inputLabelBox : false, nodeIpInput: false, checkBox: false};
});
it("It should populate ip address because Vip label pre-exists", function() {
form.label.$viewValue = "myvip";
FormDeviceExistSvc.checkDeviceExists(form, "checkForVips");
expect(VipSvc.getVips).toHaveBeenCalled();
expect(form.address.$setViewValue).toHaveBeenCalledWith("10.11.11.1");
expect(disable.checkBox).toBe(true);
});
it("It should populate ip address because Vip label pre-exists", function() {
form.label.$viewValue = "myvip";
FormDeviceExistSvc.checkDeviceExists(form, "checkForVips");
expect(VipSvc.getVips).toHaveBeenCalled();
expect(form.address.$setViewValue).toHaveBeenCalledWith("10.11.11.1");
expect(FormDeviceExistSvc.disable.checkBox).toBe(true);
expect(FormDeviceExistSvc.disable.nodeIpInput).toBe(true);
expect(FormDeviceExistSvc.checkBox.checked).toBe(false);
});
I needed to use full service name FormDeviceExistSvc to access the value FormDeviceExistSvc.disable.checkBox.
Also, note: In testing, you only want to test what is public, not private. So... anything from the service that is return {} can be tested.
I use bootstrap multi-select and I want to update options on flow with ajax
To populate on init my multiselect I do
<select name="model" class="multiselect" multiple="multiple">
<? foreach ($sel_models as $mod) { ?>
<option value="<?= $mod ?>" <?= ($mod == $params['model']) ? 'selected' : '' ?>><?= $mod ?></option>
<? } ?>
</select>
then on event I would like to update my option list with the following ajax
I was trying to use the rebuild method but won't fire the drop-down after creation
$.ajax({
type: 'post',
url: "helper/ajax_search.php",
data: {models: decodeURIComponent(brands)},
dataType: 'json',
success: function(data) {
$('select.multiselect').empty();
$('select.multiselect').append(
$('<option></option>')
.text('alle')
.val('alle')
);
$.each(data, function(index, html) {
$('select.multiselect').append(
$('<option></option>')
.text(html.name)
.val(html.name)
);
});
$('.multiselect').multiselect('rebuild')
},
error: function(error) {
console.log("Error:");
console.log(error);
}
});
With firebug I can see that the list is generated but on select won't show up
In the doc I can read :
.multiselect('setOptions', options)
Used to change configuration after initializing the multiselect. This may be useful in combination with .multiselect('rebuild').
Maybe you can't change your widget data by your initial way. In a correct way you should use setOptions method.
Else : With your way, maybe should you think about destroy your widget .multiselect('destroy') and create it again after.
Update after comment :
In the doc : ( you've linked )
Provides data for building the select's options the following way:
var data = [
{label: "ACNP", value: "ACNP"},
{label: "test", value: "test"}
];
$("#multiselect").multiselect('dataprovider', data);
So :
When you get data from your ajax call, you have to create an array of objects ( it's the options in the select you want to have ) with the format like
var data =
[
{label: 'option1Label', value: 'option1Value'},
{label: 'option2Label', value: 'option2Value'},
...
]
When your objects array is created, then you just have to call the method
$("#multiselect").multiselect('dataprovider', data);
Where data is your array of objects.
I hope I'm clear :/
As an alternative to multiselect('dataprovider', data) you can build the list with jquery append exactly the way you did in your question. The only change you need to make is to delay the rebuild until after the ajax request is complete.
var buildDrivers = $.getJSON('resources/orders/drivers.json', function(data) {
$.each(data, function(i, driver) {
$('#toolbar select[name="drivers"]').append('<option>'+driver+'</option>');
});
});
buildDrivers.complete(function() {
$('.multiselect').multiselect('rebuild');
});
see http://api.jquery.com/jquery.getjson/ for documentation
I've been added the functionality of updating options after filtering and getting them from the server side. This solution relays on the concept of injecting new options, destroying the select and initializing it again.
I took into account:
Considering the existing selected options, which must stay.
Removing duplicate options (might be as a conflict from which that already selected and the new that came from the server).
Keeping the options tray open after the update.
Reassign the previous text in the search text box & focusing it.
Just add the 'updateOptions' as a function after the 'refresh' function along with the two helper functions as follows:
updateOptions: function (options) {
var select = this.$select;
options += this.getSelectedOptionsString();
var selectedIds = select.val(),
btnGroup = select.next('.btn-group'),
searchInput = btnGroup.find('.multiselect-search'),
inputVal = searchInput.val();
options = this.removeOptionsDuplications(options);
if (!options) {
options = '<option disabled></option>';
}
// 1) Replacing the options with new & already selected options
select.html(options);
// 2) Destroyng the select
select.multiselect('destroy');
// 3) Reselecting the previously selected values
if (selectedIds) {
select.val(selectedIds);
}
// 4) Initialize the select again after destroying it
select.multiselect(this.options);
btnGroup = select.next('.btn-group');
searchInput = btnGroup.find('.multiselect-search');
// 5) Keep the tray options open
btnGroup.addClass('open');
// 6) Setting the search input again & focusing it
searchInput.val(inputVal);
searchInput.focus();
},
getSelectedOptionsString: function () { // Helper
var result = '',
select = this.$select,
options = select.find('option:selected');
if (options && options.length) {
$.each(options, function (index, value) {
if (value) {
result += value.outerHTML;
}
});
}
return result;
},
removeOptionsDuplications: function (options) { // Helper
var result = '',
ids = new Object();
if (options && options.length) {
options = $(options);
$.each(options, function (index, value) {
var option = $(value),
optionId = option.attr('value');
if (optionId) {
if (!ids[optionId]) {
result += option[0].outerHTML;
ids[optionId] = true;
}
}
});
}
return result;
},
Demo:
State:
"Option 1"
$('#select').multiselect('updateOptions', '<option value="2">Option 2</option>');
State:
"Option 2"
"Option 1"
I think this is an easier way to add options on the fly (using ajax or any other listener) to an existing Bootstrap MultiSelect.
Following is a simplified example to add options:
function addOptionToMultiSelect(multiselectSelector, value, selected) {
var data = [];
$(multiselectSelector + ' option').each(function(){
var value = $(this)[0].value;
var selected = $(this)[0].selected;
data.push({label: value, value: value, selected: selected});
});
// Add the new item
data.push({label: value, value: value, selected: selected});
$(multiselectSelector).multiselect('dataprovider', data);
}
For simplicity, I have assumed both the label and value are the same in an option. Note that the already selected options are taken care of by reading the selected attribute from the existing options. You can make it more sophisticated by tracking the disabled and other attributes.
Sample:
addOptionToMultiSelect('#multiselect-example', 'new-option', true);
Hi I'm nearly finished with my small task of populating select dropdowns then outputting a relevant number. The select a company etc works.
Here's my JSFiddle: http://jsfiddle.net/3MK3D/1/
I need to now generate the appropriate companies in the select dropdown dependent on which sector is selected. I've created a new javascript array for personal companies.
I've thought of maybe doing something like this and passing the correct variable to the appropriate function but not really sure how to implement it:
var companiesArray;
$('#sector').on('change', function(e){
var optionSelected = $("option:selected", this);
var sectorSelected = this.value;
if( sectorSelected == 'business' ) {
companiesArray = 'insurancecompanies';
} else if( sectorSelected == 'personal' ) {
companiesArray = 'personalcompanies';
} else {
}
});
There is probably a better way?
Use a companies object that has your sector select values as keys to the relevant arrays:
var companies = {
business : [
{
name : 'Advent',
property : '01242 674 674',
fleet : '',
motortrade : ''
},
{
name : 'Allianz',
property : '0844 412 9988',
fleet : '0800 587 5858',
motortrade : ''
},
// other insurance companies
],
personal : [
// personal companies
]
}
Then:
$('#sector').on('change', function(e){
var optionSelected = $("option:selected", this);
var sectorSelected = this.value;
var companyArray = companies[sectorSelected];
// iterate over companyArray and create the relevant option objects for #company
});