jQuery autocomplete to apply to all fields that share a similar name - javascript

I have a form with several rows. each row has a product column with a name starting product. so the names are product1, product2, product3 etc etc.
I have an autocomplete script as follows:
<script type="text/javascript">
$(function(){
$("#product1").autocomplete({ //product is input cell to reference. autocomplete is a jquery function that is being called.
source: "get_sku_codes",
messages: {
noResults: '',
results: function() {}
}
});
});
</script>
This works great on input product1 but does not work on product2 as the script obviously references a different input.
How can I modify my script to be triggered when any cell starting with product is populated?
UPDATE with dynamic content
<script type="text/javascript">
var counter = 1;
jQuery("table.authors-list").on('change','input[name^="qty"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr>'+
' <td><a class="deleteRow"> <img src="<?php echo base_url() ?>application/assets/images/no.jpg" /></a></td>' +
' <td><input type="text" id="product' + counter + '" name="product' + counter + '" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset" /></td>'+
' </tr>');
jQuery('table.authors-list').append(newRow);
});
</script>
Dipesh update
<script type="text/javascript">
var counter = 1;
jQuery("table.authors-list").on('change','input[name^="qty"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr>'+
' <td><a class="deleteRow"> <img src="<?php echo base_url() ?>application/assets/images/no.jpg" /></a></td>' +
' <td><input type="text" id="product_' + counter + '" name="product_' + counter + '" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset" /></td>' +
' </tr>');
jQuery('table.authors-list').append(newRow);
$('#product'+counter).autocomplete(
{
source: "get_sku_codes",
messages: {
noResults: '',
results: function() {}
}
});
});
jQuery("table.authors-list").on('click','.deleteRow',function(event){
if ($(this).parents('table').find('tr').length > 2) { //get number of rows(TR's) in table
$(this).closest('tr').remove();
}else{
alert ('Form must have at least one row') // alert if only one row left in table
}
});
</script>

Use attribute starts with selector [name^="value"]
Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.
$('input[name^="product"]').autocomplete({
Official Document
For Dynamic loaded
You can use .on for that.
$('input[name^="product"]').on('focus',function(){
// code for $(this).autoComplete();
});
According to updated code you can add below code so newly added DOM has autocomplete code attached.
$('#product'+counter).autocomplete(
{
source: "get_sku_codes",
messages: {
noResults: '',
results: function() {}
}
});
add above code after append statement.

try to apply a same class to all those elements
$(".className").autocomplete({
or
$("input[name^='product']").autocomplete({

What is id #product1 on? div? a tag?
Say, if it is a div, loop through all the elements:
$('[.(container wrapper) > div]').each(function () {});
where .(container wrapper) is the class name of the div or p or whatever that encloses you 'products' ..naturally, you would remove the [] ..only for demontration and for the whole thing to make sense.

try multi selector
$("input[id^='product']").autocomplete({ //if you have ID
.....
$("input[name^='product']").autocomplete({ //if you have name
.....
updated
creata a function
function callAutocomplete(obj)
{
$('#'+obj).autocomplete{
//your autocompletecode
};
}
call this function after this line
.....
jQuery('table.authors-list').append(newRow);
callAutocomplete("product" + counter);
and here
$(function(){
callAutocomplete("product1"); //remove other code that u mentioned above
});
and that should do the trick...

Related

How can I add jQuery information to a html form?

This html form gets displayed by a bit of javascript code. Now I want to add the information of the cells in my table, when I click on them, to this kind of alert.
How can I do that?
<div class='alertBox' id='box'>
<script type="text/javascript">
$(document).ready(function() {
$('#tableBody td').on('click', function() {
alert($(this).html() + ' ' + months[currentMonth] + ' ' + currentYear);
});
});
</script>
<form>
<input name='Event' type='text' value='Event'> <br>
</form>
<a onclick='unpop()' class='close'>Close</a>
</div>
...
This is a website, where you can add appointments to a calendar and afterwards the appointments will be displayed by a raspberry pi.
Thank you for your answer.
I already found another solution.
Here it is if you are interested:
$(document).ready(function() {
$('#tableBody td').on('click', function() {
var cellIndex = document.getElementById('displayDate').innerHTML = $(this).text() + ' ' + months[currentMonth] + ' ' + currentYear;
});
});
function pop() {
document.getElementById('box').style.display = 'block';
cellIndex;
}
function unpop() {
document.getElementById('box').style.display = 'none';
}
If the HTML for the alert box is added by javascript, then you will need to use .on() to catch user events (this is called event delegation). Also, when you do that, you must attach the .on() method to an element that definitely exists before the javascript is run - $(document) is always safe.
Try this:
$(document).ready(function() {
$(document).on('click', '#tableBody td', function() {
let txt = $(this).text();
$('#box input[name=Event]').val(txt);
$('#box').show();
});
$(document).on('click', '#box a.close', function(){
$('#box').hide();
});
});
table{border-collapse:collapse;}
th,td{border:1px solid #ccc;}
#box{position:absolute;top:5vh;left:20vw;padding:2vh;background:wheat;display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class='alertBox' id='box'>
<form>
<input name='Event' type='text' value='Event'> <br>
</form>
<a class='close'>Close</a>
</div>
<table>
<thead><th>Name</th><th>Vehicle</th></thead>
<tbody id="tableBody">
<tr><td>Bob</td><td>Car</td></tr>
<tr><td>Sam</td><td>Truck</td></tr>
<tr><td>Fred</td><td>Bike</td></tr>
</tbody></table>

jquery: set the value of the added input with the append one at a time

With ajax, I add to a table one row of an item and therefore imposed the id value of an input (connected to a button that opens the php page with that specific item card).
The first entry (via append) is ok: the item is properly displayed and its id is properly assigned to the button
but when I add (via append) the following item in the subsequent lines, the id of the setting of these successive item does not work: each of these id has the value of all ( id_item = 1 & id_item = 2 & id_item = 3 ... ).
The append function does not retain the attributes settings?
Enclosed is the code that I use:
$.ajax({
...
success: function(id_item) {
var row_appended = (
'<tr class="class_tr" id="id_tr">' +
'<td width="90%">NEW ITEM</td>' +
'<td width="10%">' +
'<form method="GET" action="see_item.php">' +
'<input type="hidden" name="id_item" class="id_item" value=0>' +
'<button type="submit" class="button_change_item" title="see item">See item</button>'+
'</form>' +
'</td>' +
'</tr>'
);
//$(append).appendTo('table#tabella_elenco_clienti');
//OR:
$("#table_items").last().append(row_appended);
//$('table#table_items tr :input[value="0"]').val(id_item);
//OR:
$('#table_items tr:last :input.id_item').val(id_item);
},
error: function(){
alert("Error!!!");
}
});
Your problem it's not on the append function it's on the jquery or jscript execution.
Those append id's don't exists for .click because they are not on the dom
so you should use a jquery .live|.on jquery action instead of .click
juqery.on

click(dataMap, method) version of the jQuery is not working

I tried to pass data through the click method to test it out so that I do not have to call a function from handler onclick. I want to do this to prevent the default submit whenever I press any button. Like this instead of having.
<button onclick="addAuthor()">Add Author</button>
I can have something like:
<button id="addAuthor">Add Author</button>
Which would go to.
$("#addAuthor").click({
id: 100
}, addAuthor);
Then.
function addAuthor(dataMap) {
alert(dataMap.data.id)
//add another author
}
I want the button "Remove div2" to do the same thing the span "Remove" does.
For now I had it to give an alert with the value of 100 but it does not even do that.
$("removeDiv").click({bookDiv: count}, removeDiv);
This is what I want to put so that the variables are passed but the test doesn't work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
////////////////////////////////////////////////
//HERE
$("#removeDiv1").click({
id: 100
}, removeDiv1);
////////////////////////////////////////////////
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>'
///////////////////////////////////////////////////
////HERE
+ '<button id="removeDiv1"> Remove div2</button>'
///////////////////////////////////////////////////
+ '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
///////////////////////////////////////////
//HERE
function removeDiv1(dataMap) {
alert(dataMap.data.id)
}
///////////////////////////////////////////
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr)
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem isn't with passing in the dataMap (try it without it; it still won't work).
The problem is that when you attempt to set your click handler with $("#removeDiv1").click(...), the #removeDiv1 element doesn't exist yet - it's created and added to the DOM later, in addMore.
You need to do one of the following:
Set your click handler inside of addMore, after str is appended.
Change your click handler to use jQuery's event delegation capabilities. $("#removeDiv1").click(...) becomes $("body").on('click', '#removeDiv1', ...)
Side note: the "body" selector can be replaced by any selector that will select an ancestor of #removeDiv1; the click event propagates up from #removeDiv1 to its parent, its parent parent, and so on, until it's handled and something calls e.stopPropagation(), or until it reaches the document root.
First off, this is really something that Angular or something like it can do much better.
Next, I wouldn't use ids. You can do the same thing with classes without having to increment and restrict your code. Here's how I'd code the HTML:
<div>
<h1>My favorite authors and their books</h1>
<button class="js-add">Add An Author</button>
<div class="authors"></div>
<button class="js-save">Save</button>
</div>
I've also pulled all the javascript out of the HTML.
Next, "click" won't apply to items added after it is stated. You either need to re-state a click for the new element, or you need to use "on". Note in the code below that I can use the "click" method for "add Author" because that button exists when the script was run. For the other buttons, I had to use "on('click'..."
var addAuthor = function($this) {
var books = $('<div>')
.addClass('books')
.append(
$('<button>')
.addClass('js-addBook')
.html('Add a book')
)
.append(
$('<div>')
.addClass('bookName')
.html('Books:')
);
addBook(books.find('button'));
$($this)
.parent()
.find('.authors')
.append(
$('<div>')
.addClass('author')
.append(
$('<div>')
.addClass('authorName')
.html('Author: ')
.append(
$('<div>')
.addClass('remove js-removeAuthor')
.html('x')
)
.append(
$('<input>')
)
)
.append(
books
)
)
};
var addBook = function($this) {
$($this)
.parent()
.append(
$('<div>')
.addClass('book')
.append(
$('<div>')
.addClass('remove js-removeBook')
.html('x')
)
.append(
$('<input>')
)
)
};
addAuthor($('button.addAuthor'));
$('.js-addAuthor').click(function() {
addAuthor(this);
});
$('.authors').on('click', '.js-addBook', function() {
addBook(this);
});
$('.authors').on('click', '.js-removeBook, .js-removeAuthor', function() {
$(this)
.parent()
.remove()
});
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/rt3tpeta/3/

Div's content editor

I have this code:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#k123").click(function () {
//var text=$(this).val(); //this does not work
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" onclick="save();" value="save"><input type="button" onclick="cancel();" value="cancel"></div>';
$(this).replaceWith(k);
});
});
function save() {
}
function cancel() {
//alert(text);
var k='<div id="k123"></div>';
$("#k123").replaceWith(k);
}
</script>
</head>
<body>
<div id="k123">aaaaa</div>
</body>
</html>
My question is :
1)In both functions : cancel & save , How can I get content of div id->#k123->textarea->content
functions cancel & save are outside the scope and they are independent functions I cannot tell $(this).parent().
I need to ask about div which has id #k123 , then get inside to textarea's content and get it.
and I have also to get id #k123 automatically because if I have many divs I cannot tell save & cancel manually the div's id, cancel & save should know the div's id sender from the input type='button'`s parent id.
**please I do not prefer the suggestion of sending div id from input button
**We are assuming that both input buttons have no IDS or Names
I tried another way but still having same problem
I replaced
$(document).ready(function() {
$("#k123").click(function () {
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel"></div>';
$(this).replaceWith(k);
});
//$("#k123 > input").click(function() {
$("#k123").children("input:second").click(function() {
alert("hi");
});
});
thank you.
I have the working code for you below. You don't even need an id.. just a container div and delegation of events. The below accomplishes what I thought you were after, in what I believe to be a much simpler, and much more efficient fashion:
(I've added comments to assist in understanding the code)
$(document).ready(function() {
$(".container").on('click', function(e) {
if (!$(e.target).is('input') && !$(e.target).is('textarea')) { //check to make sure the target is neither an input or a textarea
var div_text = $(e.target).text(); // use a variable named something other than text, because text is already a method for another element
$(e.target).data('text',div_text); // set the div's current contents as a hidden data attribute, to be retrieved later. You can get rid of this and the other line if you want cancel to completely wipe the div.
var k = '<textarea rows="10" cols="10">' + div_text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel">';
$(e.target).html(k); //set the inner HTML of the div, so we don't lose any data saved to that div
}
if ($(e.target).is('input') && $(e.target).val() == 'save') {
$(e.target).parent().html($(e.target).parent().find('textarea').val()); // replace the current contents of the parent div with the contents of the textarea within it.
} else if ($(e.target).is('input') && $(e.target).val() == 'cancel') {
$(e.target).parent().html($(e.target).parent().data('text')); //set the contents to the old contents, as stored in the data attribute. Just replace the contents of the .html() here with '' to completely clear it.
}
});
});​
DEMO
REVISED - WORKS
Check this out... not quite there but close!
REVISED JS Fiddle
function editit() {
var divId = $(this).attr('id');
var text = $(this).html();
var k = '<div id="' + divId + '" class="editable"><textarea id="newvalue' + divId +'" rows="10" cols="10">' + text + '</textarea><br /><input id="save' + divId + '" type="button" value="save"><input id="cancel' + divId + '" type="button" value="cancel"></div>';
$('#' + divId).replaceWith(k);
$('#cancel' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + text + '</div>');
$('.editable').bind('click', editit);
});
$('#save' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + $("#newvalue" + divId).val()+ '</div>');
$('.editable').bind('click', editit);
});
}
$('.editable').bind('click', editit);

How to fetch the id of dynamically generated textboxes?

How is it possible to get the id of the dynamically generated textboxes using jquery?. I need to fire the TextChanged event for the corresponging textbox. There is no method reference for the textboxes in the code behind.How can i refer to any method in the codebehind on firing the event. Somebody please help. I dont know jquery much. The entire script im using is as as follows:
<script type="text/javascript">
$(init);
function init()
{
$('#test').droppable(// Div Control
{
drop: handleDropEvent
});
$('a').each(function(idx, item) {
$(item).draggable({ cursor: 'move', helper: 'clone' })
});
}
$(function() {
$("#draggable").draggable(); //Nothing to do with this div
});
function handleDropEvent(event, ui)
{
var draggable = ui.draggable;
document.getElementById('test').innerHTML += addColumn(draggable.attr('text')) + '<br>';
}
function addColumn(column)
{
var iHtml;
// This code will generate a checkbox and a textbox. I need to fire the event of thus generated textboxes.
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input type="text" runat="server" id="aln' + column + '"> </div>';
return iHtml;
}
</script>
There's two ways: keep the generated element, or generate an ID when you generate your new element.
a) keep the generated element
This requires that you don't use innerHTML, but create the element (with document.createElement, or with jQuery's $), and then you can use the element directly (no need to call it by ID any more). For instance, with jQuery:
var container = $('#container');
var myDiv = $('<div id="myDiv"/>');
var myCheck = $('<input type="checkbox"/>');
myDiv.append(myCheck);
container.append(myDiv);
b) generate the ID
container.innerHTML = '<div id="myDiv"><input type="checkbox" id="myCheck"/></div>';
// and after this you can get them by ID:
var myCheck = $('#myCheck');
I would just add a class to the textbox in your iHtml then use .live() event
replace your iHtml with this
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input class="myclass" type="text" runat="server" id="aln' + column + '"> </div>';
then add the live event
$('.myclass').live('change', function() {
alert(' Live handler called.');
});
here is a WORKING DEMO

Categories