I'm creating a webpage(e-commerce) and I'm trying to put a search bar with autocomplete suggestions and this is my original code with jQuery:
<script>
$(document).ready(function(){
$('#products').keyup(function(){
var query = $(this).val(); var query = document.querySelectorAll(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#productlist').fadeIn(); //
$('#productlist').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#products').val($(this).text());
$('#productlist').fadeOut();
});
});
$('#products').keyup(function() {
if($('#products').val() === '') {
$('#productlist').hide();
}
});
</script>
I'm trying not to use any framework so I wanted to turn the code stated above to vanilla javascript and this is the code I currently have right now:
<script>
document.querySelector(document).ready(function(){
document.querySelectorAll(".products").keyup(function()
{
var query = document.querySelectorAll(this).value();
if(query != '')
{
fetch("search.php")
.then((response))=>response.json())
.then(data)=> console.log(data));
});
}
});
element.addEventListener("click", function (){ console.log("clicked");});
document.querySelector(document).addEventListener('click', 'li', function(){
document.querySelector('#products').val(document.querySelector(this).text());
document.querySelector('#productlist').fadeOut();
});
</script>
Related
I have a search bar, by default it's loading all the data under the search bar.
I want to limit the default before searching to be only 5 results in the table.
I'm trying this but it doesn't work!
What I'm doing wrong?
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
$('#result').dataTable({'iDisplayLength': 5});
}
else
{
load_data();
}
});
});
</script>
And the HTML part is just this code:
<div id="result"></div>
if you are using datatbles then you have to pass pageLength: 5.
$('#example').dataTable( {
"pageLength": 5
} );
you can see in this link
I have an AJAX autocomplete form. After many issues it works.
However I need help with three issues.
If the user type and result display, if the user backspace, the
results remain in schoollist. How do I clear schoollist
searchbox if is empty.
Some of the words contain letters like ë. When retrieved from the
database it display a ■ instead of ë.
If there is no results, it will display "School not found". If you click on school not found, it accepts the answer. I prevent clicking on "School not found?
HTML
<div class="ui-widget">
<label>What school does the child attend<input type="text" name="school" id="school" class="form-control" placeholder="Enter school Name"/></label>
<div id="schoollist"></div>
</div>
AJAX
$(document).ready(function(){
$('#school').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#schoollist').fadeIn();
$('#schoollist').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#school').val($(this).text());
$('#schoollist').fadeOut();
});
});
PHP
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT School FROM Schools WHERE School LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['School'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
https://jsfiddle.net/47v1t3k4/1/
1- I think a simple empty before your AJAX call will solve the problem: $('#schoollist').empty();
2- Use <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> In your html, and also try to set the content type header of your response to utf-8 Like this: header('Content-Type: text/html; charset=utf-8');
3- To prevent click event if no result found you have to use off method:
$('#school').keyup(function(){
var query = $(this).val().trim();
$('#schoollist').empty();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#schoollist').fadeIn();
$('#schoollist').html(data);
if ( data.indexOf("School not found") > -1 ) {
// detach click event
$(document).off('click', 'li', go);
} else {
// attach click event
$(document).on('click', 'li', go);
}
}
});
}
});
function go(){
$('#school').val($(this).text());
$('#schoollist').fadeOut();
}
For 1. issue:
$(document).ready(function(){
// I added two new variables:
var $schoolInput = $('#school');
var $schoolList = $('#schoollist');
$schoolInput.on('keyup', function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$schoolList.html(data).fadeIn();
}
});
}
else { // It's answer for your 1. issue:
$schoolList.fadeOut().html('');
}
});
$(document).on('click', 'li', function(){
$schoolInput.val($(this).text());
$schoolList.fadeOut();
});
});
For 2. issue:
Probably your database has invalid charset. Try to use utf8_general_ci.
For 3. issue:
I suggest to do this if you find a list of schools then enter the response from the server to #schoollist - that is like now. Otherwise, if no school is found then pass a string such as 'notFound'. And then:
$(document).ready(function(){
// I added two new variables:
var $schoolInput = $('#school');
var $schoolList = $('#schoollist');
$schoolInput.on('keyup', function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
// 3. issue:
if(data == 'notFound') {
$schoolList.html('<div class="notFound">School not found</div>').fadeIn();
}
else {
$schoolList.html(data).fadeIn();
}
}
});
}
else { // It's answer for your 1. issue:
$schoolInput.val($(this).text());
$schoolList.fadeOut().html('');
}
});
$(document).on('click', 'li', function(){
$schoolInput.val($(this).text());
$schoolList.fadeOut();
});
// 3. issue
$(document).on('click', '.notFound', function(){
var text = $(this).text();
$schoolInput.val(text);
});
});
i want to check regular expression and if it doesn't match alerts 'invalid' but my problem is regular expression doesn't work
$("#SendPhone").click(function() {
var phonePattern = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/;
if ($("#PhoneField").val() == '' || !$("#PhoneField").match(phonePattern) == false) {
alert("it is invalid")
}
}
i worked with this code in javascript pure it worked but in jquery doesnt work
this is whole jquery code snippet:
<script>
$(document).ready(function() {
$("#SendPhone").click(function() {
var phonePattern = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/;
if ($("#PhoneField").val() == '') {
alert("it is invalid")
}
var phoneField = $("#PhoneField").val();
$.ajax({
type:'post',
url:'insert.php',
data:{'phoneField':phoneField},
success:(function (response) {
})
})
$.ajax({
type:'post',
url:'show.php',
data:{},
success:(function (response) {
$("#CodeField").val(response);
})
})
});
});
If you are sure that your regular expression is the right one, then you need to change your code as follows (the match string method does not return a boolean, it's either an array with the matches or null) :
$("#SendPhone").click(function() {
var phonePattern = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/;
if ($("#PhoneField").val() == '' || !$("#PhoneField").match(phonePattern)) {
alert("it is invalid");
}
});
I have been using this jQuery before I use $.ajax(); and it was working good:
$(document).ready(function(){
var urlSerilize = 'some link';
var appList = $("#applications > li > a");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//var appList = $(".body-list > ul > li");
//var appCheck = $('input[type=checkbox][data-level="subchild"]');
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
installbtn.on('click', function () {
event.preventDefault();
jQuery.each( form, function( i, val ) {
console.log(val);
var request = $.ajax({
url: urlSerilize,
type: 'GET',
data: $('#'+val).serialize(),
success: function( response ) {
console.log( response );
$('#applications').html();
$('#apps_box').html();
}
});
request.done(function(msg){
console.log('Ajax done: ' + 'Yeah it works!!!');
});
request.fail(function(jqXHR, textStatus){
console.log('failed to install this application: ' + textStatus);
});
});
});
});
but after I used this ajax code the .click() jQuery event don't work anymore:
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
})
request.fail(function() {
console.log("error");
})
request.always(function() {
console.log("complete");
});
//end loading apps
var showmore = $('.showapps');
showmore.click(function(){
var parent = $(this).parent('.tv_apps');
var displayC = parent.children('.body-list').css('display');
console.log(displayC);
if (displayC=='none') {
parent.children('.body-list').show('400');
$(this).children().find('img').rotate({animateTo: 180});
}else{
parent.children('.body-list').hide('400');
$(this).children().find('img').rotate({animateTo: 0});
};
});
});
at first place I though it was because of the ajax loads and don't stop, then i was wrong.
I have tried the window.load=function(); DOM function to load the script after Ajax finish loading and also was wrong.
So please if there any idea to fix this problem,
Thanks.
This is the event I want it to be fixed:
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
showmore.click(function(){
should be
$('.showapps').on('click', function(){
OR
$(document).on('click','.showapps', function(){
For dynamically added contents, you need to bind events to it.
For more info: http://learn.jquery.com/events/event-delegation/
Thanks everyone, at last I have found the solution.
It was a question of the DOM, when I use the ready method of jquery it loads an empty ul (without content), so then what I figured out in the first time was correct, all I did is to remove the ready and use a simple function that includes all the .click() events, then call it in request.done();.
This is the solution:
function loadInstaller(){
var urlSerilize = 'some link';
var appList = $("#applications > li");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//...etc
};
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
loadInstaller();
})
//...etc
});
I hope this answer will help someone else :)
I have this array = var1;var2;var3;var4;var5;var6;var6
and I want to split it with jQuery and put it in different textboxes (txt1),(txt2)...etc,
but I can't find the right code.
<script type="text/javascript">
$(document).ready(function() {
$("#cb_motor").change(function() {
$("#cb_motor option:selected").each(function() {
cb_motor = $('#cb_motor').val();
$.post("http://localhost/sag_app/index.php/motor/motor/buscar_id/", {
cb_motor : cb_motor
}, function(data) {
valores = data.split(';');
});
});
})
});
</script>
If txt1, txt2 are inputs ID and is set following DOM order, you could use:
$("[id^=txt]").val(function(i){
return valores[i];
});
Assuming cb_motor is a select with no multiple, the code can be simplified
$(function() {
$("#cb_motor").change(function() {
$.post("http://localhost/sag_app/index.php/motor/motor/buscar_id/", {
cb_motor : $(this).val()
}, function(data) {
var valores = data.split(';');
$('[name="txt_num_serie_motor"]').each(function(i) {
$(this).val(valores[i]);
});
});
});
});
if it IS multiple, then you cannot do Ajax using each for the selected values since you need to wait for each call to return