I am not a techie in terms of html or ajax or javascript. But i had to develop a script. My problem is "hide" is not working in my ajax.
I have 2 text field that gives the search result. I want to hide the search suggestion (in "ul" tag) of one when the user searches in the other.
Below given is the javascript and html
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
document.getElementById('house_list_id').style.display = 'none';
}
function autocomplet_house() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#house_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh_house.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#house_list_id').show();
$('#house_list_id').html(data);
}
});
} else {
$('#house_list_id').hide();
}
document.getElementById('country_list_id').style.display = 'none';
}
<form>
<div class="label_div">Search Name:  </div>
<div class="input_container">
<input type="text" id="country_id" name="country_name" autocomplete="off" onkeyup="autocomplet()">
<ul id="country_list_id"></ul>
</div>
<div class="label_div">Search House:  </div>
<div class="input_container">
<input type="text" id="house_id" name="house_name" autocomplete="off" onkeyup="autocomplet_house()">
<ul id="house_list_id"></ul>
</div>
</form>
It seems like you have a hide-condition, that is never met:
var min_length = 0;
if (keyword.length >= min_length){
/* keyword is always zero length or greater */
} else {
/* will never reach here */
}
Besides, I think you want to hide 'the other list', when showing the 'current list' ... Try changing your ajax-success like this:
success:function(data){
$('#country_list_id').html(data).show();
$('#house_list_id').hide();
}
success:function(data){
$('#house_list_id').html(data).show();
$('#country_list_id').hide();
}
Ok ... I have been thinking, and have rearranged everything.
Try this:
<script>
function autocomplet(Elm){
var Name = Elm.attr('name');
var Word = Elm.val();
var ListA = $('#'+Name+'_list_id');
var ListB = Elm.parents('form').find('ul').not(ListA).hide();
var min = 0; // min caracters to display the autocomplete
if( Word.length >= min ){
$.ajax({
url: 'ajax_refresh_'+Name+'.php',
type: 'POST',
data: {Word:Word},
success:function(data){
ListA.empty().html(data).show();
}
});
}
}
</script>
<form>
<div class="label_div">Search Name: </div>
<div class="input_container">
<input type="text" name="country" autocomplete="off" onkeyup="autocomplet($(this));">
<ul id="country_list_id"></ul>
</div>
<div class="label_div">Search House: </div>
<div class="input_container">
<input type="text" name="house" autocomplete="off" onkeyup="autocomplet($(this));">
<ul id="house_list_id"></ul>
</div>
</form>
Thanks a lot OLA, you gave me an idea to reduce the redundancy of the code. I've Cleared my browsing history and it worked.
Related
Could someone plz help me out here as most of the things looks ok like fetching matching results from database but then when i click on value on both input box the same autocomplete value gets added.
could someone please help me fix this issue?
here is my html:
<div class="col-sm-12">
<label class="form-label-outside">From</label>
<div class="form-wrap form-wrap-inline">
<input id="from-input" class="form-input" name="from" type="text">
<div id="from-show-list" class="list-group"></div>
</div>
</div>
<div class="col-sm-12">
<label class="form-label-outside">To</label>
<div class="form-wrap form-wrap-inline">
<input id="to-input" class="form-input" name="to" type="text">
<div id="to-show-list" class="list-group"></div>
</div>
</div>
my js
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#from-input").keyup(function() {
let searchText = $(this).val();
if (searchText != "") {
$.ajax({
url: "airports.php",
method: "post",
data: {
query: searchText,
},
success: function(response) {
$("#from-show-list").html(response);
},
});
} else {
$("#from-show-list").html("");
}
});
// Set searched text in input field on click of search button
$(document).on("click", "a", function() {
$("#from-input").val($(this).text());
$("#from-show-list").html("");
});
});
$(document).ready(function() {
$("#to-input").keyup(function() {
let searchText = $(this).val();
if (searchText != "") {
$.ajax({
url: "airports.php",
method: "post",
data: {
query: searchText,
},
success: function(response) {
$("#to-show-list").html(response);
},
});
} else {
$("#to-show-list").html("");
}
});
// Set searched text in input field on click of search button
$(document).on("click", "a", function() {
$("#to-input").val($(this).text());
$("#to-show-list").html("");
});
});
</script>
and here is the php
require_once 'includes/config.php';
if (isset($_POST['query'])) {
$inpText = $_POST['query'];
$sql = 'SELECT * FROM pt_flights_airports WHERE cityName LIKE ? OR name LIKE ? OR code LIKE ?';
$stmt = $db->prepare($sql);
$stmt->execute(array('%'.$inpText.'%','%'.$inpText.'%','%'.$inpText.'%'));
$result = $stmt->fetchAll();
if ($result) {
foreach ($result as $row) {
echo ''.$row['cityName'].' ('.$row['code'].') - <small>'.$row['name'].'</small>';
}
} else {
echo '<p class="list-group-item border-1">Airport not listed!</p>';
}
}
Appreciate your help
The issue arises due to the click function on link. Define two separate groups of links by specifying the id of the div that contains those links.
// Set searched text in input field on click of search button
$(document).on("click", "#from-show-list a", function() {
$("#from-input").val($(this).text());
$("#from-show-list").html("");
});
// Set searched text in input field on click of search button
$(document).on("click", "#to-show-list a", function() {
$("#to-input").val($(this).text());
$("#to-show-list").html("");
});
Apply max height to the results div using css like this.
<div id="from-show-list" class="list-group" style="max-height: 100px; overflow: auto;"></div>
<div id="to-show-list" class="list-group" style="max-height: 100px; overflow: auto;"></div>
In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;
I'm making a form using MaterializeCSS and jQuery. I got 2 fields : Name and ID.
The field Name is an AutoComplete field that gets the right data. The ID field is not important.
I'm trying to implement a functionality to get data as the user writes.
The problem occurs when the user writes : the data "behind" the AutoComplete is changing properly, but the dropdown component of the AutoComplete hides. The user must click outside of the AutoComplete field and click back on it to see the changes, which is absolutely not user-friendly.
$(document).ready(function () {
//Autocomplete
$(function () {
$.ajax({
type: 'GET',
url: 'https://reqres.in/api/users?page=1',
success: function (response) {
var nameArray = response.data;
var dataName = {};
console.log('nameArray = ' + JSON.stringify(nameArray, 4, 4));
for (var i = 0; i < nameArray.length; i++) {
dataName[nameArray[i].last_name] = nameArray[i].flag;
}
console.log('dataName = ' + JSON.stringify(dataName, 4, 4));
$('#name_autocomplete').autocomplete({
data: dataName,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
$(document).ready(function () {
$('#name_autocomplete').keyup(function () {
$(function () {
$.ajax({
type: 'GET',
url: 'https://reqres.in/api/users?page=2',
success: function (response) {
var nameArray = response.data;
var dataName = {};
console.log('nameArray = ' + JSON.stringify(nameArray, 4, 4));
for (var i = 0; i < nameArray.length; i++) {
dataName[nameArray[i].last_name] = nameArray[i].flag;
}
console.log('dataName = ' + JSON.stringify(dataName, 4, 4));
$('#name_autocomplete').autocomplete({
data: dataName,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" rel="stylesheet"/>
<main>
<div class="container">
<div id="main_panel_form" class="card-panel col s12">
<div class="row">
<form class="col s12" action="/test">
<div class="row">
<div class="input-field col s4">
<input id="name_autocomplete" name="name_autocomplete" type="text" class="autocomplete">
<label id='label_name_autocomplete' for="name_autocomplete" class="active">Name</label>
</div>
<div class="input-field col s3">
<input id="id" name="id" type="text" class="autocomplete">
<label id="label_id" for="id">ID</label>
</div>
</div>
<div class="row center-align">
<button class="btn waves-effect waves-light" type="submit" value="Submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</main>
On this example, when the user starts to write, it gets new data (from ?page=1 to ?page=2)
I'd like to see the data of the AutoComplete change while it remains opened.
I've also made an example on Codepen
The AutoComplete component hides each time the user writes because you initialize #name_autocomplete for each keyup. Each time the init function is called, it closes the autocomplete suggestions.
Materialize has a specific method updateData to refresh the initial object provided: http://materializecss.com/autocomplete.html
I took your codePen and refactored it so you can have an example of the autocomplete method updateData. Codepen
I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.
I have a timeline that loops posts and allows for users to comment on each post. After entering the comment it is meant to prepend to the post in which the comment is made. Problem now is that it prepends to the very first post. This means that this prepend action is not following the loop.
Add comment function
<!--Function to add comment-->
var msg2 = $("#feeds li #comment-form #comment");
var msg = $("#feeds #comment-form #hidden");
var textarea = $('#comment');
$('.comment-btn').on("click",function(event) {
var one = $(this).parent().find(msg2).val();
var two = $(this).parent().find(msg).val();
$.ajax({
type: "POST",
url: "add_comment.php",
data: "msg2="+ one +"&msg=" + two,
msg: "Checking...",
success: function(data){
$('#feeds li #comment-form').parent().find('textarea').val("");
updateComment();
}
});
});
And this is the updateComment function
<!--Function to update the comment feed-->
function updateComment(){
var id = 0;
id = $('#feeds li #other-comments').attr('data-id');
$.ajax({
'url' : 'comment.php',
'type' : 'POST',
'data' : {
'latest_comment_time' : id
},
success : function(data){
if(id != 0){
$('#sub-comments').prepend(data);
}
}
})
}
Edited
html
<div id='comments'>
<form action='' id="comment-form" method="post">
<textarea id="comment" name="comment" placeholder="Add comment..."></textarea>
<input type="button" class='comment-btn' value='Send'>
<input type="hidden" name="msg" value="<?=$item['msg_id']?>" id="hidden">
</form>
<div id="sub-comments">
<?php require('comment.php');?>
</div>
</div>
Note: the 'feeds li' is for the looping post.