Iam trying to do autocomplete input box. Datalist rows are from JSON. I want that user sees name of the city (data[i].stationName below) while making his choise, but i would like to get that data[i].stationShortCode as a return attribute instead of name when city is selected.
Is that possible to do that way without that user needs to see that shortcode?
I tried to put those in array, but iam not figured out how that would help me or..
My js below:
$(document).ready(function(){
var url="https://rata.digitraffic.fi/api/v1/metadata/stations";
var stations=[];
var elem;
$.getJSON(url,function(data,status){
if(status=="success"){
$.each(data, function(i, item){
if(data[i].passengerTraffic!=false){
elem=$("<option value="+data[i].stationName+ ">");
elem.appendTo('#stations');
//stations[i]={value: data[i].stationName, data:data[i].stationShortCode};
}
else{
}
})
}
else{
console.log("Something went wrong");
}
})
});
And html:
<div class="stationSearch">
<input type="text" list="stations" id="station" placeholder="Valitse Asema"/>
<datalist id="stations"></datalist>
<button class="pick">Paina</button>
The idea of an array is OK, but it better be an object (or Map) so that you have direct access:
var stations = {};
// ...
$("<option>").attr("value", data[i].stationName).appendTo('#stations');
stations[data[i].stationName] = data[i].stationShortCode;
Now when you have the input value in an event handler (e.g. after button click), then get the short code from the input value like this:
var selectedShortCode = stations[$("#station").val()];
Here is working snippet:
var url="https://rata.digitraffic.fi/api/v1/metadata/stations";
var stations = {};
$.getJSON(url, function(data,status) {
if (status=="success"){
$.each(data, function(i, item){
if(item.passengerTraffic){
$("<option>").attr("value", item.stationName).appendTo('#stations');
stations[item.stationName] = item.stationShortCode;
}
});
}
else{
console.log("Something went wrong");
}
});
// ...
$("#station").on("input", function () {
$("#code").text(stations[$(this).val()]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" list="stations" id="station" placeholder="Valitse Asema"/>
<datalist id="stations">
<option value="shortcode">longcode</option>
</datalist>
Code: <span id="code"></span>
Yes, modify your script where you build the <option> elements as such:
if(data[i].passengerTraffic!=false){
elem=$("<option value=" + data[i].stationShortCode + ">" + data[i].stationName + "</option>");
elem.appendTo('#stations');
}
This will generate <option> elements where the "stationShortCode" is the option value and the "stationName" is the displayed value.
Related
I have some jQuery that uses AJAX and JSON to populate a UL tag with data.
This is the jQuery code:
$('#pSearch').on('click', function()
{
var partnername = $('#pNameSearch').val();
if($.trim(partnername) != '')
{
$.post('api/pNameSearch.php', {partnername: partnername}, function(data)
{
var obj = JSON.parse(data);
$('#pName').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li>' + item.datestamp + ' - ' + item.comment + ' - ' + item.username + '</li>';
}).join('');
$('#pNames').html(htmlToInsert);
});
};
});
The code above populates a UL field called pNames. It fills LI tags with parsed JSON data retrieved from a PHP script.
What I need to do now is clear the pNames field.
I might be looking at this the wrong way, if so, please let me know.
In the search window that prints the data, I have an HTML RESET button.
<input type="reset" class="btn btn-sm btn-default" id="pReset" name="pReset" value="reset" />
Please note the TYPE in the input field, which I have set to 'reset', will clear out the FORM field, but it will not clear out the UL field that populated the data.
Here is the JavaScript I attempted to use to clear out the field:
$('#pReset').on('click', function ()
{
document.getElementById('#pName').val("");
});
I think it's pretty obvious that I'm missing something.
Update
Since you didn't post your code, let's go with this simplified example:
HTML:
<h3><code>pNames</code></h3>
<ul id="pNames">
</ul>
<div>
<button id="get-pnames">Get pNames</button>
<input type="reset" id="pReset" value="Reset pNames" />
<input type="reset" id="pClear" value="Clear pNames" />
</div>
JS
var yourOriginalAjaxCallbackLogic = function (obj) {
var htmlToInsert = obj.map(function (item) {
//console.log(
return '<li>' + item.datestamp + ' - ' + item.comment + ' - ' + item.username + '</li>';
}).join('');
$('#pNames').html(htmlToInsert);
};
$('#get-pnames').on('click', function (e) {
e.preventDefault();
// your additional logic for grabbing
// the pName and what not would go here
// note the last argument to $.post - this allows us to let jQuery
// take care of converting the json response
$.post('api/pNameSearch.php', {partnername: partnername}, function (data) {
yourOriginalAjaxCallbackLogic(data);
}, 'json');
});
// This version just removes the content of the LI items.
$('#pReset').on('click', function (e) {
e.preventDefault();
$('#pNames li').html('');
});
// This version removes all the LI items
$('#pClear').on('click', function (e) {
e.preventDefault();
$('#pNames').empty();
});
You can see a working fiddle here: http://jsfiddle.net/qhrmh3o1/1/
.val is only for form inputs. These are li elements so you would use $('li').html('');
$('#pReset').on('click', function () {
$('#pName li').html('');
});
You may need to modify that selector because I'm not 100% positive what the selector should be for the li items you want to clear (or if you really want to remove them or their ul from the DOM).
So, I placed the UL tag inside of a DIV, called masterdiv.
I updated my javascript as follows:
$('#pReset').on('click', function ()
{
$('#masterdiv ul').text("");
});
This worked on clearing out the UL field called pNames.
I'm building an icon library where the user on the front end (submitting a form) can select an icon. I managed to get everything working as far as the selection process. Now, the final product will have over 400 icons, and i wanted to add a search (ajax, i guess) or autocomplete input where the user can type a couple of letters and it filter's out those icons.
They search will be filtering out some with a class that has the prefix "icon-".
I started on jsFiddle here: http://jsfiddle.net/yQMvh/28/
an example would be something like this :
http://anthonybush.com/projects/jquery_fast_live_filter/demo/
My HTML Markup:
<div class="iconDisplay">Display's selected icon</div>
<span id="selectedIcon" class="selected-icon" style="display:none"></span>
<button id="selectIconButton">Select Icon</button>
<div id="iconSelector" class="icon-list">
<div id="iconSearch">
<label for="icon-search">Search Icon: </label>
<input type="text" name="icon-search" value="">
</div>
<span class="icon-icon1"></span>
<span class="icon-icon2"></span>
<span class="icon-icon3"></span>
<span class="icon-icon4"></span>
<span class="icon-icon5"></span>
<span class="icon-icon6"></span>
<span class="icon-icon7"></span>
<span class="icon-icon8"></span>
</div>
JS (note: this includes the selection jQuery as well):
var iconVal = $(".icon_field").val();
$('#selectedIcon').addClass(iconVal);
$("#selectIconButton").click(function () {
$("#iconSelector").fadeToggle();
});
$("#iconSelector span").click(function () {
selectIcon($(this));
});
function selectIcon(e) {
var selection = e.attr('class');
$(".icon_field").val(selection);
$("#iconSelector").hide();
$('#selectedIcon').removeClass();
$('#selectedIcon').addClass(selection).show();
return;
}
Will this work for you? http://jsfiddle.net/yQMvh/37/
I've modified your input field slightly (added an id)
<input type="text" id="txt-icon-search" name="icon-search" />
and added this bit of code.
/**
* Holds information about search. (document later)
*/
var search = {
val: '',
icons: function (e) {
// get all the icons.
var icons = $('span[class*="icon-"]');
// assign the search val. (can possibly use later)
search.val = $(e.currentTarget).val();
// let the looping begin!
for (var i = 0, l = icons.length; i < l; i++) {
// get the current element, class, and icon after "icon-"
var el = $(icons[i]),
clazz = el.attr('class'),
iconEnd = clazz.substr(5, clazz.length);
// was the value found within the list of icons?
// if found, show.
// if not found, hide.
(iconEnd.indexOf(search.val) === -1) ? el.hide() : el.show();
}
}
};
$('#txt-icon-search').keyup(search.icons);
One possible way could be to use DataTables, this framework includes a search functionality, its row based tho, could be modified probably. Or if you want to present each icon with some facts like size, name, creator, it would be good maybe. The user could then sort the height etc.
Have a look here
Its a bit heavy weight but have a lot of possibilities for optimization
What you're looking for is something like this: http://jqueryui.com/autocomplete/
Pretty easy and all ready to use. You could pre-populate the available tags with your icons selection. Quick example:
$(function() {
var availableTags = [
"icon-name1",
"icon-name2",
"icon-name3",
"etc."
];
$( "input[name=icon-search]" ).autocomplete({
source: availableTags
});
});
EDIT: of course you can do something much more sophisticated, like displaying a thumbnail/preview of your icon next to each result
EDIT2:
From the sample in your link, I quickly threw something together to have it the way you wanted it:
JSCODE:
<script>
$(function() {
$.expr[':'].Contains = function(a,i,m){
return ($(a).attr("data-index") || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
$("input.filterinput")
.change( function () {
var filter = $(this).val();
if(filter) {
$(list).find("span:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("span:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(function () {
listFilter($("#iconSearch"), $("#list"));
});
});
</script>
Your html code tweaked a little:
<div id="iconSelector" class="icon-list" style="display: block;">
<div id="iconSearch">
<label for="icon-search">Search Icon: </label>
<input type="text" name="icon-search" class="filterinput" value="">
</div>
<ul id="list">
<li><span class="icon-icon1" data-index="red"></span></li>
<li><span class="icon-icon2" data-index="yellow"></span></li>
<li><span class="icon-icon3" data-index="blue"></span></li>
</ul>
</div>
Now if you type "red" you'll get the first span since the search is looking for a match from the data-index attribute. You can replace those with "Facebook", "Twitter", or whatever the name of your icon is.
If you want to directly search from the class name you can do something like this then:
<script>
$(function() {
$.expr[':'].Contains = function(a,i,m){
return ($(a).attr("class") || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
$("input.filterinput")
.change( function () {
var filter = "icon-" + $(this).val();
if(filter) {
$(list).find("span:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("span:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(function () {
listFilter($("#iconSearch"), $("#list"));
});
});
</script>
I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});
I'm trying to do something similar to this:
$('#dropdown1').change(function() {
window.location = $(this).val();
});
I need to build a page with 2 dropdown lists and a textbox, and I need the values for each one to be stored and then appended to the URL when the form is submitted.
The URL needs to look similar to this when all options have been selected:
http://www.domain.co.uk/search-results/?searchOptions=dropdown1=value1|dropdown2=value2|textarea1=value3
I've figured out how to store the values of the dropdowns but I can't seem to append it to the url.. Here's where I got to:
<script type="text/javascript">
function getValues() {
var priceTo = document.form.priceTo.value;
//alert (priceTo);
}
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo
return false;
});
});
</script>
<body>
<form id="form" name="form">
Price:
<select name="priceTo" id="priceTo" onchange="getValues()">
<option value="5000">Up to £5,000</option>
<option value="10000">Up to £10,000</option>
<option value="20000">Up to £20,000</option>
<option value="40000">Up to £40,000</option>
<option value="80000">Up to £80,000</option>
</select>
<input type="submit" id="submit" value="submit"/>
</form>
</body>
For some reason this goes to:
http://www.domain.co.uk/search-results/?searchOptions=priceto=[object%20HTMLSelectElement]
EDIT:
I finally got it working on most browsers, including IE8 with this code:
<script type="text/javascript">
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.selektvolvocars.co.uk/selekt-search-results/?searchOptions='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value + model.options[model.selectedIndex].value + '%7Czipcode=' +document.getElementById('zip').value + '%7Cproximitydistance=50'
e.preventDefault();
});
});
</script>
For some reason though it doesn't work in IE9... makes no damn sense to me, it just spits out a completely jumbled up URL. Any ideas?
your priceTo is the select list. Use the following to get the selected value:
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value
e.preventDefault();
});
If I've understood correctly:
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location = initialURL + $("#priceTo").val() + "|" + $("#anyOtherSelects").val();
e.preventDefault();
});
You can remove the rest of the Javascript.
You can use a little helper function which gets the id of a <select> or <input> element and returns it with its value. For example:
<script type="text/javascript">
//Helper function to return id and value. The id parameter shouldn't have the # sign at its beginning
function getIdVal( id ) {
return id + "=" + encodeURIComponent( $("#"+id).val() );
}
//run this when the document is loaded and ready
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?'
$('#form').submit(function(e) {
window.location.href = initialURL + getIdVal( "priceFrom" ) + "|" + getIdVal( "priceTo" );
return false;
});
});
</script>
Notes:
You get the value of the current <option> selected in a <select> element using $(...).val().
It is a good programming practice to use encodeURIComponent() for encoding the values just to make sure that no strange character is going to break your convention of using = and | as record and field separator in the search query URL.
i have HTML like below,
<ul class="holder" style="width: 512px;">
<li id="pt_5uZqW99dmlgmiuCTJiPHDC9T9o2sfz0I"
rel="test1#gmail.com"
class="bit-box">test1#gmail.com
</li>
<li id="pt_9O0pMJDhtNbRgU1vNM8He8Vh9zpJ1tcE"
rel="test2#gmail.com"
class="bit-box">test2#gmail.com<a href="#"
class="closebutton"></a>
</li>
<li id="pt_U8JH5E9y5w4atm4CadEPvuu3wdh3WcBx"
rel="test3#gmail.com"
class="bit-box">test3#gmail.com<a href="#"
class="closebutton"></a></li>
<li id="Project_update_user_id_annoninput"
class="bit-input">
<input type="text" autocomplete="off" size="0" class="maininput"></li>
</ul>
<input id="removeuser" value="" />
I need to store the values of li's in hidden input box when I click that li's.
If I click first two li's i need to store the values like,
<input id="removeuser" value="test1#gmail.com,test2#gmail.com" />
That is i need to append input values every time when i click li's.
i used below one,
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
jQuery("input#removeuser").val(jQuery.map(jQuery(this).parent().attr('rel')).join(","));
});
});
But it does not works.how can i do that?
http://jsfiddle.net/ySV6F/
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
jQuery("input#removeuser").val(jQuery("input#removeuser").val() + "," + jQuery(this).parent().attr('rel'));
$(this).remove();
return false;
});
});
This fiddle fixes your issue: http://jsfiddle.net/pratik136/zVmwg/
First change I did was move your text within the <a /> tags. This allowed you to click on them as expected.
Next, I changed the JS to:
jQuery(document).ready(function() {
jQuery("a.closebutton").click(function(a) {
var v = jQuery(this).parent().attr('rel');
var t = jQuery("input#removeuser").val();
if (t.indexOf(v) < 0) {
if(t.length>0){
t += ",";
}
jQuery("input#removeuser").val(t + v);
}
});
});
I addded the additional check to ensure no duplicates are entered, and that a comma is appended only when necessary.
Try:
var arr = [];
$(".closebutton").click(function(e) {
e.preventDefault();
var email = $(this).parent("li").attr("rel");
if( $(this).hasClass("added") ) {
arr= $.grep(arr, function(value) {
return value != email;
});
$(this).removeClass("added");
}
else {
arr.push( email );
$(this).addClass("added");
}
$("input[id='removeuser']").val( arr.join(",") );
});
First I would suggest that instead of using rel attribute (which has a specific meaning in (X)HTML with certain tags) you use html safe data-* attributes
like this:
<li id="pt_5uZqW99dmlgmiuCTJiPHDC9T9o2sfz0I" data-email="mdineshkumarcs#gmail.com"
class="bit-box">mdineshkumarcs#gmail.com</li>
To access this attribute just use jQuery $(elem).attr('data-email')
Now the solution with no duplicates:
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
var value = $(this).parent().attr('data-email');
var values = $("input#removeuser").val().split(',');
var is_in = false;
// already in?
$.each(values, function(i, e){
if(e == value) {
is_in = true; return false; // set and exit each
}
});
if (!is_in) {
values.push(value);
$("input#removeuser").val(values.join(','));
}
return false;
});
})
I've put the working code on jsFiddle so that you can see it in action.
jQuery(document).ready(function(){
jQuery("a.closebutton").bind('click', function(){
var data = $(this).parent().attr('rel');
if($("#removeuser").val() == ""){
$("#removeuser").val(data);
} else {
$("#removeuser").val(", "+data);
}
$(this).parent().hide();
});
});
Here I'm removing the li once clicked. You may I believe use the .toggle() function to enable users to remove a value from #removeuser as well.
Hope this helps!