html javascript autocomplete not working with dynamically added textboxes - javascript

Hi when I use jquery autocomplete on 1 textbox it work, but when i dynamically add new textbox these new textbox dont have the same autocomplete
Here is my javascript autocomplete
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script type="text/javascript" src="dynamicscript.js"></script>
<script>
$(document).ready(function(){
$(".DRUG_NAME").autocomplete("gethint.php", {
selectFirst: true
});
});
</script>
this is what i am dynamically adding each time, html code
<form method="post">
<p>
<input type="button" value="Add Drug" onClick="addRow('dataTable')" />
<input type="button" value="Remove Drug" onClick="deleteRow('dataTable')" />
</p>
<table id="dataTable" class="form" border="1">
<tbody>
<tr>
<p>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" />
</td>
<td>
<label>Drug</label>
<input type="text" required="required" name="DRUG_NAME[]" id="DRUG_NAME" class="DRUG_NAME">
</td>
</p>
</tr>
</tbody>
</table>
<input type="submit" value="Save" />
</form>
this is the javascript dynamically add / remove row i even added the autocomplete function after my addrow to try and get the jquery autocomplete to be called each time after i add row but it still does not work
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 5) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
} else {
alert("Maximum Drug is 5");
}
$("#DRUG_NAME").autocomplete("gethint.php", {
selectFirst: true
});
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount < 1) { // limit the user from removing all the fields
alert("Nothing to Remove");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
any ideas?? tx

The following code (from your post) attaches events to the elements with class DRUG_NAME that currently exist on the page:
$(".DRUG_NAME").autocomplete("gethint.php", {
selectFirst: true
});
When you dynamically add an element that selector will be updated, but the events still won't be attached, see this answer: Event binding on dynamically created elements?
Using that answer, together with the one #LcKjus linked in his answer (Bind jQuery UI autocomplete using .live()), I believe this will work for you (replace the code above with this snippet to test):
$(".DRUG_NAME").on("focus", function (event) {
$(this).autocomplete(options);
});
This may run the autocomplete code multiple times (if the user refocuses the input field), though, so be aware of that.
P.S. As others have noted, it is unwise to have multiple elements with the same id on the same page.

You probably need a live binding.
Take a look at this post:
Bind jQuery UI autocomplete using .live()

The problem is that you are creating elements with the same ID DRUG_NAME and then you are applying autocomplete selecting the field by ID.
Remove the id from the input field of the first row, as it is going to be replicated:
<input type="text" required="required" name="DRUG_NAME[]" class="DRUG_NAME">
Use the class selector when you create new rows:
$(".DRUG_NAME").autocomplete("gethint.php", {
// ^^
selectFirst: true
});

The code to bind the autocomplete is being run on document ready. You need to run it again after you add the dynamic text boxes (maybe create a bindAuto() function or whatever, and run it from both places).

Related

javascript stop button onClick from submitting form

I have two button inside a form that I don't want to submit the form but add and remove table rows. One button is dynamically added.
I have tried many ways to prevent the submission but none seem to work. When I was getting the button by id and using an event listener it was ok but that did not work with button that get added after age load. I am trying to find a solution that will work with buttons. The one that loaded on page load and the ones that get added dynamically with JavaScript.
<table id="conditions-table">
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th></th>
</tr>
<tr>
<td>
<input id="condtitions-input"></input>
<select id="condtitions-level">
<option value="Mandatory">Mandatory</option>
<option value="Important">Important</option>
<option value="Support">Support</option>
</select>
</td>
<td>
<button id="add-condtition" onclick="addCondition(e); return false;">Add Conditions</button></td>
</td>
</tr>
</thead>
</table>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
<script>
var counter = 0;
function addCondition(e){
e.preventDefault()
var table = document.getElementById("conditions-table");
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var condtionsInput = document.getElementById("condtitions-input");
var condtionsInputValue = condtionsInput.value;
condtionsInput.value = "";
var selectedLevel = document.getElementById("condtitions-level");
var selectedLevelValue = selectedLevel.value;
cell1.innerHTML = `<input type="text" name="strategies_conditions[${counter}][name]" value=" ${condtionsInputValue}"></input>
<select>
<option ${(selectedLevelValue == "Mandatory") ? 'selected="selected"' : ""} value="Mandatory">Mandatory</option>
<option ${(selectedLevelValue == "Important") ? 'selected="selected"' : ""} value="Important">Important</option>
<option ${(selectedLevelValue == "Support") ? 'selected="selected"' : ""} value="Support">Support</option>
</select>`;
cell2.innerHTML = "<button class='remove-condition' onclick="removeCondition()">X</button></td>";
counter++;
return false;
};
function removeCondition() {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
};
The default type of a button is "submit"; just override that behavior by setting it to "button".
cell2.innerHTML = "<button type='button' class='remove-condition' onclick='removeCondition()'>X</button></td>";
You also need to define event as a parameter of the event handler function.
function removeCondition(event) {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
};
Just don't insert the argument e inside the onclick event in the markup you can apply an event using JavaScript like the following
btn.onclick = e => {
e.preventDefault();
}
<form>
<input type="text" name="" placeholder="Name">
<input type="submit" name="" id="btn">
</form>
or you can simply make a onclick event return false like the following
<form>
<input type="text" name="" placeholder="Name">
<input type="submit" name="" id="btn" onclick="return false">
</form>
to add an event to an element that doesn't exist yet on the DOM you need to know about event.target
here is a sample that might help you
document.addEventListener( "click", listenerFunction );
function listenerFunction(event){
var element = event.target;
// here you check for that auto generated element
if(element.tagName == 'A' && element.classList.contains("someBtn")){
console.log("hi");
}
}
All you really need to do is add:
<input type="submit" onclick="event.preventDefault();">
You probably want to handle it though so in total you'd probably do something more like this:
<script>
function myFunction(){
if (confirm("Are you sure you want to ...? This action cannot be undone.")) {
document.getElementById("myForm").submit();
}
}
</script>
<form method="post" action="/test" id="myForm">
<input type="submit" onclick="event.preventDefault();myFunction();">
</form>
This allows the user to click ok to proceed or cancel to not have it submit the form.

how to validate dynamic text box values in jquery

Thanks in advance.I have a popup window which has a dynamic text box fields.These textboxes will multiple according to the selected combo box values from the first form.The dynamic textboxes are displayed from jquery. Please anyone help me how to validate a dynamic text boxes on clicking the submit button. Actually I have to validate the textboxes before sending the mail. I have written a code which will validate only static textboxes. My code as below
<head>
<script>
$(document).ready(function () {
$(".myformid").click(function(){
var nameVal = $('.names').val();
var emailVal = $('.emails').val();
var phoneVal = $('.phones').val();
if(nameVal == "")
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Name</p>");
}
else if(emailVal == ""){
//alert("A textbox is required");
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the email Id</p>");
}
else if(!ValidateEmail(emailVal))
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Invalid Email Id</p>");
}
else if(phoneVal == "")
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Phone Number</p>");
}
else if(isNaN(phoneVal))
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Valid Phone Number</p>");
}
else if(emailVal !="" && phoneVal != "")
{
$('#errmsg').text(" ");
var username = $('#usernameId').val();
var length = $('#lengthId').val();
var nameArray = [];
var emailArray = [];
var phoneArray = [];
$('.names').each(function(){
nameArray.push(this.value);
});
var nameboxVal = nameArray.join(",");
//alert(nameboxVal);
$('.emails').each(function(){
emailArray.push(this.value);
});
var emailboxVal = emailArray.join(",");
//alert(emailboxVal);
$('.phones').each(function(){
phoneArray.push(this.value);
});
var phoneboxVal = phoneArray.join(",");
//alert(phoneboxVal);
$.ajax({
type: "POST",
url: "/invl_exams/popSubmit",
data: {user:username,name:nameboxVal,email:emailboxVal,phone:phoneboxVal,lengths:length},
success: function(result){
console.log(result);
$('#mailSuccess').text('Mail Send Successfully');
$('#mailSuccess').fadeOut(5000);
}
});
}
});
});
// Passing dynamic textboxes inside the dialog box
$(".create-user").change(function(){
var selVal = $(this).val();
$('#lengthId').val(selVal);
$("#textboxDiv").html('');
if(selVal > 0) {
for(var i = 1; i<= selVal; i++) {
var sno = i;
$("#textboxDiv").append('<tr><td>'+sno+'. </td><td>Name:<input type="text" name="names" class="names" value="" required="required" /></td><td> </td><td>Email:<input type="email" name="emails" class="emails" value="" required="required" /></td><td> </td><td>Phone:<input type="text" name="phones" class="phones" value="" required="required" minlength="10" maxlength="16"/><br/></td></tr>');
}
}
});
});
</script>
</head>
<body>
<div id="dialog" title="Enter details to send Mail">
<!--<form id="myformid" method="post" action="<?php //echo $this->webroot?>users/sendmail">-->
<div id="mailSuccess" style="color:#019002;font-weight:bold"></div>
<form id="myformid" method="post">
<table id="examtable">
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<div id="textboxDiv"></div>
<input type="hidden" name="username" id="usernameId" value="<?php echo $this->Session->read('Auth.User.username'); ?>">
<input type="hidden" name="length" id="lengthId" value="">
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>
<!--<input type="submit" name="btnSubmit" value="Submit">-->
<input type="button" name="btnSubmit" value="Send Mail" id="popSubmit">
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
I don't think any validation is happening at all, whether the elements are static or dynamic.
$(".myformid").click(function(){
will not bind to anything because there are no elements with the class "myformid". The "." at the start of a selector indicates a class.
However you do have an element with an id "myformid". If you change your selector from . to # to indicate an id, then it will bind the event to the form. However, "click" is not the correct event to bind to a <form> element. You want to handle the form's "submit" event:
$("#myformid").submit(function(event){
Lastly, as it stands, your form will do a regular (non-ajax) postback as well as running your function, because the default behaviour of the submit event is not suppressed. Add this line as the first line of the above function:
event.preventDefault();
This will stop a regular postback from happening and allow your validation function to execute. At that point you should have a working solution, assuming the logic in your validation code is what you want.
If your validations are right you just need to attach event in way that dinamicly created elements will be supported too (jQuery on)
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
for example
from
$(".myformid").click(function(){/*Some action*/});
to
$("body").on('click', ".myformid", function(){/*Some action*/});
from
$(".create-user").change(function(){/*Some action*/});
to
$("body").on('change', ".create-user", function(){/*Some action*/});
Small advice: Try to avoid using $("body") selector you can see what is your good dom element witch is parent to your dynamically generated contend/elements.

jQuery keeps number of cloned rows after reset

I have a form in a popup, that presents a simple table with header and one row, with a + button the user can click to add (clone) a row.
This works perfectly, the user submits the form, data is read - no problem.
The form is reset after submission with:
$('#entryTable').find("tr:gt(1)").remove(); // keep header and first row
$('#entryForm')[0].reset();
If the user calls the form immediately, the forms "seems" correctly reset, all fields look like new.
If the user clicks on the + (clone) button - it adds the number of rows added previously, and not 1, as if something (but what ?????) was not reset.
my clone function is
$(".cloneprod_add").on('click', function(e) {
e.preventDefault();
var $tr = $(this).closest('.tr_clone'); //only first row has +
var idtr= parseInt($tr.attr("id")); // checked it is always id of row1
var $clone = $tr.clone(true);
cindex++;
$clone.find(':text').val('');
$clone.attr('id', idtr+(cindex) );
$clone.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cindex);
}
});
$tr.after($clone);
$("#addline_"+cindex).addClass("uk-hidden"); // remove +
$("#delline_"+cindex).removeClass("uk-hidden"); // add -
});
cindex is correctly reset to 0 when the form is called again. What else should be reset ? where is my error ?
Thanks for your advices
(EDIT)
I am adding the form . I am using UIkit (www.getuikit.com), a node server and the form comes from a template in jade - I copied the HTML from the browser
<form id="entryForm" action="" class="uk-form uk-form-stacked" >
<div id="entryDialog" class="uk-modal-dialog uk-modal-dialog-large">
<fieldset data-uk-margin="">
<div class="uk-panel uk-panel-box uk-panel-box-primary uk-margin-small-top">
<div class="uk-form-row"><div class="uk-grid"><div class="uk-width-1-1">
<table id="entryTable" class="uk-table">
<thead><tr><th>lot</th><th>code</th><th>num</th>
<th>qte</th><th>unit</th><th>pos</th><th>cont</th>
<th></th></tr>
</thead>
<tbody><tr id="0" class="tr_productclone">
<td><input type="text" name="lot" id="lot_0" class="lot"></td>
<td><input type="text" name="code" id="code_0" class="code"></td>
<td><input type="text" name="num_0" id="num_0" class="num"></td>
<td><input type="text" name="qte_0" id="qte_0" class="qte"></td>
<td><select name="unit_0" id="unit_0" class="unit"><option value="items">pezzi</option></select></td>
<td><select name="pos_0" id="pos_0" class="pos"><option value="1">piece1</option></select></td>
<td><select name="cont_0" id="cont_0" class="cont"></select></td>
<td><button id="addline_0" class="uk-button cloneprod_add"></button>
<button id="delline_0" class="uk-button cloneprod_del"></button></td>
</tr>
</tbody></table></div></div></div></div>
<div class="uk-modal-footer"><button id="btnSave" type="submit" class="uk-button ">save</button></div>
</fieldset></div></form>
I found a solution to my problem. I don't know the why and hows, but at least it works.
I had the impression that the remove was keeping the information of the number of cloned rows and was thus putting that number back. I thought about reloading the table in the modal, so that it would be "fresh without memory".
In the end, I wrote the definition of the table in the js script and not in the Jade template. The table is rebuilt overtime the form is called, and no more memory ghosts.
It works, but I still don't understand why those ghosts.

Run function after a checkbox change on my page

I have dynamically created check boxes on my page and assigned each of them an unique id like 'renameteam1', 'renameteam2' etc.. I am trying to run a function when one of these gets checked. The function will then allow the user to enter a corresponding field that was previously readonly.
I have tried the following but it doesn't seem to be working.
var a=0;
$('input[type=checkbox]').change(function () {
for (var i=0;i<rows3;i++){
a=a+1;
var id= '#renameteam'+a;
if ($(id).is(":checked")) {
$('#newname'+a).removeProp('readonly');
}
}
//Here do the stuff you want to do when 'unchecked'
});
Any Suggestions?
This is how I would do it
//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#' + checkbox.data('id'));
otherInput.prop('readonly', !checkbox.is(':checked'));
if (!checkbox.is(':checked')) {
// do stuff here when checkbox isn't checked - not sure if you still want this bit but it is as per your comments in the code above
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" data-id="newname1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />
If you don't want to use a data attribute, you could do this:
//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#newname' + this.id.replace('renameteam', ''));
otherInput.prop('readonly', !checkbox.is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />
Try using an on click instead of on change for checkboxes and radio buttons.

How to insert selected radio button value into table cell

I have 5 radio buttons
<input type="radio" id="rating">1
<input type="radio" id="rating2">2
<input type="radio" id="rating3">3
<input type="radio" id="rating4">4
<input type="radio" id="rating5">5
I have one table
<table id="myTableData" border="1" style="width:100%">
<tr id="templateRow">
<th>Ratings</th>
</tr>
</table>
One add button
<input type="button" id="add" value="Add" onclick="addRadioValue()">
I've written the code to dynamically add rows to the table, but when I select a radio button and then I click on the add button, the value of the selected radio button should get inserted into a new cell within table Ratings.
I am able do this thing for a text box, but I'm not able to do it for a radio button.
Can anyone help me?
you can use querySelector('input[name="rating"]:checked')
Java script
function addRow() {
var myName = document.getElementById("name");
var auther = document.getElementById("auther");
var publish = document.getElementById("publish");
var rating = document.querySelector('input[name="rating"]:checked');
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML=count ;
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= auther.value;
row.insertCell(3).innerHTML= publish.value;
if(rating.checked)
row.insertCell(4).innerHTML= rating.value;
else
row.insertCell(4).innerHTML= "";
count=count+1;
}
Here is my Demo
Your problems were that you didn't have name set on the radios and that you were trying to grab the selected radio with a get id statement. You actually need to grab the radio elements by name and do a loop to check which is selected.
Working jsfiddle: http://jsfiddle.net/cv4u0nf9/4/
The loop i inserted
var ratings = document.getElementsByName("rating");
for (var i=0; i<ratings.length; i++) {
if (ratings[i].checked) {
rating = ratings[i];
}
}

Categories