How to insert autocomplete jquery in innerhtml generated textbox - javascript

The autocomplete jquery shows list of all users in the database, when atleast 2 characters are entered in the textbox. The autocomplete is working on a normal input field, but when genereated through innerHTML it is not working.
The autocomplete is working on the following field:-
<input type="text" id="j_d_permit_by[]" name="j_d_permit_by[]" >
A click on the button will add other fields as well calling the addjobdesc function:-
<img src="images/add.png" width="12" height="12"> Add New Job Description<br />
The function:-
function addjobdesc() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<table id="tblObs" name="tblObs" width="70%" bgcolor="#CCCCCC"><tr bordercolor="#FFFFFF">
<td colspan="5"><b>Job Description (Work Ppermit/ Activity)</b></td></tr>
<tr bgcolor="#33CC00">
<td ><center> <b>Exact Location</b> </center></td> <td><b><center>Permit Initiated By<br />/<br />Activity Supervised by</center></b></td>
<td><b><center>Permit Accepted By<br />/<br />aActivity Executor</center></b></td><td><b><center>For What Permit Issued</center></b></td>
<td><b><center>Observation</center></b></td></tr>
<tr><td><center><select name="s_area[]" id="s_area" onchange="addSubArea()">
<option value="0">Chose Sub Area</option></select></center></td>
<td><input type="text" id="j_d_permit_by_add" name="j_d_permit_by[]"></td>
<td><center><select id="j_d_accept_by[]" name="j_d_accept_by[]" ><option value="0">Select User</option><?php $users = getUserS();
while($usersss = mysql_fetch_array($users)){ ?>
<option value="<?php echo $usersss[0];?>"><?php echo $usersss[4]." ".$usersss[5]; ?></option>
<?php } ?>
</select></td>
<td><center><textarea name="permit_ref[]" cols="30"> </textarea></center></td>
<td><center><textarea name="obs_permit[]" id="obs_permit" cols="30"></textarea></center></td></tr></table><input class="submit" type="button" value="Remove" onclick="removeR0ow__(this)">';
<!--<input type="hidden" name="j_d_Location[]" id="j_d_Location" value="" /><input type="text" name="area_Location[]" id="area_Location" value="" readonly="readonly" />-->
document.getElementById('job_desc').appendChild(div);
jQuery(document).ready(function(){
$('#j_d_permit_by_add').autocomplete({
source: 'suggest_name.php',
minLength:2
});
});
var Max_Length = parseInt(document.getElementsByName('s_area[]').length)-1;
document.getElementsByName('s_area[]').item(Max_Length).innerHTML = '';
document.getElementsByName('s_area[]').item(Max_Length).innerHTML = document.getElementById('sarea_div').innerHTML;
}
I want the autcomplete to work on the generated j_d_permit_by[] field in the innerHTML.
Really appreciate your help.

You have bind the autocomplete in jQuery(document).ready but at that time there is no input exists with id =j_d_permit_by_add and hence the function is not bind to the input. You are generating the input dynamically so you have to bind autocomplete function in following way..
Try this to Bind the autocomplete function:
jQuery(document).ready(function(){
$(document).on('#j_d_permit_by_add', selector, function() {
$(this).autocomplete({
source: 'suggest_name.php',
minLength:2
});
});
});
You can refer https://stackoverflow.com/a/25114244/1659563
#Guruprasad is also right, you can bind the autocomplete function after the input is generated dynamically in function addjobdesc()

Related

How do i clear input,select and textarea fields after cloning

i'm create form for expose item i want fresh text field. when user click button ADD
function fncAdd() { //ADD ROW AND CLONE
var tb = document.getElementById('tbl');
var tbody = document.createElement('tbody'); // fixed IE :>
tb.insertBefore(tbody, null);
var clone = document.getElementById('cln').cloneNode(true);
tbody.insertBefore(clone, null);
}
function fncDelete() { //DELETE ROW
var tb = document.getElementById('tbl');
var del = tb.rows.length;
if (del > 1) {
tb.deleteRow(del - 1);
}
}
<tr id="cln"> //CALL CLONE FUNCTION
<div align="center">1</div>
</td>
<?php //CONNECT DATABASE
include 'dbConfig.php';
$query = $db->query("SELECT * FROM accountcode ORDER BY acc_id ASC ");
$rowCount = $query->num_rows;
?>
<td>
<select id="accountcode"> //DROPDOWN 2ND BY AJAX
<option value=""> - - Please select - - </option>
<?php
if($rowCount > 0){
while($row=$query->fetch_assoc()){
echo '<option value="'.$row['acc_id'].'">'.$row['acc_name'].'</option>';
}
}else{
echo '<option value="">Accountcode not available</option>';
}
?>
</select>
</td>
<td>
<select id="item"> //DROPDOWN 2ND BY AJAX
<option value=""> - - Select accountcode first - -</option>
</select>
</td>
<td> //DETAIL BOX
<textarea rows=4 cols=25 class="txtDETAIL" maxlength="100"> </textarea>
</td>
<td>
<input type="text" class="txtAMOUNT" size="5"> //AMOUNT BOX
</td>
<td>
<input type="text" class="txtUNIT" size="5"> //UNIT BOX
</td>
<td> //NOTE BOX
<textarea rows=4 cols=15 class="note" maxlength="60"> </textarea>
</td>
<td> //UPLOADFILE FOR PICTURE OR STOCK
<a href='upload.php?id={$row[' id="id" ']}'>CLICK</a>
</td>
</table>
<p>
<input type="button" value="ADD" onClick="fncAdd()"> //BUTTON ADD
<input type="button" value="DELETE" onClick="fncDelete()"> //BUTTON DELETE
</p>
I am having trouble to create text field value when user click button i want to clone function not copy old value from 1st row and column NO can auto increment
how can i do that
EXAMPLE
To clear form data you can use,
document.getElementById("form1").reset();
Your form should look like,
<form id="form1">
<input .....
</form>
Something to be aware of, is the cloned element has unique ID's (eg, append -1 etc onto the original ID).
Also, I've recently done this using jQuery, however, I used string.replace(regex, ''); instead of this method.
Oh yeah, an example to edit to suit your situation:
var element = document.getElementById('id-of-element').cloneNode(true);
element.childNodes[x].nextSibling.childNodes[y].value = '';
document.getElementById('target-element').insertBefore(element, null);
Kind regards,

Disable the inputs when checkbox not checked

I have this code and I want to disable all the inputs when the checkbox is not checked.
<tr class="select_tr">
<td><?= ucwords($food_name); ?></td>
<td class="form-group text-center">
<input value="<?= $order_food_id; ?>" type="checkbox" name="select_food[]" checked>
</td>
<td class="form-group">
<input value="<?= $order_food_total_members; ?>" type="text" name="total_members[]" class="form-control" placeholder="Total Members">
</td>
<td class="form-group ">
<input value="<?= $order_food_date; ?>" type="date" name="food_date" class="form-control">
</td>
<td class="form-group ">
<input value="<?= $order_food_time; ?>" type="time" name="food_time" class="form-control">
</td>
</tr>
I have used this code but it is disabling only the first input and I don't know how to taget the remaining two.
$('input[type="checkbox"]').click(function () {
if(!this.checked) {
$(this).closest('td').next('td').find('input:text').attr('disabled' , true);
} else {
$(this).closest('td').next('td').find('input:text').attr('disabled' , false);
}
});
Whatever you have done is partially correct, what you have done is you have targetted with $(this) so obviously it will take the checkbox input and will find the closest 'td' and disable only the first input tag because it is the one which is closest rather you can do this by targetting the element which has this form-control class and disable the event so it will apply to all the input field which has this class which is indirectly the other three input field.
$('input[type="checkbox"]').click(function () {
if(!this.checked) {
$('.form-control').attr('disabled' , true);
} else {
$('.form-control').attr('disabled' , false);
}
});
Or the second choice is you can use this each statement to update the input element.
You should be able to do something like this - get all of the elements and then disable. You'll have to do it onclick of the checkbox.
var inputs, index;
inputs = document.getElementsByTagName('input'); // get all of the input elements
for (index = 0; index < inputs.length; ++index) { // loop through them
inputs[index].disabled = true; // disable them
}
The issue is that you are only selecting a single element:
$(this).closest('td').next('td').find('input:text')
This will find the closest <td> ancestor element to the checkbox, then select the next sibling <td> element, and finally get the descendants of that <td> element that matches the selector input:text. This will result in a single element because only one of your inputs is of type "text", and you are only selecting inside of a single <td>.
What you want to do instead is select all of the input elements that are not checkboxes in the table row <tr> (class .select_tr):
$(this).closest('.select_tr').find('input:not([type=checkbox])')
This will select the parent <tr> with class .select_tr and then select all input children of it that do not have type=checkbox.
Example:
$('.select_tr input:checkbox').change(function() {
$(this).closest('.select_tr').find('input:not([type=checkbox])').prop("disabled", !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="select_tr">
<td>
<?= ucwords($food_name); ?>
</td>
<td class="form-group text-center">
<input value="<?= $order_food_id; ?>" type="checkbox" name="select_food[]" checked>
</td>
<td class="form-group">
<input value="<?= $order_food_total_members; ?>" type="text" name="total_members[]" class="form-control" placeholder="Total Members">
</td>
<td class="form-group ">
<input value="<?= $order_food_date; ?>" type="date" name="food_date" class="form-control">
</td>
<td class="form-group ">
<input value="<?= $order_food_time; ?>" type="time" name="food_time" class="form-control">
</td>
</tr>
</table>
Your code isn't selecting all the inputs. Use nextAll() for selecting each td after the closest('td').
$('input[type="checkbox"]').click(function(){
if(!this.checked){
$(this).closest('td').nextAll('td').find('input').attr('disabled' , true);
}else{
$(this).closest('td').nextAll('td').find('input').attr('disabled' , false);
}
});
JQuery.next() is used for selecting the first matched element after the selected element
So, your code is just affecting the first next only.
JQuery.nextAll() is used for select the next all matched elements after the selected element.
So, using nextAll() instead of next() may solve your problem.
You can try something like this:
var elemCheckbox = document.querySelectorAll('[type="checkbox"]')[0];
var elemInputs = document.querySelectorAll('.form-control');
function toggleInputs() {
// https://stackoverflow.com/questions/9887360/check-if-checkbox-is-checked-javascript#answer-9887439
var shallDisable = !elemCheckbox.checked;
// https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
for (i = 0, len = elemInputs.length; i < len; ++i) {
// https://stackoverflow.com/questions/7526601/setattributedisabled-false-changes-editable-attribute-to-false#answer-7526666
elemInputs[i].disabled = shallDisable;
}
}
elemCheckbox.addEventListener("click", toggleInputs);
Find the explanation in the comments.
This example won’t disable the checkbox (if you meant it like that).
I would recommend to add an id to the checkbox. This will guarantee an explicit element selection.
You can then get like document.getElementById("<yourUniqueId>");

Javascript not enabling html forms

It has been ages i don't work anything in JS, i'm trying to do with a select enable another html form when certain selected option is being chosen. this is my script:
<script>
function Activar() {
var e = document.getElementById('perm_tipo');
var strUser = e.options[e.selectedIndex].text;
if(strUser=="familiar"){
document.getElementById('paciente').disabled = false;
}else{
document.getElementById('paciente').disabled = true;
}
}
i have those html select inside a form, i think that could be the problem but checking on google seems that's should'nt be an issue.
here is my html code:
<form id="registro" action="admin_panel.php" method="post">
<table border="0">
<tr>
<td>Tipo de permiso</td>
<td>
<select name="perm_tipo" onchange="Activar()">
<?php
permiso();
?>
</select>
<br>
</td>
<td>Paciente</td>
<td>
<select id="paciente" disabled>
<?php
pacientes();
?>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Registrar usuario"/><br>
</td>
</tr>
</table>
the php functions just fill the select options with data from some database, no big deal there, they work, no problem there.
Since you are using getElementById, you should use 'id' instead of 'name' in the 'select' element.
<select id="perm_tipo" onchange="Activar()">
....
</select>
More refactor: you can pass the DOM element itself in the event listener and you don't have to do var e = document.getElementById('perm_tipo'); in the first place
<select name="perm_tipo" onchange="Activar(this)">
....
</select>
<script>
function Activar(e) {
var strUser = e.options[e.selectedIndex].text;
if(strUser=="familiar")
document.getElementById('paciente').disabled = false;
else
document.getElementById('paciente').disabled = true;
}
</script>

Select tag not working with submit button in a table

I have a table that has one <tr> and two <td> inside of it. The first <td> shows a drop-down that has a list of books that the user chooses and the second <td> has a button that will trigger a function after choosing a book. The button works fine, but the problem is that it triggers the function even when the option is set to the "Select Book" title while it is supposed to work only when the book name is chosen not the title which asking the user to select a book.
<table>
<tr>
<td>
<div class="" style="position:relative" >
<select id="test">
<option value="" disabled="disabled" selected="selected">Select Book</option>
<?php
//API calls happening to get the list of books
?>
<option value="<?php //echo id of each book; ?>"><?php //echo name of books ?></option>
</select>
</div>
</td>
<td>
<input type="submit" value="Add to Cart" onclick="addBook()">
</td>
</tr>
</table>
here is the javascript I am running on clicking on the button.
function addBook() {
//getting product name and append it in the report table
var BookName = $("#test option:selected").text();
var tr = "<tr><td>" + BookName + "</td></tr>";
$("#SecondTable").append(tr);
}
So as you can see with the above JS, I will also print "Select Book" as it is assuming that "Select Book" is a book name!
You can check first if the option selected is disabled, then attempt to load the view, please check your function i have edited...
function addBook() {
//getting product name and append it in the report table
var selectedbook = $("#test option:selected");
if(!selectedbook.is(":disabled"))
{
var BookName = selectedbook.text();
var tr = "<tr><td>" + BookName + "</td></tr>";
$("#SecondTable").append(tr);
}
}
<option disabled="disabled">foo</option> makes it so that value is not selectable. It does not stop you from submitting the form.
If you want to validate a form before submitting, write a validation function that you execute in the onsubmit of the form. You can find many examples on how to do this if you search for "form validation".
Also keep in mind that the disabled option is merely a suggestion. A user of your form can still submit any value they like (even bypass your validation function). Validation must take place on the server. Whatever else you do in HTML is nice to have.

how to display html form using JavaScript

I have a form to enter the skills of an employee and below the form there is a link to add new skill.when clicking on the link the form has to be display again.
i have written code like this
<html>
<head>
<script type="text/javascript">
function newStyle()
{
document.getElementById('add').innerHTML="<html><body><table>
<tr>
<td>Skill</td><td><select name="skill">
<option>Select</option>
</select></td>
<td>percentage of knowledge</td>
<td><input type="number" name="percentage" min="1" max="100"/></td>
<td>No of years experience</td>
<td><input type="text" name="no_years_experience"></td>
<td>Highest level </td><td><select name="highest_level">
<option>Select</option>
</select></td>
</tr>
</table>
</body></html>";
}
</script>
</head>
<body>
<table>
<tr>
<td>Skill</td><td><select name="skill">
<option>Select</option>
</select></td>
<td>percentage of knowledge</td>
<td><input type="number" name="percentage" min="1" max="100"/></td>
<td>No of years experience</td>
<td><input type="text" name="no_years_experience"></td>
<td>Highest level </td><td><select name="highest_level">
<option>Select</option>
</select></td>
</tr>
</table>
<a onclick="newStyle()" >Add New Skill</a>
<div id="add"></div>
</body>
</html>
here the form do not display when i click the Add new skill .Can anybody help me to display the form
You have the following issues
JS Strings cannot have newlines. Although it is possible to change all newlines to nothing or escape the newline with \ it is not recommended and in here not necessary as you will see
If your string contains double quotes, you need to wrap it in single quotes or escape the double quotes \" but in your case we can simply clone your table
I gave your table an ID and the anchor an href and ID too
Plain JavaScript version - expects the source table to be wrapped in a container
Live Demo
window.onload=function() {
var srcTable = document.getElementById("srcDiv").innerHTML;
document.getElementById("addBut").onclick=function() {
document.getElementById("add").innerHTML += srcTable; // note append is +=
return false; // stop the click
}
}
jQuery version:
Live Demo
$(function() {
var $skillTable = $("#skilltable").clone(); // make a copy
$("#addBut").on("click",function(e) {
e.preventDefault();
$("#add").append($skillTable.clone());
});
});
If you want defaults, set them in the default table
<input type="number" name="percentage" min="1" max="100" value="50" />
or set them in code:
$(function() {
var $skillTable = $("#skilltable").clone(); // make a copy
$("#addBut").on("click",function(e) {
e.preventDefault();
var $newTable = $skillTable.clone();
$newTable.find('[name="percentage"]').val(50);
$("#add").append($newTable);
});
});
If you use Jquery try to wrap your code into $(document).ready to make sure that your html is loaded..
Next, pay attention to your quote, I think you have to use single quote first since you use double quote in your HTML tags like this:
document.getElementById('add').innerHTML='<html><body><table> ... </table> </body></html>'

Categories

Resources