I have used the below code for Livesearch in my webpage and it works fine in the student form. But in the index page for second text box(Staff form), live search is not working. I hope this is due to the use of JQuery function using attribute ID which is same for both input text box. Is there anyway to make the live search work in second text box without changing the entire code?
Thanks in advance
livesearch.js
$('#college').keyup(function(e)
{
if ( key != 40 && key != 38 && key != 13 ) livesearch();
}
function livesearch() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $.trim($('#college').val());
if (keyword.length >= min_length) {
$.ajax({
url: 'livesearch.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#college_list').show();
$('#college_list').html(data);
}
});
} else {
$('#college_list').hide();
}
}
index.php
<div id="student">
<form action="/" method="post">
<div class="field-wrap">
<input type="text" id="college" placeholder="College Name" required
autocomplete="off"/>
<ul id="college_list"></ul>
</div>
<button type="submit" class="button button-block"/>Get
Started</button>
</form>
<!-- Another Division similar to previous one-->
<div id="staff">
<form action="/" method="post">
<div class="field-wrap">
<input type="text" id="college" placeholder="College Name" required
autocomplete="off"/>
<ul id="college_list"></ul>
</div>
<button type="submit" class="button button-block"/>Get
Started</button>
</form>
livesearch.php
$parts = explode(' ', $keyword);
$p = count($parts);
$sql = "SELECT * FROM colleges WHERE college_id is not null";
for($i = 0; $i < $p; $i++) {
$sql .= " AND college_name LIKE '%$parts[$i]%'";
}
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// Highlight the written text
$college_name = highlight($keyword,$rs['college_name']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'",
$rs['college_name']).'\')">'.$college_name.'</li>';
}
You're targeting elements with an id - in the first line:
$('#college').keyup(function(e) { ... }
If you switch that to a class, such as .live-search and add this class to your HTML element, the script should naturally work on multiple elements.
ID's in HTML should be unique, whereas classes can be applied to multiple elements.
Update: You might also need to switch this line:
var keyword = $.trim($('#college').val());
To reference this instead:
var keyword = $.trim($(this).val());
This will ensure that when you detect a keyup on that element, that the script acts upon that one particular element.
Related
Based on my post checkbox unchecked var value 0 checkbox checked var value 1
where livello begins with 000..000 as all checkbox are unchecked and change state as a checkbox is checked, for example: 010..111, now I want to do the edit part. In this part the livello string is read from the database. I want livello to show the livello values and change as checkboxes are checked or not. Then the value from livello need to be reconverted to php string to write its value on the database.
<div class="modal-body">
<div class="form-group">
<label class="control-label col-sm-4" for="livello_u_l">Selezionare accessi per l'utente:</label>
<br>
</div>
<div class='form-group'>
<?php
// read from database but for example
$livello_u_l = '00011100011100011100011';
$liv_u_l = '';
$sql_u_l = "SELECT id, posizione, nome
FROM user_livelli";
$result_u_l = $conn->query($sql_u_l);
$contatore = 0;
if ($result_u_l->num_rows > 0) {
// output data of each row
while($row = $result_u_l->fetch_assoc()) {
$id_u_l = $row['id'];
$posizione_u_l = $row['posizione'];
$nome_u_l = $row['nome'];
// check if checkboxes are checked or not
if (substr($livello_u_l, $contatore, 1) == 1){
echo "<input type='checkbox' name='nome_posiz_u_l[]' checked />" ." " .$nome_u_l ." ";
//$liv_u_l .= '1';
$liv_u_l[$contatore] = '1';
} else {
echo "<input type='checkbox' name='nome_posiz_u_l[]' unchecked />" ." " .$nome_u_l ." ";
//$liv_u_l .= '0';
$liv_u_l[$contatore] = '0';
}
$contatore += 1;
?>
<div id='show_u_l' class='col-sm-12'></div>
<?php
}
}
//echo $livello_u_l;
//echo $liv_u_l;
//echo '<br>';
//print_r($liv_u_l);
?>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="livello_u_l">Livello:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="livello_u_l" name="livello_u_l"> </div>
</div>
<script type="text/javascript">
let oInput1=document.getElementById('livello_u_l');
let oCol1=Array.from( document.querySelectorAll('.form-group > input[type="checkbox"]') );
// the following line fill livello with all 0
let livello_u_l=new Array( oCol1.length ).fill( '0', 0, oCol1.length );
// I want something like this
//let livello_u_l=new Array( oCol1.length ).fill( <?php echo json_encode($liv_u_l); ?> );
oInput1.value=livello_u_l.join('');
oCol1.forEach( (chk,index)=>{
chk.addEventListener('change',function(e){
livello_u_l.splice(index,1,this.checked ? '1':'0' );
oInput1.value=livello_u_l.join('');
});
})
</script>
</div>
<br>
<br>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="update_utente"><span class="glyphicon glyphicon-edit"></span> Modifica</button>
<button type="button" class="btn btn-warning" data-dismiss="modal"><span class="glyphicon glyphicon-remove-circle"></span> Annulla</button>
</div>
The script must be modified first to see the livello value read from the data base and then to modify its value on checkbox changes. And at the end its value must be converted to php string to write it on the database.
I tried to modify the javascript to fill the array with the value read from the database without success or better the way commented, write 23 times the livello value and also when I change one or more checkbox state it add 0 or 1 to the value and not modify it
The problem should be in the following line.
let livello_u_l=new Array( oCol1.length ).fill( '0', 0, oCol1.length );
Instead of fill livello with all 0 I want something like this
let livello_u_l=new Array( oCol1.length ).fill( <?php echo json_encode($liv_u_l); ?> );
oInput1.value=livello_u_l.join('');
fill livello with $livello_u_l = '00011100011100011100011';
I'm trying to assign id's to some text fields that's getting created dynamically in a loop.
The div which is in the loop that consists of the text fields.
<!-- DATA ENTERED IN THIS TEXT BOX WILL BE REFLECTED IN ALL THE TEXT BOXES CREATED IN THE LOOP-->
<div class="col-sm">
<h5><span class="badge badge-dark">Add Quantity:</span></h5>
<input class="form-control" type="text" name="add0" id="add0" onkeyup="sync()">
</div>
<!-- SCRIPT FOR REFLECTING DATA -->
function sync()
{
var add0 = document.getElementById('add0');
var add1 = document.getElementById('add1');
var add2 = document.getElementById('add2');
var add3 = document.getElementById('add3');
var add4 = document.getElementById('add4');
var add5 = document.getElementById('add5');
var add6 = document.getElementById('add6');
var add7 = document.getElementById('add7');
var add8 = document.getElementById('add8');
add8.value = add7.value = add6.value = add5.value = add4.value = add3.value = add2.value = add1.value = add0.value;
}
<?php
<!-- GETS AN ARRAY OF DATA SCANNED IN THE PREVIOUS PAGE -->
$strings = explode(PHP_EOL,($_SESSION['grid']));
$sa = [];
foreach ($strings as $s) {
array_push($sa, "'".$s."'");
}
$d=implode(',', $sa);
<!-- SQL QUERY -->
$sql = "select distinct size from items where main_group IN(select distinct main_group from items where addl_item_code_barcode IN ($d)) ORDER BY size";
$result = pg_query($db, $sql);
?>
<div class="row">
<!-- THIS LOOP WILL CREATE 8 DIV'S BECAUSE THERE ARE 8 SIZES 36-50 -->
<?php while($res = pg_fetch_assoc($result)){ ?>
<div class="col-md-2 show-hide">
<input type="text" value="<?php echo $res['size']; ?> " readonly
style="background-color: #F5F5F5;" class="form-control"/>
<!-- // OUTPUT WILL BE GENERATED HERE -->
<div id="addition"></div>
<select class="form-control">
<option>25%</option>
<option>50%</option>
<option>100%</option>
</select><br>
</div>
</div>
<br>
<br>
<button type="submit" value="submit" class="btn btn-primary"><i class="fas fa-paint-brush"></i>Apply</button>
</form>
<?php }?>
<!-- The script that I tried for assigning unique id's -->
$(document).ready(function() {
for( var i=1; i<9; i++) //i<9 because that's the maximum number of
// text fields to be created is 8.
{
$('#addition')
.append('<input class="form-control" type="text" name="add" id="add'+i+'" />');
}
The problem is that this script creates a series of text boxes only in the first iteration of the while loop.
Here's how it looks.
Here this output is creating all the 8 text boxes below the 'size' field i.e, '36'. How do I get the 2nd text box below 38 and the 3rd below 42 and so on...
Is there a way only create the id's dynamically and append it in the input area, instead of putting the input itself in the loop like I have done?
var text = "";
for(var i=0;i<11;i++)
{
text += '<input class="form-control" type="text" name="add" id="add_'+i+'" /></br>';
}
$("#addition").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="addition"></div>
You can set the id within the while-loop, but you have to set an unique id. Maybe you should include the loop-iterator in the id. Try following example:
<?php while($res = pg_fetch_assoc($result)){ ?>
<div class="col-md-2 show-hide">
<input type="text" id="field<?php echo $res['size']; ?>" value="<?php echo $res['size']; ?> " readonly
style="background-color: #F5F5F5;" class="form-control"/>
<div id="addition"></div> // OUTPUT WILL BE GENERATED HERE
<select class="form-control">
<option>25%</option>
<option>50%</option>
<option>100%</option>
</select><br>
</div><?php }?>
I have foreach loop in php on front page for getting images and description of the image, inside foreach loop I have form, form is use for sending comment, this is front page..
<?php foreach ($photo as $p) : ?>
<div class="photo-box">
<div class="galP photo-wrapper" >
<div data-fungal="<?php echo $p->id; ?>" class='galFun-get_photo'>
<img src="<?php echo $p->thumb; ?>" class='image'>
</div>
</div>
<div class='inline-desc'>
<a href="/gallery/user.php?id=<?php echo $p->userId; ?>">
<?php echo $p->username; ?>
</a>
</div>
<form method="POST" action="" class="form-inline comment-form galForm">
<div class="form-inline">
<input type="hidden" class='photoId form-control' name="photoId" value="<?php echo $p->id; ?>" >
<input type="hidden" class='userId form-control' name="userId" value="<?php echo $session->userId; ?>" >
<textarea cols="30" rows="3" class='comment fun-gal-textarea' name="comment" placeholder="Leave your comment"></textarea>
<button type='button' name='send' class='sendComment'>SEND</button>
</div>
</form>
<div class='new-comm'></div>
<div class='comments-gal' id='comments'>
<div data-id='<?php echo $p->id; ?>' class='getComment'>
<span>View comments</span>
</div>
</div>
</div>
Using ajax I want to send userId,photoId and comment after clicking the button that has class sendComment. When I send comment on the first image everything is ok but when I try to send comment for some other image it wont work. I can't select that specific input and textarea for geting the right value .This is my jquery
$('body').on('click','.sendComment',function(){
var selector = $(this);
var userId = selector.siblings($('.userId'));
var photoId = selector.siblings($('.photoId'));
var c = selector.siblings($('.comment'));
var comment = $.trim(c.val());
if (comment == "" || comment.length === 0) {
return false;
};
$('#no-comments').remove();
$.ajax({
url: '/testComment.php',
type: 'POST',
data: {comment:comment,userId:userId,photoId:photoId}
}).done(function(result) {
...
}
})
});
Also, I have tried in every possible way to get the right value from the form without success..
This line
var userId = selector.siblings($('.userId'));
will be unlikely to get the correct input as, according to https://api.jquery.com/siblings/
.siblings( [selector ] )
selector
A string containing a selector expression to match elements against.
so this would need to be :
var userId = selector.siblings('.userId');
at that point you also need to get the actual value from the input, giving:
var userId = selector.siblings('.userId').val();
var photoId = selector.siblings('.photoId').val();
var c = selector.siblings('.comment');
and the rest of the code as-is.
I'm building an AJAX live search, it works but I would like to navigate using keyboard arrows (up/down). I don't know how I can do this.
My form.php
<div class="input-group" id="nav-input-group" style="display:table;">
<input name="q" id="thesearchbar" class="form-control input-search " name="search" placeholder="Serach..." autocomplete="off" type="text" onclick="">
<div class="result"></div>
</div>
My script
$(document).ready(function(){
$('#nav-input-group input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("_ajax_search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents("#nav-input-group").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
and _ajax_search.php
<?php
require('bdd_pdo_connect.php');
try{
if(isset($_REQUEST['term'])){
$sql = "SELECT * FROM subcategories WHERE subcategory LIKE :term";
$stmt = $bdd->prepare($sql);
$term = '%' . $_REQUEST['term'] . '%';
$stmt->bindParam(':term', $term);
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row['subcategory'] . "</p>";
}
} else{
echo "<p>No matches found";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
unset($bdd);
?>
I'm new with AJAX and any help will be greatly appreciated.
Why don't you use HTML select tag to make a dropdown list? It supports arrow keys navigation by default. If you want all options to appear, use the size attribute of the HTML select tag (see HTML5 size attribute specification).
HTML
<div class="input-group" id="nav-input-group" style="display:table;">
<input name="q" id="thesearchbar" class="form-control input-search " name="search" placeholder="Serach..." autocomplete="off" type="text" onclick="">
<select class="result" size="10"></div> <!-- size="10" is an example here -->
</div>
JS
// (ajax part)
// ...
$(document).on("change", ".result", function(){
$(this).parents("#nav-input-group").find('input[type="text"]').val($(this).val());
$(this).empty();
});
There is similar code in the application that works in this same fashion, but my addition is not working. I can get the search page to pop-up in a new window, but when I select the group to pass to the form page and display the pop-up window will not close or populate the form field on the add form page. Any help would be appreciated.
ADD Form PHP Page
Want to hide a readonly form field for a group name and display a button to search group listing from another page.
Form Field Page HTML Code
<div class="form-group">
<label class="col-sm-3 control-label" for="groupId">Group *</label>
<div class="col-sm-6" id="div_gr_name" style="<?php if ($gr_id < 1) {?> display:none <?php } else { ?> display:inline <?php } ?>">>
<input type='text' name='gr_name' class='span2 form-control' placeholder="Search Group Name" value="<?php if ($gr_id != -1) {echo $gr_name;} else {echo '';} ?>" id='gr_name' readonly='true' required/>
</div>
<div class="col-sm-2" style = "<?php if ($gr_id > 1) {?> display:none <?php } else { ?> display:inline <?php } ?>">
<button type="button" class="btn btn-primary" onclick='OpenPopup()'>Search</button>
</div>
<div>
<span id='paientNameMissing'></span>
</div>
</div>
Javascript OpenPopup from footer page
function OpenPopup() {
try {
window.open("searchgroup.php", "_blank", "width=850,height=500,scrollbars=yes,resizable=yes");
}
catch (ex) {
alert(ex);
}
finally {
event.cancelBubble = true;
event.returnValue = false;
return false;
}
}
Searchgroup Selection PHP Page
Group Selection Page PHP & HTML Code
//retrieve our table contents
while($row=mysql_fetch_array($rs)){
extract($row);
//creating new table row per record
echo "<tr>
<td>{$gr_name}</td>
<td>{$gr_leadername}</td>
<td>{$gr_leadcontact}</td>
<td>{$gr_leademail}</td>
<td>";?>Select<?php echo "</td>
</tr>";
}
//end table
echo "</tbody>
</table>
</div>";
}
Select Group javascript function
function select_group( id, name ){
var selvalue = id;
var selvalue1 = name;
window.opener.document.getElementById('gr_id').value = selvalue;
window.opener.document.getElementById('gr_name').value = selvalue1;
if (id!=0) {
window.opener.document.getElementById('div_gr_name').style.display = "inline";
}
else {
window.opener.document.getElementById('div_gr_name').style.display = "none";
}
window.close();
}
if you use window.open you call new browser window which doesnt know nothink about other windows. You can use store your information (cookies or session, i prefer cookies because they are stored on client side) to share across multiple browser windows. If you use phpmyadmin, look how it works