Could anyone help me on how I can append an '%' character to the spinner text field value, please?
Thank you.
I think this could help you:
$.widget( "ui.mySpinner", $.ui.spinner, {
_format: function( value ) { return value + ' %'; },
_parse: function(value) { return parseInt(value); //or parse to your datatype }
});
$("#spinnerId").mySpinner(
min: 0,
step: 100,
stop: function() {
$(this).siblings().val($(this).val());
});
And in your html:
<input type="text" id="spinnerId" value="1">
EDIT
I found a eassier way to fix this problem, please find the solution here
http://jsfiddle.net/8P6Gf/
Related
I have a search module in which: when a user stop typing it should search the name.
What I think the solution is to do a timeout when a user keyup. reference
<input type="text" #keyup="textSearch($event)">
textSearch(e){
var timer;
clearTimeout(timer);
timer = setTimeout(() => {
alert('searching...');
}, 2500);
}
The code were all working, the problem is why when I type 3 character in just 1 second it pops out 3 alerts? I expect there should be one pop-out since it waits for 2.5 seconds.
Is there something wrong with the code? Need help Sirs
If I understand you problem correctly the timeout you clear each time you run textsearch()is not the one you last created, but the one you just declared with var timer.
I'd suggest storing your timer variable in your data properties instead to have clearTimeout clear the right timeout.
Something like this:
data: {
timer: undefined
},
methods: {
textSearch(e){
clearTimeout(this.timer)
this.timer = setTimeout(() => {
alert('searching...')
}, 2500)
}
}
Working fiddle of your code with my modifications:
https://jsfiddle.net/MapletoneMartin/yjxfsehz/2/
Good luck!
Here is a solution:
setTimeout is fine -- alternatively, you can use debounce Vue-debounce
<input v-debounce:400ms="myFn" type="text" />
<script>
export default {
methods: {
myFn(val) {
console.log(val) // => The value of the input
}
}
}
</script>
What I do to fix this issue is that I take timer variable in Vue data because when textSearch method called inside timer function is reassigned.
data () {
return {
timer: null
}
}
textSearch(e){
clearTimeout(this.timer);
this.timer = setTimeout(() => {
alert('searching...');
}, 2500);
}
I think this will solve your issue.
Another solution for this is, to use a watch instead of using event-keyup. You must create model first.
<input type="text" v-model="searchTxt">
data(){
return{
searchTxt: ''
}
},
watch: {
searchTxt: function(val) {
if (!this.awaitingSearch) {
setTimeout(() => {
alert('searching');
alert(this.searchTxt); //alert value
this.awaitingSearch = false;
}, 2500); // 2.5 sec delay
}
this.awaitingSearch = true;
}
}
More information
CODE USED FOR TYPEAHEAD :
<script type="text/javascript">
$('input.typeahead').typeahead({
name: 'Artist',
prefetch:{url: '/queryjson, ttl: '1'},
template: '<p><strong>{{firstname}}</strong>',
limit : 10,
engine: Hogan,
});
</script>
Code in App.js :
app.get('/queryjson', function(req,res,next){
var firstname = req.body.firstname;
connection.query("select firstname from entries",
function (err, rows, fields) {
if (err)
throw err;
res.end(JSON.stringify({
data : rows
}));
});
})
AND FINALLY THE CODE FOR THE INPUT TEXT IN HTML :
<input class="typeahead" type="text" placeholder="Artist" data-provide="typeahead">
Note :
When i type /queryjson in the address bar, the rows generated by the database are available, and in a json format ( {"data":[{"firstname":"sheila"},{"firstname":"Noreen"}... )
But when i type something inside the input text, no suggestions are generated.
Do you have any idea on what might be possible the issues? I really, really need your help.
Or do you have any suggestions on the proper implementation of typeahead in node using prefetch?
you are missing a single quote! replace '/queryjson, with '/queryjson',
appart from that, it looks correct, http://jsfiddle.net/8GJh2/
Edit: I also notice that your json format is different, they do not include the 'data' element
queryjson:
[
{ "firstname": "sheila"},
{ "firstname":"Noreen"}
]
App.js
res.end(rows);
I'm trying to implement a search bar dropdown using bootstrap v3.0.0 with typeahead.js.
My search bar will take a student's firstname and lastname. I'm using a MYSQL database which consists of a table called practice with afirstname, alastname, aid as columns. The search bar should not only contain the firstname and lastname in the dropdown, but also the id associated with it in a second row. I've read all the examples on the typeahead.js page and I'm unable to do it with ajax call.
Below is the code of my index.php
JS
<script type="text/javascript">
$(document).ready(function() {
$('.cr.typeahead').typeahead({
source: header: '<h3>Select</h3>',
name: 'accounts',
source: function (query, process) {
return $.getJSON(
'localhost/resultly/source.php',
{ query: query },
function (data) {
return process(data);
});
});
});
</script>
HTML:
<body>
<div class="container">
<br/><br/>
<input type="text" name="query" class="form-control cr typeahead" id="firstname" />
<br/><br/>
</div>
</body>
Code for source.php : This should return the firstname and lastname from my database in the form of a json string or object?
<?php
$query = $_POST['query'];
try {
$conn = new PDO('mysql:host=localhost;dbname=practice','root','');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
$stmt->execute();
}
catch (PDOException $e) {
echo 'ERROR:' . $e->getMessage();
}
foreach ($stmt as $row) {
$afirstname[] = $row['afirstname'];
$alastname[] = $row['alastname'];
}
echo json_encode($afirstname);
echo json_encode($alastname);
?>
result:
http://oi41.tinypic.com/50moi1.jpg
Nothing shows up. I've tried adding a prefetch:
prefetch: {
url: 'localhost/resultly/source.php',
filter: function(data) {
r1 = [];
for (var i = 0; i < data.length; i++) {
r1.push({
value: data[i].afirstname,
tokens: [data[i].afirstname, data[i]alastname],
afirstname: data[i].afirstname,
alastname: data[i].alastname,
template: '<p>{{afirstname}} - {{alastname}}</p>',
});
}
return r1;
}
}
Please do provide a solution or an example which I could refer.
Update:
The source.php should return a list of json encoded data. I debugged by looking at the output that the source.pho created. What I did wrong was whenever I was supposed to put a url I did localhost/source.php instead of just source.php.
Solution provided by Bass Jobsen works and now I have run into another problem.
I'm using
if(isset($_POST['query']))
{ $q_uery = $_POST['query'];
$query = ucfirst(strtolower($q_uery))};
to take the user's data and use it for searching logic
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
The updated source.php is http://pastebin.com/T9Q4m10g
I get an error on this line saying Notice: Undefined variable: stmt I guess the $query is not being initialized. How do I get this to work. Thanks.
Update 3
I used prefetch: instead of 'remote:' that did all the matching.
Your return is not correct:
echo json_encode($afirstname);
echo json_encode($alastname);
See for example Twitter TypeAhead.js not updating input
Try echo json_encode((object)$stmt);, see: typeahead.js search from beginng
Update
I tried echo json_encode((object)$stmt);still doesn't work.
Do you use any kind of debugging? What does? source.php return? Try to follow the steps from
typeahead.js search from beginng without the filter.
html:
<div class="demo">
<input class="typeahead" value="" type="text" spellcheck="off" autocomplete="off" placeholder="countries">
</div>
javascript:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10
});
php (source.php):
<?php
$people = array();
$people[] = array("lastname"=>"Inaw",
"firstname"=>"Dsajhjkdsa");
$people[] = array("lastname"=>"Dsahjk",
"firstname"=>"YYYsgbm");
$people[] = array("lastname"=>"Dasjhdsjka",
"firstname"=>"JHJKGJ");
$datums = array();
foreach($people as $human)
{
$datums[]=(object)array('value'=>$human['firstname'],'tokens'=>array($human['firstname'],$human['lastname']));
}
echo json_encode((object)$datums);
This should work
update2
Thanks, it worked. How do I display 2 or more 'value'?
add some values to your datums in source.php:
foreach($people as $human)
{
$datums[]=(object)array
(
'value'=>$human['firstname'],
'tokens'=>array($human['firstname'],$human['lastname']),
'firstname'=>$human['firstname'],
'lastname'=>$human['lastname']
);
}
firstname and lastname now are field you csn use in your templates
Add a template and template engine to your javascript declaration:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10,
template: [
'<p>{{firstname}} - {{lastname}}</p>'
].join(''),
engine: Hogan
});
The above make use of https://github.com/twitter/hogan.js. You will have to include the template engine by javascript, for example:
<script src="http://twitter.github.io/typeahead.js/js/hogan-2.0.0.js"></script>
It is working for me. please follow below step.
Please add below Js and give proper reference.
bootstrap3-typeahead
--- Ajax Call ----
$("#cityId").keyup(function () {
var al = $(this).val();
$('#cityId').typeahead({
source: function (valuequery, process) {
var states = [];
return $.ajax({
url: http://localhost:4000/GetcityList,
type: 'POST',
data: { valueType: "", valueFilter: valuequery },
dataType: 'JSON',
success: function (result) {
var resultList = result.map(function (item) {
states.push({
"name": item.Value,
"value": item.Key
});
});
return process(states);
}
});
},
});
});
---- Cs Code ---
public JsonResult SearchKeyValuesByValue(string valueType, string valueFilter)
{
List<KeyValueType> returnValue = SearchKeyValuesByValue(valueType, valueFilter);
return Json(returnValue);
}
Auto suggest of Bootstrap typehead will get accept only "name" and "value" so create reponse accordinly
I want to create asynchronous username validation,
where upon change of the value of the username input, the database is accessed to see if that username is valid for use. So far I have this code, which doesn't seem to work. Please help me in finding out where things went wrong. Thanks!
My HTML:
<div>Username</div>
<input type="text" name="id" id="id">
<div id="idval"></div>
My Script:
<script>
function CheckId() {
$.get('/signup/', {username: $(this).val()},
function(data){
if(data == "True"){
$('#idval').html("You may use this ID");
} else {
$('#idval').html("Unavailable");
}
});
}
function onChange(){
$("#id").change( function() {CheckId()});
}
$(document).ready(onChange);
</script>
My View:
def signup(request):
if request.method == "GET":
p = request.GET.copy()
if p.has_key('username'):
name = p['username']
if User.objects.filter(username__iexact=name):
return HttpResponse(False)
else:
return HttpResponse(True)
in CheckId() $(this).val() isn't going to work. You need $('#id').val()
See this discussion of how the this keyword works
Could you please help me in forming the DIV block(HTML) for the response which i got in JSON format.
JSON format: [{"REL_NAME" : " 999999999","SO" : "","U_ID" : "105"}]
Snippet:
function ServiceSucceeded(result) {
$('#accNo12').empty();
if (DataType == "json") {
$('#accNo12').append("<div id=\"Search\" class=\"results\">"+
"<span id=\"lb\">Account No:"+result.U_ID+"</span></div>"+
"<label>RelMgr: </label>"+
"<span id=\"RID\">"+result.REL_NAME +"</span><br />"+
"<label>Off ID: </label><span id=\"OffId\">"+ result.SO+"</span><br/>");
}
}
As of now i am getting the output values as undefined.
Appreciate if you could help
Thanks
function ServiceSucceeded(result) {
$('#accNo12').empty();
if (DataType == "json") {
result = result[0];
...
basically, your result object is inside an array. alternatively you can use result[0].U_ID instead of result.U_ID
I think your problem here is that you don't parse the JSON data
Add this at the beginning of your function,
result = jQuery.parseJSON(result);
Basically you are checking for an inexistent DataType. I fiddled around and here are the results:
html:
<div id='accNo12'>hello</div>
javascript:
function ServiceSucceeded(result,DataType) {
alert(DataType);
$('#accNo12').empty();
if (DataType == "json") {
$('#accNo12').append("<div id=\"Search\" class=\"results\">"+
"<span id=\"lb\">Account No:"+result.U_ID+"</span></div>"+
"<label>RelMgr: </label>"+
"<span id=\"RID\">"+result.REL_NAME +"</span><br />"+
"<label>Off ID: </label><span id=\"OffId\">"+ result.SO+"</span><br/>");
}
}
$(document).ready( function () {
ServiceSucceeded(jQuery.parseJSON('{"REL_NAME" : " 999999999","SO" : "","U_ID" : "105"}'),'json');
});
result:
Account No:105
RelMgr: 999999999
Off ID: