Autocomplete multiple value from database - javascript

I've completed the question before. However I got another issue. I want to make multiple autocomplete like https://jqueryui.com/autocomplete/#multiple .
I've include function into my script but still doesn't work.
This is html email form code
<div class="input_container">
<input type="text" id="contact_id" name="sender" onkeyup="autocomplet()" size="95">
<input type="hidden" id="client_id" value="<?php echo $id_client; ?>">
<ul id="contact_list"></ul>
This javascript script
function autocomplet() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#contact_id').val();
var cid = $('#client_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_email_refresh.php',
type: 'POST',
data: "keyword="+keyword+"&cid="+cid+"",
success:function(data){
$('#contact_list').show();
$('#contact_list').html(data);
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
}
});
} else {
$('#contact_list').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#contact_id').val(item);
// hide proposition list
$('#contact_list').hide();
}
ajax_email_refresh code
$keyword = '%'.$_POST['keyword'].'%';
$cid = $_POST['keyword2'];
$sql = "SELECT * FROM contact WHERE contact_name LIKE (:keyword) AND id_client = (:cid) ORDER BY contact_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$contact_name = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['contact_email']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['contact_email']).'\')">'.$contact_name.'</li>';
}

I am not sure if I understood correctly what you are looking for. I have included an example that will help you get started. The timer I have included is to minimize the amount of ajax request you will be doing. Instead of making a request on after every single key stroke, it actually waits 250 milliseconds after the last stroke has been made to run your ajax.
var object = [{'key': 'value1'}, {'key': 'value2'}];
var timer;
function autocompletion(element){
clearTimeout(timer);
timer = setTimeout(function(){
var options = element.nextElementSibling;
options.innerHTML = '';
for(var i = 0; i < object.length; ++i){
var li = document.createElement('li');
li.innerHTML = object[i]['key'];
options.appendChild(li);
}
options.style.display = 'block';
}, 250);
}
<div class="input_container">
<input type="hidden" id="id_client" name="id_client" value="<?php echo $id_client; ?>">
<input type="text" id="contact_id" name="sender" onkeyup="autocompletion(this)" size="95">
<ul id="contact_list" style='display: none'></ul>

Related

How to insert dynamic HTML elements into database using PHP?

I'm having some issues submitting an HTML form. The form allows the user to add skills to the HTML page using a button. These newly created skills then need to be inserted into the database. The problem is, I can only insert one skill at a time. The skills are entered as checkboxes and all checked skills should be entered in the database. I think my issue is that each checkbox that is created dynamically shares the same $skill_name variable, but this is not an issue when I grab existing skills from the database to display. I added some ajax to try and save each skill in a post statement as they are created, but it doesn't help when I actually go to insert. The INSERT statement looks something like this:
if(!empty($_POST["backend"])){
$backend = $_POST["backend"];
$sql2 = "INSERT INTO skill (skill_cat_id, skill_name) VALUES (?,?)";
$skill_cat_id = 1;
for ($i = 0; $i < count($backend); $i++){
$skill_name = $_POST["skill_name"];
if($stmt = $mysqli->prepare($sql2)){
$stmt->bind_param("is", $skill_cat_id, $backend[$i]);
if ($stmt->execute()) {
echo "<script>
alert('Success!');
</script>";
}
else{
echo "<script>
alert('Failure!');
</script>";
}
}
}
}
And the HTML for looks like this:
<h5>Backend Technologies </h5>
<div class="container">
<div id = "backendDiv">
<?php
$backend=getbackendtech();
while($row = $backend -> fetch_assoc()) {
// echo "<input type='checkbox' value='{$data['skill_name']}'>". $data['skill_name'];
echo "<div class=\"list-group-item checkbox\" id = \"backendCheckBoxes\">
<label><input type=\"checkbox\" name=\"backend[]\" class=\"common_selector form\" value='{$row['skill_name']}'> {$row['skill_name']}</label>
</div>";
}
echo"<input type=\"button\" class='btn btn-warning btn-sm' id = \"addBackendButton\" value = \"Add\" onclick=\"addSkill('backendCheckBoxes', 'backendDiv', 'backend', 'addBackendButton')\">";
?>
</div>
</div>
And here is the addSkill event:
function addSkill(checkBoxDivId, divId, nameId, buttonId){
//Variables
//Creating new elements for new skills and
//setting their attributes
let count = 0;
console.log(checkBoxDivId);
let existingSkills = document.querySelectorAll("div[id =" + checkBoxDivId +"]");
console.log(existingSkills);
for (let i = 0; i < existingSkills.length; i++){
count++;
}
let uniqueId = count+1;
console.log(uniqueId);
let hiddenValue = document.createElement("input");
hiddenValue.setAttribute("hidden", true);
hiddenValue.setAttribute("name", "skill_name");
let checkBoxDiv = document.createElement("div");
checkBoxDiv.setAttribute("id", checkBoxDivId);
checkBoxDiv.setAttribute("class", "list-group-item checkbox");
//console.log(checkBoxDiv);
let textBoxParent = document.getElementById(divId);
//console.log(textBoxParent);
let newTextBox = document.createElement("input");
newTextBox.setAttribute("type","text");
newTextBox.setAttribute("id", "newTextBox");
let newCheckBox = document.createElement("input");
newCheckBox.setAttribute("name", nameId);
newCheckBox.setAttribute("class", "common_selector form");
newCheckBox.setAttribute("type","checkbox");
newCheckBox.setAttribute("checked", true);
newCheckBox.setAttribute("value", uniqueId);
let newLabel = document.createElement("label");
newLabel.setAttribute("for", "newCheckBox");
let addButton = document.getElementById(buttonId);
//console.log(addButton);
//adding textbox to page
textBoxParent.appendChild(newTextBox);
//When an enter key is pressed the newly created textBox
//will be removed and a new checkbox will appear
newTextBox.addEventListener("keypress", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
//console.log(newTextBox.value);
//Canceling the default action, if needed
event.preventDefault();
event.stopPropagation();
//Setting Label value
newLabel.innerHTML = newTextBox.value;
let skill_name = newLabel.innerHTML;
console.log(newCheckBox.getAttribute("value"));
//posting skill name to database
hiddenValue.setAttribute("value", newLabel.innerHTML);
console.log(hiddenValue);
//Remove textbox from page
textBoxParent.removeChild(newTextBox);
//Adding new Checkbox to Div
checkBoxDiv.appendChild(newCheckBox);
checkBoxDiv.appendChild(newLabel);
//checkBoxDiv.appendChild(hiddenValue);
//Adding new Checkbox Div to page
addButton.before(checkBoxDiv);
$.ajax({
type: 'post',
data: {skill_name: skill_name},
success: function(response){
alert(skill_name);
}
});
}
});
}

How can I get my information to display into a link <a href> or a <div>?

The issue I am having is that I need the search results to be displayed in a link or a . Right now they display into a text input field. When I try to change it to a link or div no text is generated. I am almost certain it has to do with the java/jquery script I have. The script I am using is an open source script that I need for simple reasons.
What I have tried is changing the element in which the script calls for from an input to a div or a href. I have googled and tried to find some sort of reference to which the script selects what elements to display the code into and the only thing I can identify as being the problem is, "userid = ui.item.value; // selected id to input".
index.php - Script
<script type="text/javascript">
$(document).ready(function(){
$(document).on('keydown', '.username', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var name = response[0]['name'];
var displayid = response[0]['displayid'];
document.getElementById('name_'+index).value = name;
document.getElementById('displayid_'+index).value = displayid;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function(){
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='username' id='username_"+index+"' placeholder='Enter username'></td><td><input type='text' class='name' id='name_"+index+"' ></td><td><input type='text' class='displayid' id='displayid_"+index+"' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
</script>
index.php - Html
<div class="container">
<table border='1' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Search</th>
<th>Name</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<tr class='tr_input'>
<td><input type='text' class='username' id='username_1' placeholder='Enter username'></td>
<td><input type='text' class='name' id='name_1' readonly></td>
<td><input type='text' class='displayid' id='displayid_1' readonly></td>
</tr>
</tbody>
</table>
<br>
<input type='button' value='Add more' id='addmore'>
</div>
getDetails.php
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM item_template WHERE name like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['entry'],"label"=>$row['name']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM item_template WHERE entry=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['entry'];
$name = $row['name'];
$displayid = $row['displayid'];
$users_arr[] = array("entry" => $userid, "name" => $name,"displayid" => $displayid);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I except the selector is wrong in the script, where it selects where to copy the text to.
You just need to use innerHTML instead of value.
document.getElementById('name_'+index).innerHTML = name;
document.getElementById('displayid_'+index).innerHTML = displayid;
and change the input tag to div tag. You might want to read more about innerHTML.

button radio wont stay checked after update Wordpress

I m trying to implement query with custom fields on my local wordpress website.
All works like a charm except when I check the radio button, this one want to be checked...
Can you help me please ? thanks for your reply.
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
$field = get_field_object($key);
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="radio"]', function(){
var url = '';
args = {};
$('#archive-filters .filter').each(function(){
var filter = $(this).data('filter'),
vals = [];
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
})(jQuery);
</script>

php How can I add additional selected items to an array

I am having problems with a list box that is set to multiple.
My setup is 3 individual list boxes, Categories(single select), Jobs(single select), and Tasks(multiple select)
When a users selects one item in Categories an ajax request populates the Jobs list box.
when a user selects one item from Jobs an ajax request populates the tasks box with one or more pre-selected items, plus the un-selected items.
All this works well my problem araises when I try to select additional items in tasks the pre selected items clear. I need the pre selected items to remain selected and be able to select additional items. I am using a function to select the additional item and refresh the tasks list box so that I do not have to press ctrl when selecting an item.
Here is my html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<?php
session_start();
include('dbcon/dbconnect.php');
$con=mysqli_connect($host,$user,$password,$db);
?>
<script>
function getSelectedItems(){
var items = "";
var frm = document.forms[0].s1;
var len = frm.length;
for(i=0;i<len;i++){
if(frm[i].selected){
items += frm[i].value + "~";
}
}
alert(items);
}
$(document).ready(function(){
$("select#cat").change(function(){
var cat_id = $("select#cat option:selected").attr('value');
$("#job").html( "" );
if (cat_id.length > 0 ) {
parent.top.$("#jobbtn").val("Change Category");
$.ajax({
type: "POST",
url: "fetch_jobs.php",
data: "cat_id="+cat_id,
cache: false,
beforeSend: function () {
$('#job').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#job").html( html );
}
});
}
});
$("select#job").change(function(){
var job_id = $("select#job option:selected").attr('value');
invid = 0;
$("#task").html( "" );
if (job_id.length > 0 ) {
$.ajax({
type: "GET",
url: "1a.php",
data: "job_id="+job_id+"&invid="+invid,
cache: false,
beforeSend: function () {
},
success: function(html) {
$("#task").html( html );
var selected = $("#task").val();
}
});
}
});
});
function getnotes(){
}
</script>
</head>
<body>
<form id="form1" >
<select id="cat" size="12" style='font-style:arial;font-size:14px;'>
<?php
$result = mysqli_query($con, "SELECT CatID, Catagory FROM catagory ORDER BY Catagory");
while($row = mysqli_fetch_array($result))
{
echo "<option value=\"".$row['CatID']."\">".$row['Catagory']."</option>\n ";
}
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:0px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='jobl' style='position:fixed;left:180px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933 ;width:340px;height:20px;'>Jobs</span></div>";
echo "<select name='job' id='job' size='12' style='position:fixed;left:180px;top:23px;width:340px;font-size:14px;font-family:Arial;' onchange='' >";
echo "<option value='' ></option>";
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='taskl' style='position:fixed;left:535px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933;width:335px;height:20px;'>Tasks</span></div>";
echo "<select name='task' id='task' size='12' style='position:fixed;left:535px;top:23px;width:335px;font-size:14px;font-family:Arial;' onchange='getnotes()' multiple>";
echo "<option value='' ></option>";
echo "</select>";
echo "<input type='submit' id='taskb' name='taskb' style='position:fixed;top:330px;left:700px;width:150px;height:60px;font-size: 22px;font-weight: bold;white-space:normal;background:Lime;' value= 'Add Task->' onclick='shofinal();'></form></div>";
echo "</form>";
?>
<script>
(function() {
var selected = {};
$('select#task').click(function(e) {
var $this = $(this),
options = this.options,
option,
value,
n;
// Find out what option was just added
value = $this.val();
// Re-apply the selections
for (n = 0; n < options.length; ++n) {
option = options[n];
if (option.value == value) {
// The one being updated
selected[value] = !selected[value];
}
// One of the others
option.selected = !!selected[option.value];
}
});
})();
</script>
</body>
</html>
I believe my problem is in the script at the end of the html but I am unsure of what to change to fix this.
I have finally gotten this worked out thought I would post what fixed it for others to see/use
I added this jquery to the $(document).ready(function()
and now pre selected items stay selected and newly selected items are selected or if I click an item that is already selected it becomes unselected. I am pretty sure I understand what is happening here though I can not put it into words. But it works and I guess that is whats important.
I also removed the script from the end of the original html and everything is good so far.
Works in FF
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
// toggle selection
if (el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}

Add / Update Custom Fields After Select Pictures in Media Window (Wordpress)

I have a question about wordpress, I just added a button called Add Slider in Add/Edit Post Page.
here's my code in my function.php :
//Add button to create slider
add_action('media_buttons','add_my_media_button',15);
function add_my_media_button(){
echo 'Add Slider';
}
function include_media_button_js_file(){
wp_enqueue_script('media_button',get_bloginfo('template_directory').'/js/media_button.js',array('jquery'),'1.0',true);
}
add_action('wp_enqueue_media','include_media_button_js_file');
and this my media_button.js code
jQuery(function($){
$(document).ready(function(){
$('#insert-my-media').click(open_media_window);
})
function open_media_window(){
if (this.window === undefined) {
this.window = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
var self = this; //needed to retrieve the function below
this.window.on('select',function(){
var files = self.window.state().get('selection').toArray();
var values;
for (var i = 0; i < files.length; i++) {
var file = files[i].toJSON();
if(values===undefined){
var values = file.url;
}
else{
var values = values+','+file.url;
}
};
wp.media.editor.insert(values);
});
}
this.window.open();
return false;
}
});
after user select the pictures in media window and press Insert button it will add url value of pictures to content editor post box.
My question is how to add this value automatically on custom fields box and add/update that automatically without click add custom field button.
So user can add / update custom fields for that pictures url without view/ check custom fields to view in post editor on Screen Options in wordpress.
Please help me for this question, Thanks.
I modify my jquery / js like this..
$(document).ready(function(){
// $('#insert-my-media').click(open_media_window);
if($('#images_id').val() != '' && $('#images_url').val() != ''){
$('#open_media').text("Edit Slider");
}
$('#open_media').click(function(e){
e.preventDefault();
var target = $('#images_id');
var target_url = $('#images_url');
var btnSave = $('#publishing-action input.button');
if(target.val() == '' && target_url.val() == ''){
var wpmedia = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
wpmedia.on('select', function(){
var ids = [];
var urls = [];
var models = wpmedia.state().get('selection').toArray();
for (var i = 0; i < models.length; i++) {
var file = models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Adding...");
btnSave.click();
});
wpmedia.open();
}else{
wp.media.gallery
.edit('[gallery ids="'+ target.val() +'" urls="'+ target_url.val() +'"]')
.on('update', function(g){
var ids = [];
var urls = [];
for (var i = 0; i < g.models.length; i++) {
var file = g.models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Editing...");
btnSave.click();
});
}
});
$('#save_desc').click(function(e){
e.preventDefault();
var target = $('#desc_editor');
var btnSave = $('#publishing-action input.button');
target.val(target.val());
btnSave.click();
});
$('#delete_slider').click(function(e){
e.preventDefault();
/*var target = $('#images_id');
var target_url = $('#images_url');*/
var btnSave = $('#publishing-action input.button');
/*target.val("");
target_url.val("");*/
$('#deleting_slider').val("Deleting...");
$('#delete_slider').text("Deleting...");
btnSave.click();
});
});
and then I make file called metabox.php to create metabox
<?php
function koplan_add_metabox(){
add_meta_box(
'koplan_metabox_gallery',
'Slider Gallery',
'koplan_show_metabox',
'post'
);
}
function koplan_add_maps_metabox(){
add_meta_box(
'koplan_metabox_maps',
'Maps Descriptions',
'koplan_show_maps_metabox',
'post'
);
}
function koplan_show_metabox($post){
$ids = get_post_meta($post->ID, 'gallery_images', true);
$urls = get_post_meta($post->ID,'images',true);
?>
Add Slider
<hr>
<input type="hidden" name="gallery_images" id="images_id" value="<?php echo $ids; ?>">
<input type="hidden" name="gallery_urls" id="images_url" value="<?php echo $urls; ?>">
<input type="hidden" name="deleting_slider_post_meta" id="deleting_slider" value="<?php echo $urls; ?>">
<?php
if($ids=="" and $urls==""){
return;
}
else{
echo do_shortcode('[gallery ids="'.$ids.'" urls="'.$urls.'"]');
}
?>
<hr>
Delete Slider
<?php
}
function koplan_save_gallery_metabox($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if(! isset($_POST['gallery_images']) && !isset($_POST['gallery_urls'])){
return;
}
$ids = sanitize_text_field( $_POST['gallery_images'] );
$urls = sanitize_text_field( $_POST['gallery_urls'] );
$terms = wp_get_object_terms( $post_id, 'category', array( 'fields' => 'names' ) );
/*$termsname = $terms[0]->name;*/
if(strlen($terms[1]) > strlen($terms[0])){
$term = $terms[1];
}
else{
$term = $terms[0];
}
$sldata = '<slider images="'.$term.'" />';
update_post_meta($post_id, 'slider', $sldata);
update_post_meta($post_id, 'gallery_images', $ids);
update_post_meta($post_id, 'images', $urls);
if(isset($_POST['deleting_slider_post_meta']) && $_POST['deleting_slider_post_meta'] != ""){
delete_post_meta($post_id, 'slider', $sldata);
delete_post_meta($post_id, 'gallery_images', $ids);
delete_post_meta($post_id, 'images', $urls);
}
}
function koplan_show_maps_metabox($post){
$desc = get_post_meta($post->ID,'mapsdesc',true);
if($desc!=""){
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"><?php echo $desc; ?></textarea>
<?php
}else{
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"></textarea>
<?php
}
?>
<hr>
Save
<?php
}
function koplan_save_maps_desc_metabox($post_id){
if (define('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if(!isset($_POST['maps_descriptions'])){
return;
}
$desc = $_POST['maps_descriptions'];
update_post_meta($post_id,'mapsdesc',$desc);
}
add_action( 'add_meta_boxes', 'koplan_add_metabox' );
add_action('add_meta_boxes','koplan_add_maps_metabox');
add_action( 'save_post', 'koplan_save_gallery_metabox' );
add_action( 'save_post', 'koplan_save_maps_desc_metabox' );
?>
I said problem solved, case closed. Thanks all, thanks stackoverflow

Categories

Resources