autocomplete on click updates the same value on second input box - javascript

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>

Related

textarea not send form do not send form the first click to send. The at 2 click yes

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;

hold the value from form through keyup

I have an input field through which i am getting the value that user enters, although i am able to display it but instead of displaying it, i wish to store the user entry in a variable and then use it to get data from database. Below is the code that i have so far (#JSFiddle)
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button">submit</button>
</form>
<script>
$( "input" )
.keyup(function() {
var value = $( this ).val();
$( "p" ).text( value );
})
.keyup();
</script>
E.g: if a user enters 12 in input box and then click enter button, then 12 should get stored in a variable, but the whole form should not get submitted after every value of input field is filled then only the form should get submitted
$idd=12;
and then i wish to run a query as
$sql=" SELECT * from menu where id = '".$idd."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
/*
*
* code to display data
*
*/
}
}
and the result that i need to display will come from the code running inside while loop
Can anyone please tell how to obtain the result
With this code, you store the result to a variable declared before the keyup event.
<input type="text" value="some text">
<p></p>
<script>
var inputValue;
$( "input" )
.keyup(function() {
inputValue = $(this).val();
})
.keyup();
</script>
Than you could do your AJAX call.
EDIT
Here's the code that only respond to the "enter" keycode
var value;
$('input').on('keyup', function(ev) {
if(ev.keyCode == 13) {
value = $(this).val();
}
});
You can do by two ways
<input type="text" value="some text" id="input_id" name="input_name">
<input type="submit" name="submit">
With jquery/ajax
$('#input_id').on('keyup', function() {
var field_value = $("#input_id").val();
jQuery.ajax({
type: 'post',
url: 'path_to_the_file',
data: { fieldValue: field_value },
success: function(successData) {
//do whatever want on success
}
});
});
Or without jquery/ajax On same page
if(isset($_POST['submit']))
{
$my_value = $_POST['input_name'];
//Execute your query
}
you can use ajax to post value of input box and get the result like this
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button" id="btnsubmit">submit</button>
</form>
<script>
var value
$("input").keyup(function () {
value = $(this).val();
})
$('#btnSubmit').click(function(){
$.ajax({
type: "POST",
url: "url_of_php_page",
data: {id: value},
success: function (html)
{
$("p").text(html);
}
});
});
</script>

Hide is not working in Ajax

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:&nbsp </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:&nbsp </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:&nbsp</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:&nbsp</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.

Debugging failing jQuery validate addMethod

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.

open a modeldialog on submit of a form with all values of that form

I have an MVC4.0 website that has a button on a screen. according to my requirement i have submit a hidden form that has some hidden values, on the click of that button. My requirement is that
I have to open a model dialog with all these hidden values.
Please give me some solution.
//under a Beginform of a view this button code is written
<input type="button" id="idBtnScan" name="btnName" value="Scan" onclick="javascript:subProcessURL()" />
//I have add this hidden form on click of this button
//#Model.UDConfig.sScanningURL = is the url of the another website's default page
//Model.UDConfig.listScanData (list) that contains all parameter that takes another website.
<form id="idFormSelect" action ="#Model.UDConfig.sScanningURL" method="post" >
<div class="makeHidden">
#for(int i=0;i<Model.UDConfig.listScanData.Count;i++)
{
<input type="text" id="#Model.UDConfig.listScanData[i].sKey" name="#Model.UDConfig.listScanData[i].sKey" value ="#Model.UDConfig.listScanData[i].sValue" />
}
<input type="text" id="ASPUserSessionId" name="ASPUserSessionId" value="#Session.SessionID" />
<input type="submit" name="SubmitDetails" />
</div>
</form>
<script type ="text/javascript" >
function subProcessID() {
window.showModalDialog("#Model.UDConfig.sScanningURL", "#idFormSelect", "dialogWidth:700px;dialogHeight:500px;scroll:no;")
$("#idFormSelect").submit();
}
</script>
$("#idBtnScan")[0].onclick = function () {
HideDivInfoNErrorMsg();
ShowOverlay_Base();
subProcessURL();
#*$.ajax({
//type: "POST",
//url: "#Url.Action("GetSingleScanURL", "CreationOutward")",
//success: function (data) {
//window.showModalDialog(data, "", "dialogWidth:700px;dialogHeight:500px;scroll:no;")*#
//functionality of view image
$.ajax({
type: "POST",
url: "#Url.Action("ActionViewImage", "CreationOutward")",
success: function (dataImage) {
HideDivInfoNErrorMsg();
if ((dataImage == "Image not found")
|| (dataImage == "Image Folder not found")
|| (dataImage == "Error in processing image")
|| (dataImage == "Multiple Images found")) {
$("#DivInfoNErrorMsg")[0].innerHTML = "<div class=\"errormessage\"><span>".concat(dataImage, "</span></div>");
DisplayInfoNErrorMsg();
}
else {
$("#divImgView")[0].innerHTML = dataImage;
HideDivInfoNErrorMsg();
}
HideOverlay_Base();
}
})
//View Image till here
//}
//}
// )
}
Your button calls a javascript function called 'subProcessURL', but in your code there's only a subProcessID function. These do not match

Categories

Resources