Typeahead submit with enter - javascript

I'm using bootstrap typeahead and I'm wondering, how do I make it submit when clicking the enter button? In other words, if I typed "hello" into the typeahead input and pressed enter, how would I submit "hello"?
I've already made it so that the typeahead doesn't auto-select the first result.
This is my code:
<form method="POST" action="script.php">
<input name="typeahead_field" class="typeahead" data-provide="typeahead" autocomplete="off" type="text">
</form>
jQuery:
$('.typeahead').typeahead({
items: 10,
source: function (query, process) {
$.ajax({
url: 'typeahead.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
},
highlighter: function(data) {
// code that returns each result
return html;
},
updater: function(data) {
// code that redirects the user if they click the selection
},
});
Please help!

Old question, but worth answering. Here is a possible solution:
$('.typeahead').on('keydown', function(e) {
if (e.keyCode == 13) {
var ta = $(this).data('typeahead');
var val = ta.$menu.find('.active').data('value');
if (!val)
$('#your-form').submit();
}
}
EDIT: First attempt was very naive :)

You need a submit button to enable submit on enter. You can hide the button with this CSS:
<input type="submit" style="position: absolute; left: -9999px">
(from https://stackoverflow.com/a/477699/759971)

works well, but doesn't highlight selection like mouse-over event does. Maybe this solution would work better as seems to encapsulate the gist of previous answer.
https://bwbecker.github.io/blog/2015/08/29/pain-with-twitter-typeahead-widget/

Related

Jquery result is not coming without alert

I did a live search function Laravel 7 using jquery. I used the keyup function. I have written the code tested each and every time for the keypress the alert is working and result also coming but I stop the alert search result is coming I tried the keypress & keydown event also same issues. I don't what is the issue please help me to solve this issue.
<form id="small-search-box-form" action="{{route('MainSearchProduct')}}" method="get">
<input type="text" class="search-box-text" id="search_query" name="search" placeholder="Search store" />
<input type="submit" class="button-1 search-box-button" value="Search" />
<ul class="search-drop" id="result">
</ul>
</form>
$(document).ready(function() {
var input_search = $('#search_query');
input_search.keyup(function() {
//alert(input_search.val());
var query = input_search.val();
$.ajax({
url: "{{ route('MainSearchQuery') }}",
type: "GET",
data: {
'proSearch': query
},
success: function(data) {
$('#result').html(data);
}
}, 10000);
});
$(document).on('click', 'li', function() {
var value = $(this).text();
$('#search').val(value);
$('#result').html("");
});
});

Get checkbox value with jQuery in .ajax data

I'm trying to pass a boolean (checked/unchecked) value with .ajax, and I can't make it work. I have read a bunch about how to get the value of a checkbox using .is(':checked'), vs .prop('checked') but I can't seem to make anything work.
Here is my HTML:
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
And here is my JavaScript
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $('checkbox#typeOfSearch').prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
I can make the script work for the select boxes, and those continue to work after I add the checkbox, but the value of the checkbox is not being passed.
All I am interested in is passing 'checked' vs 'unchecked'.
Any help would be appreciated. Thanks.
You are using invalid selector. Use input instead.
Your HTML have input element,
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
function send() {
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $('input#typeOfSearch').prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
}
$('#submit').click(function() {
send();
});
You can't select a checkbox as no such tag exists. Try input or even giving it a unique id without caring about the tag e.g. $('#typeOfSearch'):
function send() {
$cb = $('input#typeOfSearch');
console.log($cb.prop('checked'));
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $cb.prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
}
$('#submit').click(function() {
send();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
<button id="submit">Send</button>
Hope this helps :)
$(document).ready(function() {
//set initial state.
$('#typeOfSearch').change(function() {
$('#typeSelected').html(($(this).is(':checked') ? "TRUE" : "FALSE"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="typeOfSearch" /> This Type
<br>
Type Selected:
<span id="typeSelected">FALSE</span>
Your selector is wrong
$('checkbox#typeOfSearch')
You are looking for this:
<checkbox id="typeOfSearch">
If you just select by the id, it would work
$('#typeOfSearch')
The below are some of the ways you can see if the checkbox is checked. If the checkbox is checked the value is true or else it is false.
if ($('#typeOfSearch:checked').length > 0) {
/* Do something */
}
if($('#typeOfSearch').prop('checked') == true) {
/* Do something */
}
if ($('#typeOfSearch').filter(':checked')) {
/* Do something */
}
Hope this helps.
Please search better when asking Stack Overflow questions. This was the top hit on Google for "jquery get checked or unchecked":
https://stackoverflow.com/a/27265333/5129424
Your selector will only attach event to element which are selected in the beginning. You need to determine check unchecked state when value is changed:
$("#countries input:checkbox").change(function() {
var ischecked= $(this).is(':checked');
if(!ischecked)
alert('uncheckd ' + $(this).val());
});
Working Demo

jQuery UI dialog closes on enter in input field

I open my dialog with a button then I place my cursor in a input field and presses enter my dialog closes and this line is inserted to the address bar:
jQuery:
$('#dialog').load("form-incident.php").dialog({
title: "Add Incident",
autoOpen: false,
resizable: false,
width: 800,
modal:true,
position: ['center', 'top+50'],
buttons: {
Add: function(){
$.ajax({
url : 'save.php',
type : 'POST',
data : $('form').serialize(),
context: $(this),
success: function (result) {
if (result === "true") {
alert('Incident has been added successfully');
} else {
alert('ERROR: Cannot insert data to MySQL table');
}
window.location.reload();
$(this).dialog( "close" );
},
error : function(){
alert('ERROR: Check database connection');
}
});
},
Cancel: function() {
$(this).dialog( "close" );
}
}
});
form-incident.php:
<form>
Name: <input type="text" name="name" id="name"><br><br>
Project:
<select name="project" id="project">
<option value="test">Test</option>
</select><br><br>
Incident:<br> <textarea name="incident" id="incident" style="resize:none; width: 100%;" rows="14" cols="94"></textarea>
</form>
How can I fix the problem so the dialog box does not close but still reacts to enter if there was some suggestions from earlier where the form was filled out?
Okay, I forgot that implicit submission will still happen if there is only a single input element in the form, even if there isn't a submit button.
So, it looks like the problem is happening from the form being submitted. But in that case, calling preventDefault() on the submit even will fix it.
I threw together a fiddle with your code snippets from above, and was able to reproduce the problem. Once I put in the preventDefault(), it stopped happening. Please check it out, and see how it differs from your live code.
https://jsfiddle.net/elezar/u0sfx22p/2/

Take input from html field and store it in JSON object (lots of input fields)

I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code
Javascript/jQuery:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.
jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.
Helpful example: https://stackoverflow.com/a/6960586/4180481

Jquery fails when i use button tag in HTML to call Javascript function which in turn uses Jquery

I have button on my HTML page. Initially i was using
<input name="op" id="changepass_submit" value="Change Password" disabled="disabled" class="form-submit" type="button" onClick="change_passwd();" />.
Using this i am able to call the javascript function change_passwd() which has it's definition as,
function change_passwd()
{
var o_pass = document.getElementById('o_passwd').value;
var n_pass = document.getElementById('n_passwd').value;
var c_pass = document.getElementById('c_passwd').value;
if(n_pass == "")
alert("New Password can not be empty!");
else
{
if(n_pass == o_pass)
{
alert('New password and old password are same! Please choose different new password.');
}
else
{
o_pass = rtrim(ltrim(o_pass));
n_pass = rtrim(ltrim(n_pass));
$.ajax({
type: "POST",
data: {o_pass:o_pass,n_pass:n_pass},
url: "changepass",
success: function(response) {
var result = eval(response);
alert(result[1]);
window.location = "/my_profile";
}
});
}
}
}
It works fine.
But when i change <input> tag to:
<button name="op" id="changepass_submit" disabled="disabled" class="form-submit" onClick="change_passwd();" style="width:150px;"><strong>Change Password</strong></button>
it gives jQuery error..
why so? If any body has any suggestions or answers pls let me know. Thanks in advance.
I don't know about the jQuery error (what's the error?) but a <button> is type="submit" by default and not type="button". That means when clicked (assuming it is not disabled as in the markup), since you do not return false to cancel the default action, the form will continue to submit, potentially cancelling your ajax() operation.

Categories