Enter to select and activate href link - javascript

I have setup an autocomplete searchbar with jquery. When I type a part of a searchterm the suggestions pop-up, when I click the suggestion I get redirected to a new page (of the suggestion) which is good.
The problem I have is when I type the a part of a searchterm or the full searchterm there is no action.
What I want is: When I type a searchterm or a part of a searchterm and I press Enter I get redirected to the page of the first suggestion. When I press hover over the suggestion press Enter right now, the first suggestion just comes up in the searchbar.
How can I go about this?
Javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/black-tie/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
$(function() {
var projects = [{
label: "Bitcoin (BTC)",
icon: "./alt/alt_logo/bitcoin.png",
href: "./alt/alt_info/bitcoin.html"
}, {
label: "Ethereum (ETH)",
icon: "./alt/alt_logo/ethereum.png",
href: "./alt/alt_logo/bitcoin.png"
}, {
label: "Litecoin (LTC)",
icon: "./alt/alt_logo/litecoin.png",
href: "./alt/alt_logo/bitcoin.png"
}, {
label: "Cardano (ADA)",
icon: "./alt/alt_logo/cardano.png",
href: "./alt/alt_logo/bitcoin.png"
}];
$(".field_values").autocomplete({
source: projects,
create: function() {
$(this).data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.append('<img class="icon" src="' + item.icon + '" />' + item.label + '<br>' + '')
.appendTo(ul);
};
}
});
});
PS: Dont mind the wrong href in var projects
EDIT:
When I submit the form by pressing enter or hitting the button. The page reloads but stays on the same page.
HTML:
<div class="searchbar">
<form id="submitsearch">
<input class="field_values" id="autocomplete" placeholder="Search..."/>
<button type="submit" id="searchbutton" class="icon" ><i class="fa fa-search"></i></button>
</form>
</div>
I also tried <form action="./js/searchbar.js"> but that just sends me to a webpage with the javascript displayed on it

You need to add autoFocus: true, to the autocomplete
so that it becomes:
$("#field_values").autocomplete({
autoFocus: true,
source: projects,
This only puts the data into the form field.
To handle the data, you will need to do the following:
Wrap the input in a form tag
Make sure you have a submit button in the form
You will then be able to hit enter to fill in the field and you will have to hit enter again to submit the form.

Related

Display another button with autocomplete in JS

I'm tring to do a autocomplete from json url, it works good.
Now what I want, it's when I click to the autocomplete, I want to display the import button and if input is empty or we put a new value (not in the import), display the create button.
Give you a example on what i'm doing with some datas:
$('#search-deal').autocomplete({
source: function(request, response) {
var data =[{
"id": 1671,
"title": "Queens Park Tyres deal"
}, {
"id": 1672,
"title": "Wildman Craft Lager deal"
}, {
"id": 1673,
"title": "General Store deal"
}, {
"id": 1674,
"title": "Deluxe Off Licence deal"
}, {
"id": 1675,
"title": "Ahmed Halal Bazaar deal"
}];
var datamap = data.map(function(i) {
return {
label: i.id + ' - ' + i.title,
value: i.id + ' - ' + i.title,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
if(i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0){
document.getElementById("create").style.visibility = 'hidden';
document.getElementById("import").style.visibility = 'visible';
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
};
});
response(datamap);
},
minLength: 1,
delay: 100
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="text" id="search-deal" />
<button id="create" type="submit" class="btn btn-primary">Créer une affaire</button>
<button id="import" type="submit" style="visibility:hidden" class="btn btn-primary">Importer</button>
The problem here, it's when I write "p", the button import show up and I want to show up only when I click to the autocomplete.
The second problem, it's the button create nevere come back if value is empty or put another value
Anybody can help me ?
I understand from the shared snippet that you are using jquery ui autocomplete.
I would suggest following changes/updates to your code
For changing button display on selecting the autocomplete item, use select event. https://api.jqueryui.com/autocomplete/#event-select
Whenever user types something, hide the import button. Display it only when an item is selected.
For handling empty input case, use oninput event.
I have made following changes to the code you shared
Added a new function to handle button toggle
Hide the import button from source property i.e. when user type some input and also when input box is blank
Show the import button when user selects an autocomplete option
Working code link: https://plnkr.co/edit/PgzUuOADhIqk9zbl?preview
I hope this solves your issue

convert text to editable text input and save into db - Laravel

I'm currently implementing a feature that somebody can add addresses on my page. He can do this via a simple form. What I have now (to print the addresses) is:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: {{$address->name}}<br/>
Straße: {{$address->street}}<br/>
PLZ: {{$address->plz}}<br/>
Ort: {{$address->city}}<br/>
<a type="button" class="btn btn-info" href="/editAddress/{{$address->id}}">Bearbeiten</a>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
The variable addresses is passed into the view from the controller.
What I'm trying to achieve now, is that the user can simply click on one of those address parts, like name, straße, plz and ort, and it's converted to an input field, so the value can be changed. Then, when leaving the focus (so clicking somewhere else (or maybe add a save button next to it)), the new data has to be sent to the controller by ajax (the request itself should be no problem then). But: How can I convert it to an input field and how can I then convert it back and react to it (to then send the ajax request)?
I searched in the internet, but didn't find something...
Edit: found a fiddle here (http://jsfiddle.net/yXcZG/3) that does nearly what I want, but I have the problem, that it doesn't seem to keep the format, 1. it has much more space between the lines and: when clicking on it to edit, the input field jumps to the bottom of the page and doesn't stay on the same position. Also I just want the variables to be editable, not the text before the :.
So this is what I tried: (of course the AJAX thing is still missing, but first the other thing has to work)
In JS:
$(document).on('click', '.editableText', function (e) {
console.log(this);
TBox(this);
});
$("input").live('blur', function (e) {
RBox(this);
});
function TBox(obj) {
var id = $(obj).attr("id");
var input = $('<input />', { 'type': 'text', 'id': id, 'class': 'editableText', 'value': $(obj).html() });
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var input = $('<p />', { 'id': id, 'class': 'editableText', 'html': $(obj).val() });
$(obj).parent().append(input);
$(obj).remove();
}
HTML:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: <span id="addressName{{$address->id}}" class="editableText">{{$address->name}}</span><br/>
Straße: <span id="addressStreet{{$address->id}}" class="editableText">{{$address->street}}</span><br/>
PLZ: <span id="addressPLZ{{$address->id}}" class="editableText">{{$address->plz}}</span><br/>
Ort: <span id="addressCity{{$address->id}}" class="editableText">{{$address->city}}</span><br/>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
Edit2: Found this answer on stackoverflow too (https://stackoverflow.com/a/6814092/3375021), so use contenteditable, but I have the problem, that I on blur neither know, which address should be changed in the database, nor which part of the address..
If you're looking for a jQuery working solution you can go with this
JsFiddle example
You have a listener for when you click an element that is editable, it'll take the value of it and put it inside an input.
After you blur you can take this value and do whatever you want with it..
Here is the javascript (jQuery) part.
$(function(){
$('body').on("click", ".changeable", function(e){
var text = $(this).text();
$(this).html("<input type='text' class='input-editable' value='" + text + "'>");
$(this).find('input').focus();
});
$('body').on("blur", ".input-editable", function(e){
var text = $(this).val();
$(this).parent().html(text);
console.log("Value changes to: " + text);
});
});
I think you should be using <?php echo $variable; ?> instead of blade {{$variabl}}
If you going to store a html tags or js into your database then you need to not use blade to echo it, you should use php simple echo function instead

Using Fuel ux placard on jQuery autocomplete field

I have a situation where I have a jquery autocomplete field that I would also like to make a placard for (http://getfuelux.com/javascript.html#placard). I've got everything set up fine. When I click the field, the placard shows up, and I can still type into the field to receive suggestions.
The problem comes in when I attempt to click one of the suggestions. It calls my select: function as expected, which populates the text input. But then as the event cascades it triggers the "cancel" (I'm guessing here) event on the placard, which resets the value of the input to default and removes the placard visual.
Here's the gist of the code:
HTML
<label class="control-label">Select User:</label>
<div class="placard" data-initialize="placard">
<div class="placard-popup"></div>
<input class="autocomplete-web-users placard-field glass form-control" id="Approver_FirstName" name="Approver.FirstName" type="text" value="" />
<div class="placard-footer">
<a class="placard-cancel" href="#">Cancel</a>
<button class="btn btn-primary btn-xs placard-accept" type="button">Confirm</button>
</div>
</div>
JS
$(".autocomplete-web-users").autocomplete({
source: function (request, response) {
var $element = $(this.element).parent().first();
var $loader = $("<span style='font-size: 1em; position: relative; top: -25px; right: 20px;' data-initialize='loader' class='loader'></span>");
$element.append($loader);
//start loading spinner
$loader.loader();
$loader.loader('play');
$.ajax({
url: '/Search/SearchWebUsers',
data: { term: request.term },
success: function (data) {
var results = $element.data('results');
//data loaded, destroy data spinner
$loader.loader('destroy');
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Id,
tag: item.UniqueId,
id: item.Id
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
event.preventDefault();
$(event.target).parents().find(".placard").placard('setValue', ui.item.tag);
}
});
JS PLACARD INITIALIZATION
$(".placard").placard();
I've fiddled with the "explicit" and "externalClickAction" options, but can't seem to get anything to work. Any ideas? I can't find anything about fuel ux on the intertubes.

Add an html element on click

I have a very simple function to render the value of an input "text" into the html.
<form>
<input type="text" class='test'><input type='submit' value='send'>
</form>
<div class='test2'> </div>
<script>
$("form").submit(function() {
var value = $('.test').val();
$('.test2').html(value);
});
</script>
The thing is that everytime we press "send", the new value replace the old one. I would like to display the new message without deleting the old ones, on top of them.
i.e I would like to add a 'DIV' or a 'P' each time I click on the button send.
Thank you for your help.
Try it like this
$("form").submit(function() {
var value = $('.test').val();
$('.test2').append('<p>' + value + '</p>');
});
jsBin demo
$("form").submit(function(e) {
e.preventDefault();
$('<div>',{ text: $('.test').val() }).appendTo('.test2');
$('form').get(0).reset();
});

JQuery - AJAX dialog modal, can't hit enter key to submit form

On a website I'm working on, when you click sign on, a jquery dialoge modal pops up, but you have to click on OK to submit the form, you can't just hit enter. I need it to be able to have enter work also. It seems like what I have should work, but it doesn't
I'm using jquery-1.3.2.js. I also have a php file with the following piece of code in it: `
<tr valign="top" align="right" style="height:40px"><td >
<div id="signin">
<table style="margin-top:4px;margin-right:4px;border-style:solid;border-width:1px">
<tr><td style="width:165px;">
<div><center>
<a title="Sign In" onclick="LoginDialogOpen()" href="javascript:void();">Sign In</a><b> | </b>
<a title="Create Account" href="CreateAccount.html">Create Account</a>
</center></div>
</td></tr>
</table>
</div>
</td></tr>
<div id="Signin_Dialog" >
<div id="bg">
<label><span>Email:</span></label>
<input type="text" name="email" id="email" class="dialog-input-text"/>
<br>
<label><span>Password:</span></label>
<input type="password" name="password" id="password" class="dialog-input-text"/>
<br>
<br>
<center><b><label id="login_error" style="color:red"><span> </span></label></center></b>
</div>
</div>
<script>
$('#login_dialog').dialog({
autoOpen: false,
width: 310,
overlay: { opacity: 0.5, background: "black" },
modal: true,
buttons: {
"Ok": function() {
$("body").addClass("curWait");
sql = "select client_id from users where email = '" + $("#email")[0].value + "' and login_password='" + $("#password")[0].value + "'";
$.get('BongoData.php', { task:"SQLResultToJSON", sql: sql}, ResultOfLoginAttempt, "json");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
</script>`
i have a javascript file with the following function:
function LoginDialogOpen(){
$('#login_dialog').dialog('open');
$('#login_dialog').keypress(function(e) {
if (e.which == 13) {
$("body").addClass("curWait");
sql = "select client_id from users where email = '" + $("#email")[0].value + "' and login_password='" + $("#password")[0].value + "'";
$.get('BongoData.php', { task:"SQLResultToJSON", sql: sql}, ResultOfLoginAttempt, "json");
}
});
}
That is the code I have, I don't understand why it isn't working.
I also had it try $('#login_dialog').dialog('isOpen'); right after i opened it, but it always returned false oddly enough. Please help if you can.
I strongly recommend to consider all notes made by the others regarding raw client side SQL!
Regarding your actual question I propose the following:
Put a form in your login dialog like so:
<div id="login_dialog">
<form method="get" action="BongoData.php">
<input type="text" name="email" />
<input type="password" name="password" />
<input type="submit" />
</form>
</div>
Then in your script part where the dialog is initialized write something like:
$('#login_dialog').dialog({
autoOpen: false,
width: 310,
overlay: { opacity: 0.5, background: "black" },
modal: true,
buttons: {
"Ok": function() { $('#login_dialog form').submit(); },
"Cancel": function() { $(this).dialog("close"); }
}
});
// hide the original submit button if javascript is active
$('#login_dialog form input[type=submit]').hide();
// register a submit handler to submit the form asynchronously
$('#login_dialog form').submit(function () {
// calling serialize() on a form transforms form inputs to a string suitable for $.get and $.post
$.get($(this).attr('action'), $(this).serialize(), ResultOfLoginAttempt, "json");
// prevent that the browser submits the form.
return false;
});
// and register a key listener to submit the form if the user presses enter on the password input field
$('#login_dialog form input[type=password]').onKeyDown(function (e) {
if (e.which == 13) {
// just trigger the submit handler
$('#login_dialog form).submit();
}
});
With these preparations you can simplify your javascript a lot:
function LoginDialogOpen(){
$('#login_dialog').dialog('open');
}
Some additional notes:
Don't use SQL in your javascript. Instead write a customized php file with prepared sql to verify login data. In this solution the login form degrades gracefully if no javascript is present as it is a standard html form which can be sent by the browser. You should also be aware of the fact, that some browser send forms (i.e. trigger the submit handler) on Enter without further requirements, but as it's browser specific you cannot rely on this if it's a must for your application. As a last action you should eventually check whether you need to close the dialog manually within your "ResultOfLoginAttempt" method.
Look at the Tamper Plugin for Fire Fox : Tamper Data 10.1.0
Genertate SQL on the client side is bad. You can hijack the http request.
I think you mean if (e.keyCode == 13) { rather than if (e.which == 13) {.
Also Ian Elliot is right. You should never have the actual sql as any part of your javascript or any part of your form. You can submit values to the server that will eventually be interpolated into your SQL*, but never the complete SQL.
*Once the values have been properly validated, sanitized, & optionally passed through another layer of abstraction (think MVC).

Categories