Autocomplete input field not working in bootstrap tabs - javascript

I am working on a web development project and I am using bootstrap tabs there. I am dynamically creating them using add and remove input field section, according to that number of inputs I am creating the tabs in the same page using ajax.
In that tabs I have the same form with same input fields. There is a input field with autocomplete function in that form. I am taking data from mysql to that field. My problem is autocomplete is only working in the first tab not in the others. Autocomplete field label is Responsible
This is my function.
function autocompletT() {
var min_length = 0;
var keyword = $('#responsible_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh2.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#responsible_id_list').show();
$('#responsible_id_list').html(data);
$('#responsible_id_list li').click(function() {
var txx = $(this).text();
var tcust = $(this).val();
});
}
});
} else {
$('#responsible_id_list').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#responsible_id').val(item);
// hide proposition list
$('#responsible_id_list').hide();
}
Portion of My code
<div class="col-md-6 entire_div">
<div class="panel with-nav-tabs panel-primary">
<div class="panel-heading">
<ul class="nav nav-tabs">
<?php
for ($row = 0; $row < $agenda_size; $row++) {
$p_agenda = $mAgenda[$row];
$row_plus = $row + 1;
?>
<li><?php echo $p_agenda; ?></li>
<?php
}
?>
</ul>
</div>
<div class="panel-body">
<div class="tab-content">
<?php
for ($row = 0; $row < $agenda_size; $row++) {
$p_agenda = $mAgenda[$row];
$row_plus = $row + 1;
?>
<div class="tab-pane fade" id="<?php echo $row_plus;?>">
<!-- form -->
<form class="ws-validate">
<div class="form-group">
<label for="responsible_id" class="control-label">Responsible</label>
<input type="text" class="form-control" id="responsible_id" name="zip" placeholder="Select Responsible Person" onkeyup="autocompletT()" >
<ul id="responsible_id_list"></ul>
</div>
<div class="form-group">
<button id="submit_btn" class="btn btn-primary">Add</button>
<!-- <input id="submit_btn" type="submit" value="Add"> -->
</div>
</form>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="mytable" class="table table-bordred table-striped">
<thead>
<th><input type="checkbox" id="checkall" /></th>
<th>Action</th>
<th>Start Date</th>
<th>Due Date</th>
<th>Status</th>
<th>Responsible</th>
</thead>
<tbody>
</tbody>
</table>
<div class="delete_b_class">
<button id="delete_row" class="btn btn-danger">Delete Row</button>
</div>
</div>
</div>
</div>
<div class="submit_all_div">
<input class="submit_all_b" id="submit" onclick="myDataSendFunction()" type="button" value="Submit">
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>

ids are unique
Each element can have only one id
Each page can have only one element with that id
classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Probably, you are creating so many #responsible_id and #responsible_id_list with your php code.
So, as IDs must be unique. use the a unique ID for each search field (which is responsible_id ) and list (which is responsible_id_list ) here.
You can get a idea from here:- remove onkeyup="autocompletT" function from the input and add jquery event like this. then find the next responsible_id_list then populate list and append list to it.
$('.responsible_id').keyup(function(){
var min_length = 0;
var keyword = $(this).val() ;
///others codes
//say
var list='';
$(this).next('.responsible_id_list').html(list);
})

You might need to re-initialize the autocomplete on the inputs every time. Go through this question to get a braoder picture. This should solve your concerns

Related

Trying to pass data from a database into a bootstrap modal when opened. How do I go about doing this?

I'm trying to pass data from my database into a modal form. The purpose of this modal is so users can edit their data within the database and then save the changes to said data.
I've tried many tutorials on YouTube, as well as reading previous responses on this site using methods such as doing it through Ajax and Bootstrap Modal Event Listener & Ajax and jQuery Click function but due to my inexperience with these programming languages I've yet to understand as the examples are vastly different to my project. Below is my code for form as well as the tables in my database
Button used to open the modal:
<a class="badge badge-success p-2" role="button" data-toggle="modal" data-target="#editPostModal">Edit</a>
Modal:
<div class="modal fade" id="editPostModal" tabindex="-1" role="dialog"aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Update Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="editdata.inc.php" method="POST" enctype="multipart/form-data"> // PHP File I would like to use to run a possible "update" query
<div class="modal-body">
<div class="form-group">
<input type="text" name="themeContent" class="form-control" placeholder = "Enter theme"/>
</div>
<div class="form-group">
<input type="text" name="visualIdeaContent" class="form-control" placeholder = "Enter idea"/>
</div>
<div class="form-group">
<input type="text" name="captionContent" class="form-control" value="<?= $captionContent; ?>" placeholder = "Insert caption"/>
</div>
<div class="form-group">
<input type="date" name="dateContent" class="form-control" placeholder = "Select date"/>
</div>
<div class="form-group">
<input type="text" name="linkContent" class="form-control" placeholder = "Insert URL"/>
</div>
<div class="form-group">
<input type="file" name="visualContent" class="custom-file" placeholder = "Upload picture"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="submit" name="editdata" class="btn btn-primary">Save Changes</button>
</div>
</form>
</div>
</div>
Database
Name: annexcms
Table: content
uidContent // Unique ID
themeContent
visualIdeaContent
captionContent
dateContent
linkContent
visualContent
All in all, I expect the modal to:
1) Open and display data from the database tied to a specific User ID
2) Have the ability to save any changes made to that data when clicking the "Save Changes" button.
3) Have the saved data updated in the database.
This is the last part of my CRUD application as I've mastered the other three features. Appreciate any help I can receive.
You need 2 controller methods:
public function respondData($id)
{
//you can ever check if id exist here or if exist at all and
//throw any exeptions if not exist, this is just example
if($checkUser->exist($id))
{
$userData = array('id' => '1, 'name' => 'Name');
return json_encode($data);
}
throw new \Exeption('User does not exist');
}
public function saveData()
{
if($_POST)
{
if(($checkUser->exist($_POST['id'])))
{
//get value from POST and check and update
return true; // or message and parse it if it was ajax request
}
}
throw new \Exeption('Method not allowed');
}
JQUERY:
You need to get data from your user and bind it to modal
You can do this this way:
add data-user to you button or a link and other method to trigger modal opening:
$(document).on('click', '#your-link', function () {
var data = $(this).data('user');
$.post({
url: 'url_to_first_action' + '?id=' + data,
data: data,
success: function(data){
//here you parse JSON ARRAY to your fields
},
});
});
Now after user submit you data to second action you can do this with straight POST request or use the ajax to serialize() post.
So after tinkering with previous code, I got this to work.
My table:
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Theme</th>
<th>Visual Idea</th>
<th>Caption</th>
<th>Date</th>
<th>Visual</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$table = mysqli_query($conn ,'SELECT * FROM content');
while($row = mysqli_fetch_array($table)){ ?>
<tr id="<?php echo $row['uidContent']; ?>">
<td width="200" data-target="themeContent"><?php echo $row['themeContent']; ?></td>
<td width="300" data-target="visualIdeaContent"><?php echo $row['visualIdeaContent']; ?></td>
<td width="600" data-target="captionContent"><?php echo $row['captionContent']; ?></td>
<td width="100" data-target="dateContent"><?php echo $row['dateContent']; ?></td>
<td width="200" data-target="visualContent"><img id="imgsrc" src="<?php echo $row['visualContent']; ?>"width="200"/></td>
<td style = "display:none" width="100" data-target="linkContent"><?php echo $row['linkContent']; ?></td>
<td width="170">
<a class="badge badge-primary p-2" role="button" href="<?php echo $row['linkContent']; ?>" target="_blank">Link</a>
<a class="badge badge-success p-2" href="#" data-role="update" data-id="<?php echo $row['uidContent'] ;?>">Edit</a>
<a class="badge badge-danger p-2" role="button" href="action.inc.php?delete=<?php echo $row['uidContent'] ;?>" onclick="return confirm('Are you sure you want to delete this post? This process cannot be undone.');">Delete</a>
</td>
</tr>
<?php }
?>
</tbody>
</table>
The script:
<script>
$(document).ready(function(){
// Gets values in input fields
$(document).on('click','a[data-role=update]',function(){
var id = $(this).data('id');
var themeContent = $('#'+id).children('td[data-target=themeContent]').text();
var visualIdeaContent = $('#'+id).children('td[data-target=visualIdeaContent]').text();
var captionContent = $('#'+id).children('td[data-target=captionContent]').text();
var linkContent = $('#'+id).children('td[data-target=linkContent]').text();
var dateContent = $('#'+id).children('td[data-target=dateContent]').text();
var visualContent = $('#'+id).children('td[data-target=visualContent]').text();
$('#themeContent').val(themeContent);
$('#visualIdeaContent').val(visualIdeaContent);
$('#captionContent').val(captionContent);
$('#dateContent').val(dateContent);
$('#linkContent').val(linkContent);
$('#visualContent').val(visualContent);
$('#uidContent').val(id);
$('#updatePostModal').modal('toggle');
});
});
</script>
The only issue is that I'm not getting the image path to display as a thumbnail in the form, but I'll figure it out on my own through research.
My code is ugly, but at this point, I'm more concerned about the functionality. Thanks everyone.

How do I insert Data Into database with many Input which has same name?

hello friends I have a form field in which I want to insert data which has four field which are customer_id , field_name1 ,field_name2, field_name3 ,
The question is I want to insert data which has many inputs but same input name like field_name1 field_name2 field_name3 , firstly there is no input but when I click on a button add partner details then these inputs shows by javascript .
like field_name1,field_name2,field_name3 ten times can repeat , I want to insert data in database according to there numbers with same customer_id , but different field name , below is my code , hope you understand it .
here is my code
<?php
$conn=mysqli_connect("localhost","root","","satya");
if(isset($_POST['submit'])){
$customer_id=$_POST['customer_id'];
for ($ix=0; $ix<count($_POST['field_name1']); $ix++)
{
$field_data = array(
'field_name1' => $_POST['field_name1'][$ix],
'field_name2' => $_POST['field_name2'][$ix],
'field_name3' => $_POST['field_name3'][$ix],
);
$sql="INSERT INTO customer(customer_id,details1,details2,details3) VALUES('$customer_id','$field_name1','$field_name1','$field_name1')";
$result=mysqli_query($conn,$sql);
if($result){
echo "data has been inserted";
}
else{
echo "data could not be inserted";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="" method="post">
<div class="form-group">
<div class="row" style="margin-top: 20px">
<div class="col-md-4" ></div>
<div class="col-md-4">
<label for="customer_id">Customer ID </label>
<input type="text" class="form-control" name="customer_id" placeholder="customer_id">
</div>
<div class="col-md-4"></div>
</div>
<div class="row" style="margin-top: 20px;">
<div class="col-md-3">
<label for="details1">details1 </label>
</div>
<div class="col-md-3">
<label for="details2">details2</label>
</div>
<div class="col-md-3">
<label for="details3">details3</label>
</div>
<div class="col-md-3">
<div>
Add Partner Details
</div>
</div>
<div class="partner_wrapper" >
</div>
</div>
<div class="col-md-4"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
<div class="col-md-4"></div>
</form>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
<script>
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_partner'); //Add button selector
var wrapper = $('.partner_wrapper'); //Input field wrapper
var fieldHTML = '<span class="row"><div class="col-md-3"><input type="text" class="form-control" name="field_name1[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name2[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name3[]" value=""/></div><button type="button" href="javascript:void(0);" class="remove_button btn btn-primary" title="Remove field">Remove</button></span>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('span').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
Give the repeating fields array-style names:
<input type="text" name="field_name1[]">
PHP will collect the inputs into arrays, so $_POST['field_name1'] will be an array. Then you can loop over them:
foreach ($_POST['field_name1'] AS $index => $field1) {
$field2 = $_POST['field_name2'][$index];
$field3 = $_POST['field_name3'][$index];
// now you can insert all these values into the DB
}

vue.js input search to find username in dynamic in users list

I made an input search to filter a list of users that is called with PHP. I'm trying to implement in Vue.js the filter so that when I search the name, the user appears filtered in the list.
Here is the searchbar HTML:
<div class="row" id="toprow">
<div class="col-md-6">
<div id="titlerow1">Users</div>
</div>
<div class="col-md-6">
<input class="searchbar" id="search1" placeholder="Search..."></input>
</div>
</div>
The users list HTML:
<div id="users" name="users">
<?php if(!empty($user))
{
foreach($user as $value)
{
?>
<div class="row oddEven usersElements userid" id=<?php echo $value->id;?> style="margin-top: -1vw;">
<div v-on:click="displayAgregators(<?php echo $value->id;?>)" class="col-md-10">
<span id="items<?php echo $value->id;?>"><?php echo ucfirst($value->username);?></span>
</div>
<div class="col-md-2">
<div class="colorsByUser" :style="{backgroundColor: randomColor()}"></div>
</div>
</div>
<?php }
}?>
</div>
Before it was in jQuery, here is the code:
$('#search1').keyup(function() {
var string1 = $(this).val().toLowerCase();
console.log("str1=" + string1);
$(".usersElements").each(function(index) {
var string = $(this).attr('id');
var string2 = $('#' + string).text().toLowerCase();
console.log("str2=" + string2);
var valtest = string2.indexOf(string1);
console.log("index value:" + valtest);
if (valtest >= 0) {
$('#' + string).show();
} else {
$('#' + string).hide();
}
});
});
I hope you guys can help! :)
Since you're stuck with PHP generating stuff, probably the best you can do is make each row a component. The HTML will look about like this:
<div id="users" name="users">
<?php if(!empty($user)) {
foreach($user as $value) {
?>
<user-component
name="<?php echo ucfirst($value->username);?>"
id="<?php echo $value->id;?>"
:match-pattern="searchPattern"
></user-component>
<?php }
}
?>
</div>
The template for your component will look about like this:
<div v-show="matches()" class="row oddEven usersElements userid" style="margin-top: -1vw;">
<div v-on:click="displayAgregators(id)" class="col-md-10">
<span>{{name}}</span>
</div>
<div class="col-md-2">
<div class="colorsByUser" :style="{backgroundColor: randomColor()}"></div>
</div>
</div>
and it will take three props: name and id come from the PHP stuff, while match-pattern comes from your parent Vue. it will have a method (or a computed) that tests whether it matches the pattern. Something like
matches() {
return this.name.toLowerCase().includes(this.matchPattern);
}
Your search bar should have v-model="searchPattern", and you should of course define a searchPattern variable in your Vue.

knockout - cannot apply bindings multiple times to the same element

I need to fill my trip table with data from two sources: from server using GET when the page loads (to have user's archive trips) and from observable values (when a user adds a new trip). Can I somehow merge those two scripts so that they apply bindings only once? Right now I get an error: You cannot apply bindings multiple times to the same element
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Add a trip</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="from">From</label>
<input type="text" class="form-control" id="from" name="from" placeholder="From" data-bind="value: from">
</div>
<div class="form-group">
<label for="to">To</label>
<input type="text" class="form-control" id="to" name="to" placeholder="To" data-bind="value: to">
</div>
<a class="btn btn-primary btn-lg" role="button" data-bind="click: add()" >Add</a>
</div>
</div>
<div class="panel panel-default">
<div class=panel-heading>Your trips</div>
<table class=table>
<thead>
<tr>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody data-bind="foreach: records">
<tr>
<td data-bind="text: from"></td>
<td data-bind="text: to"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="js/knockout-3.4.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var AppViewModel = function() {
this.from = ko.observable();
this.to = ko.observable();
this.records = ko.observableArray();
};
var model = new AppViewModel();
model.add = function() {
model.records.push({
from: model.from(),
to: model.to()
});
//sending data to server
var data =
{
from : this.from(), to : this.to(), date : this.date(), price : this.price(), freeSeats : this.freeSeats()
}
alert(data);
$.post("/data", data, function(response)
{
})
}
ko.applyBindings(model);
</script>
<script>
function tripModel() {
this.records = ko.observableArray([]);
$.getJSON("/usersTrips", function(data) {
self.records(data);
})
}
ko.applyBindings(new tripModel());
</script>
Give the relevant elements IDs and then apply the models to only those DOM elements. For example,
Html:
<div id="add-trip" class="panel panel-default">
<div id="your-trips" class="panel panel-default">
And the binding:
ko.applyBindings(model, document.getElementById("add-trip"));
ko.applyBindings(new tripModel(), document.getElementById("your-trips"));
JSFiddle Example:
https://jsfiddle.net/hellobrett/49xaqj46/1/
JSFiddle example going the other direction:
https://jsfiddle.net/hellobrett/49xaqj46/2/
Reference:
http://knockoutjs.com/documentation/observables.html
In case you’re wondering what the parameters to ko.applyBindings do,
The first parameter says what view model object you want to use with the declarative bindings it activates
Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.applyBindings(myViewModel, document.getElementById('someElementId')). This restricts the activation to the element with ID someElementId and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.

How do I change the input name in jQuery

This is what I am currently trying to achieve:
I am trying to clone a form and change the input name. How would I pull this off.
JS:
$(document).ready(function() {
var counter = 0;
var MAX_FIELDS = 3;
var MIN_FIELDS = 1;
var form = $('.force-group');
$('#add').on('click', function(e) {
if (counter < MAX_FIELDS) {
//$(".form-group").clone().appendTo("#forceForm");
$.each(form, function(i) {
var clone = $('.force-group').first().clone();
clone.children().val("");
$(this).parent().append(clone);
if (counter == 0) {
$("b:eq(1)").html("<b> Force 2</b>");
};
if (counter == 1) {
$("b:eq(3)").html("<b> Force 3</b>");
};
if (counter == 2) {
$("b:eq(5)").html("<b> Force 4</b>");
};
});
counter++;
};
});
html:
<#import "template.ftl" as layout />
<#layout.template title="Force" js="/js/force.js" css="/css/force.css">
<h3 class = "text-center">Total Force</h3>
<hr>
<div class="col-md-6 col-md-offset-3 col-xs-8 col-xs-offset-2">
<div class="force-selector input_fields_wrap">
<a id = 'add' href="#" class="btn btn-primary col-md-5">Add Force</a>
<a id = 'remove' href="#" class="btn btn-warning col-md-5 col-md-offset-2">Remove Force</a>
</div>
</div>
<div class="col-md-6 col-md-offset-">
<div class="col-xs-12">
<div class = "well" id="force-input">
<form id = "forceForm" class = "form-horizontal" method = "POST" autocomplete="off">
<fieldset>
<h4 class="text-center" id="form-title"><strong>Input</strong></h4>
<div class="form-group force-group">
<label class = "control-label col-md-2"><b>Force 1</b></label>
<label class = "control-label col-md-2">Magnitude</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0force" autocomplete="off">
</div>
<label class = "control-label col-md-2">Angle</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0angle" autocomplete="off">
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class = "col-md-5">
<table id = "forceChart" class="table table-striped table-hover">
<thead>
<tr class="table">
<th class="head-pad">Total Force</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td class="pad">Net Force:</td>
</tr>
</tbody>
</thead>
<tbody>
<tr class="table">
<td class="pad">Direction:</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class = "col-md-4 col-md-offset-4 col-xs-6 col-xs-offset-3">
<div class="form-group">
<div class = "col-md-6 col-xs-offset-3">
<input id = "calculate" class = "btn btn-success btn-block" type="submit" value="Calculate!">
</div>
</div>
</div>
This is the jsfiddle link right here:
Click here for the link.
PS: I am using a templater so the jsfiddle will look kinda bad.
I am new to jQuery and I have been searching around a solution but I seem to get stuck with it.
I tried using the .last() with the attr edit but that seems not to do anything.
To change an input name just use attr() method
$('input').attr('name', 'yourNewname');
and I remarque that you have input without Id so you should use one of those methods:
1/ give each input an Id for example #input1 #input2
$('#input1').attr('name', 'yourNewname1'); // change the name of first input
$('#input2').attr('name', 'yourNewname2'); // change the name of first input
or
you can use eq()
$('input').eq(0).attr('name', 'yourNewname1'); // change the name of first input
$('input').eq(1).attr('name', 'yourNewname2'); // change the name of first input
To change any attribute including name you can do this
$('#myInputFieldId').attr('name','new_name')
Hope it helps
Try this: $('input[name="0angle"]').attr('name', 'new-name');

Categories

Resources