typeahead not updating field - javascript

I am trying to implement typeahead for a city look-up for, but the field does not get updated. The city details show up, but I need to show the name in the city when a city is clicked, but when the form is sent, I need to send only the city code.
This is my HTML:
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
And this is the javascript:
$('#_hotelCity').typeahead({
source: function (query, process) {
airports = [];
map = {};
var data = (function () {
var data = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://localhost/imakeway/forms/finder/iata-aero-codes.json',
'dataType': "json",
'success': function (jdata) {
data = jdata;
}
});
return data;
})();
$.each(data, function (i, airport) {
map[airport.complete_location] = airport;
airports.push(airport.city + ' ( <b>' + airport.iata_code + '</b> - ' + airport.airport_name + ') near ' + airport.complete_location);
});
process(airports);
},
updater: function (item) {
selectedairport = map[item].complete_location;
selectedairport = map[item].iata_code;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp( '(' + this.query + ')', 'gi' );
return item.replace( regex, "<strong>$1</strong>" );
},
});
Thank you for any suggestions

HTML input tag can have only one value. This value is stored internally and displays inside the field.
It seems you are using some kind of AJAX form submission.
So, your solution is to have separate variable in JS to store city code.
Another solution is to use Select2 instead of typeahead.
This is my choice when you provide a SELECT-like field but need external AJAX data source.
Btw, with Select2 you can also force user to choose only an existing value.
Look here for example: http://ivaynberg.github.io/select2/#ajax

I would suggest you to use an additional hidden field which you update aside the normal input field.
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
<input type="hidden" value="" name="city_code" />
In this hidden field you put the city code eachtime the typeahead is updated. When submitting the form your server side script can parse it (in PHP it would $_POST['city_code']).

Using typeahead, and didnt want to replace very much of your code. I ended up with this fiddle: http://jsfiddle.net/Ydtq9/2/
You will definitely want to refactor some things but the trick is to set some instance variables in the source function, and you can access them in the updater function like so
$("#_hotelCity").typeahead({
"source": function(query, process) {
this.map = ...
},
"updater": function(item) {
var city = this.map(item)
//Then you can do what you need to with the original data.
}
})

Related

Get SPARQL query showing after submitting in Javascript

I am trying to display the result of a query after user presses submit with the value they have inputted, the query aims to grab this input and generate a result specific to the input. The query does grab the input as I have put the query code in an alert box and it displays the input from the user in the query, this alert box pops up after pressing submit of course. My code are below:
Html
<table id="results">
</table>
<form>
First name:<br>
<input id="messageInput" type="text" name="firstname"><br>
<input id="submit99" type="submit" value="Submit">
</form>
The query result should display in the table after pressing submit. Therefore table was inserted.
Script
<script type="text/javascript">
var table = $("#results");
table.on("click", "td", myFunction);
var url = "http://dbpedia.org/sparql";
$('#submit99').on('click', function (e) {
var userInput = $('#messageInput').val();
var query = [
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX type: <http://dbpedia.org/class/yago/>",
"PREFIX prop: <http://dbpedia.org/property/>",
"SELECT ?spouse",
"WHERE {",
"?dave dbo:spouse dbr:" + userInput + ".",
"?dave rdfs:label ?spouse.",
"}",
"Limit 1"
].join(" ");
alert("this query: [" + query + "]");
var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";
console.log(queryUrl);
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function (data) {
console.log(data);
// get the table element
var table = $("#results");
// get the sparql variables from the 'head' of the data.
var headerVars = data.head.vars;
// using the vars, make some table headers and add them to the table;
var trHeaders = getTableHeaders(headerVars);
table.append(trHeaders);
// grab the actual results from the data.
var bindings = data.results.bindings;
// for each result, make a table row and add it to the table.
for (rowIdx in bindings) {
table.append(getTableRow(headerVars, bindings[rowIdx]));
}
}
});
function getTableRow(headerVars, rowData) {
var tr = $("<tr></tr>");
for (var i in headerVars) {
tr.append(getTableCell(headerVars[i], rowData));
}
return tr;
}
function getTableCell(fieldName, rowData) {
var td = $("<td></td>");
var fieldData = rowData[fieldName];
//alert("fieldName = ["+fieldName +"] rowData[fieldName][value] = ["+rowData[fieldName]["value"] + "]");
td.html(fieldData["value"]);
return td;
}
function getTableHeaders(headerVars) {
var trHeaders = $("<tr></tr>");
for (var i in headerVars) {
trHeaders.append($("<th>" + headerVars[i] + "</th>"));
}
return trHeaders;
}
});
</script>
As you noticed the query result should be displayed in a table after user has pressed submit that's why I put almost all the code in the submit99 button. You guys should be able to run the code by copying and pasting it to your own IDE to gain a more familiar understanding. So question is right now after submission nothing shows up besides the alertbox displaying user input.
Thanks for your time :)
So I managed to fix the issue and get the result... all I had to do was insert the form elements in the table like:
<table id="results">
<First name:
<br>
<input id="messageInput" type="text" name="firstname">
<br>
<input id="submit99" type="submit" value="Submit">
</table>
However it is very strange because when I try to input the form tags it doesn't work:S atleast it does what I want it to do now:)

How to get the values in dynamicaly append check box list

I have created UI as the way what I want to enter data.
After selecting product name, flavors of that product append dynamically with check box.
All the check box data append dynamically using JS function. after that I tried to insert those data to database when button click. But I have problem in how to getting the ID of checkbox list which are checked.
Could any one please help me to figure out this problem?
I'm using Codeigniter framework for developing.
JS:
var ptype = $j("#cmb_freeproduct_type").val();
//alert(ptype);
//$j('#eqtyrw').hide(500);
$j.ajax({
type: 'post',
url: 'loadFlavorTypes',
data: {ptype:ptype},
success: function (data) {
alert(data);
var result = JSON.parse(data);
//alert(result);
var datas = [];
for (var x = 0; x < result.length; x++) {
datas.push('<tr id="'+result[x].product_flavour_id+'">'
+'<td>'
+'<input type="checkbox" name="fflavor_wise" id="fflavor_wise'+x+'" autocomplete="off" value=""></input>'
+'</td>'
+'<td id="fflavor'+x+'"> <b>'+result[x].product_flavour+'</b> </td>'
+'</tr>');
}
$j("#flavors_for_product_free").html(datas);
},
error: function(data){
alert('error');
}
});
jQuery:
// Find all checkboxes on the page that are currently checked.
var checked = $("input[type=checkbox]:checked");
Plain JavaScript:
// Find all input elements.
var inputs = document.getElementsByTagName("input");
var checked = [];
// Cycle our input elements list and find the checkboxes
// that are checked.
for ( var i = 0; i < inputs.length; i++ ) {
if ( inputs[i].type == "checkbox" && inputs[i].checked ) {
checked.push(inputs[i]);
}
}
In either case, you will now have an array containing checked checkboxes. Getting the ids of those should be pretty straight forward.
A strong argument for using jQuery when comparing these techniques.
It would be better to give them all a class (e.g. fflavor_wise_cb), then you can easily get the checked ones:
var checkedCbs = $('.fflavor_wise_cb:checked');
Or since they all share the same name, you can use that:
var checkedCbs = $('input[type=checkbox][name="fflavor_wise"]:checked');
Then you can iterate through them using each:
checkedCbs.each(function() {
console.log($(this).val());
});
In your code their value is empty, so to test better to give them a vale.
First, Please put dataType:"JSON" in ajax code, then use jquery $(data)each(function(index)){}
I have made above mentioned changes in your code, please check.
$.ajax({
type: 'post',
url: 'loadFlavorTypes',
data: {ptype:ptype},
dataType:"JSON",
success: function (data) {
alert(data);
var result = data;
//use jquery each function to iterate over the data
$(result).each(function(x){
$("#flavors_for_product_free").append('<tr id="'+result[x].product_flavour_id+'">'
+'<td>'
+'<input type="checkbox" name="fflavor_wise" id="fflavor_wise'+x+'" autocomplete="off" value=""></input>'
+'</td>'
+'<td id="fflavor'+x+'"> <b>'+result[x].product_flavour+'</b> </td>'
+'</tr>');
});
},
error: function(data){
alert('error with'+data);
}
});

How to find which checkboxes are selected and pass them to ActionResult in MVC?

I have a MVC5 app, and in one of my views, I have something like that:
<div id="subcatsform" class="form-group" style="visibility:hidden;">
#Html.LabelFor(m => m.Subcategories, new { #class = "col-md-3 control-label" })
<div id="subcats" class="col-md-9">
</div>
</div>
Then, in my JavaScript part, I do something like this in order to populate my empty div.
$(function () {
$("#CategoryID").on("change", function () {
var selected_option = $("#CategoryID option").filter(":selected").text();
$("#subcats").empty();
if (selected_option != "Please select a category") {
$("#subcatsform").css("visibility", "visible");
$.ajax({
url: "/Home/GetSubcategories",
dataType: "json",
data: {
cid: $("#CategoryID").val(),
},
success: function (data) {
$.each(data, function (key, value) {
var checkbox = '<input type="checkbox" name="subcategory" value="' + value.id + '"> ' + value.value + '<br />';
$("#subcats").append(checkbox);
});
}
});
}
else
{
$("#subcatsform").css("visibility", "hidden");
}
});
});
So, I simply check with category is previously selected, and then accordingly list all the subcategories found inside that category, and create input with type checkbox for each one of them. This works all fine, I'm able to get the appropriate subcategories when I change my category, and it creates the checkboxes for me.
The problem is that, later I don't know how to find out which checkboxes are selected, when the user presses the submit button in my view's form.
My ActionResult is defined like this:
public async Task<ActionResult> RegisterBusiness(BusinessViewModel model)
And inside my BusinessViewModel, I have a property defined like this:
public virtual ICollection<Subcategory> Subcategories { get; set; }
Any idea, how can I get the all checked checkboxes, and get their value property when the form is submitted?
Assuming that you have a boolean property named IsSelected in your SubCatagory class.
You should be to able send the values like this
var checkedList = $.map($(':input[name="Subcategory"]'),
function(){
var $this = $(this);
return {
name :$this.data('subcatagory'), // You can add the subcatagory as a data dash attribute or any other unique identifier in html of the checkbox before appending
IsSelected : $this.is(':checked')
}});
$.ajax({
url : '<your url>',
type:"POST",
contentType:"application/json; charset=utf-8",
data : JSON.Stringify({
'Subcategories' :checkedList
})
});

handling "No results" with Jquery Autocomplete

Hey I'm trying to return a message when there are no results for the users current query! I have looked all over the net and there are similar scenarios, but I can't seem to get it working with my code below!
Can anyone help me figure this out please, as I am pulling my hair out trying to fix it!
I need to maintain the ability to use the keyboard to scroll down through the results.
Thanks in advance.
HTML
<div id="search_box">
<form id="search_form" autocomplete="off" action="" onSubmit="return false;">
<input type="text" id="suggestSearchBox" value="Search by City or Hotel Name" onClick="this.value='';" />
</form>
</div>
Javascript
NOTE: The remote data source is called "dataLocCodes", which is a javascript array
// JavaScript Document
$(function() {
$("#suggestSearchBox").focus().autocomplete(dataLocCodes, {
max: 15,
selectFirst: true,
matchContains: true,
formatItem: function(row, i, max){
if (row.hotelId) {
return row.accomName + ' - ' + row.city + ' - ' + row.country;
} else {
return row.city + ' - ' + row.country;
}
}
}).result(
function(event, row, formatted) {
$("input#suggestSearchBox").val(row.city + ' - ' + row.country);
var param = row.locparam;
var encoded_url = param.replace(/ /gi,"+");
encoded_url = encoded_url.replace(/&/gi,"amp");
window.location.href = "hotels.html?location=" + encoded_url;
});
});
There are a couple of ways to handle this. You can either create a source method so that if the results from the filter are empty, you add "no results" as a value, or you handle the response event to display a message that no results where returned in your ui. If using the source method, then add a select handler to prevent No Result from being a value.
var availableTags = ['Abc', 'Def', 'ghi'];
$('#noresults').autocomplete({
source: function (request, response) {
var responses = $.ui.autocomplete.filter(availableTags, request.term);
if (responses.length == 0) responses.push('No Result');
response(responses);
},
response: function (event, ui)
{
if (ui.content.length == 0) {
console.log('No results');
}
},
select: function (event, ui) {
// don't let no result get selected
return (ui.item.value != 'No Result');
}
});

Problems with jquery Table sorter on my table, I recieve wall of json text

I am using MVC3 on my project.
I have a view with a bunch of DDL's, Search Button and a Table.
User can choose values and then hit the search button and the table will show all data that got hit.
This is my jquery code for the search button click:
$(function () {
$('#submitfloat').click(function () {
var SubjectTypes = $('#SubjectTypes').val();
var Teams = $('#Teams').val();
var Companies = $('#Companies').val();
var Consultants = $('#Consultants').val();
var PlannedDates = $('#PlannedDates').val();
var CompletedDates = $('#CompletedDates').val();
var DateTypes = $('#DateTypes').val();
var data = {
Subjectypes: SubjectTypes,
Companies: Companies,
Teams: Teams,
Consultants: Consultants,
PlannedDates: PlannedDates,
CompletedDates: CompletedDates,
DateTypes: DateTypes
};
$.post('#Url.Action("Search", "SearchNKI")', data, function (result) {
$("#GoalcardSearchResult tbody").html('');
result.forEach(function (goalcard) {
$("#GoalcardSearchResult tbody").append(
$('<tr/>', {
click: function () {
// todo: redirect
alert(goalcard.Id);
},
html: "<td>" + goalcard.Name + "</td><td>" + goalcard.Customer + "</td><td>" + goalcard.PlannedDate + "</td><td>" + goalcard.CompletedDate + "</td>"
}));
});
});
return false;
});
});
This is my Controller:
[HttpPost]
public JsonResult Search(SearchQueryViewModel model)
{
var goalcard = SearchRep.FindGoalCard(model); // My LINQ
return Json(goalcard.Select(x => new GoalCardViewModel(x)));
}
Everything works fine but when I add my Jquery Table Sorter:
<script type="text/javascript">
$(document).ready(function () {
$("#GoalcardSearchResult").tablesorter();
});
</script>
I get this wall of Json text when I click on the Search button:
![][1]
[1]:
I have no idea why this happens, when I debug my search button click jquery code its not even getting executed when I add the Table Sorter jquery code. Anyone have any idea what the cause is?
All I know is that when I add the Table Sorter, it blocks my button click jquery code from running and jumps directly to the server-side and returns json.
Thanks in advance!
It was a modified Table Sorter code, with some minor changes I got it running

Categories

Resources