jQuery Autocomplete on Dynamically new rows - javascript

Issue: The (jQuery) auto-complete works only for the first input (displayed by default). It doesn't work for additional row/s which are added using the add row function.
I have read other posts and understood that I have to use class and not id. But it still doesn't work.
I am using jquery autocomplete and some javascript to add and delete rows for a specific id.
Here is the headers:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
Here is the jquery code:
jQuery(document).ready(function ($) {
/* availableTags = [
"Demo",
"Senna",
"Adam",
"Eva",
];*/
$('.autofill').autocomplete({
source:'suggest.php', minLength:2
});
});
Here is the HTML code:
<div class="content-left">
Add rows
<div id="p_scents">
<p>
<label style="margin-bottom:10px;" for="p_scnts">
<input class="autofill" type="text" id="p_scnt" size="20" name="p_scnt[]"
value="" placeholder="Enter text" />
</label>
</p>
</div>
</div>
**Here is the Javascript to add rows:**
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function () {
$('<p><label style="margin-bottom:10px;" for="p_scnts"><input class="autofill" type="text" name="p_scnt[]" size="20" id="p_scnt_' + i + '" value="" placeholder="Add text" /></label for="remScnt"> <label style="padding-left:400px;">Remove</label></p>').appendTo(scntDiv);
//i++;
//return false;
//Added the 5 lines below
$(function ($) {
$('#p_scnt_' + i).autocomplete({
source:'suggest.php', minLength:2
});
});
i++;
return false;
});
$('#remScnt').on('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
So the above code is working fine. Cheers all for your help ;)

For your latest code, you've made two mistakes:
Increase the counter i before apply autocomplete to text field
Stopped the script by return false
Also, it's recommended to use .on() to replace .live() as it's deprecated in version 1.7 .
Demo: http://jsfiddle.net/indream/f8mt4/
$('#addScnt').on('click', function () {
$(...).appendTo(scntDiv);
//i++; Should not be done here
//return false; Stopped the script
//Added the 5 lines below
$(function ($) {
$('#p_scnt_' + i).autocomplete({
source: window.availableTags,
minLength: 1
});
});
i++; // should increase counter here
return false;
});
p.s. I've changed availableTags to global variable in order to make the demo works,
but I think you would use query to retrieve the tags.

$('#addScnt').live('click', function() {
.........................
$('#p_scnt_'+i).autocomplete({
source:'suggest_fill.php',
minLength:1
});
return false;
..................
});

I think it's the sequence of js file load problem.
Try to put your second file above the 1st file.
Hope it helps you.

the second $(function(){is too much. it should look like this
<script>
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function() {
$('<p><label style="margin-bottom:10px;" for="p_scnts"><input class="autofill" type="text" name="p_scnt[]" size="20" id="p_scnt_' + i +'" value="" placeholder="Add text" /></label for="remScnt"> <label style="padding-left:400px;"><img src="../../img/remove.jpg" width="" height="" class="img" alt="" title=""/></label></p>').appendTo(scntDiv);
i++;
//Added the 5 lines below
$('#p_scnt_'+i).autocomplete({
source:'suggest_fill.php',
minLength:1
});
return false;
});
$('#remScnt').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>

Related

jQuery - Allow user to add a maximum of 4 divs/user inputs

I'm trying to emulate this jsfiddle (code also shown below) and modify it to allow user to add a maximum of 4 fields
JS:
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
HTML:
<h2>Add Another Input Box</h2>
<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
</p>
</div>
Additionally, I tried reworking and updating code for the latest version of jQuery 1.11.0, updating function, .live() to .on() and .size() to .length() per jQuery documentation, but no luck...code didn't work that way.
Any help is much appreciated.
You have to use .on() to attach event handlers. Also, replace ID with class because there will be multiple input elements.
You can use the property .length to get the count of elements
In order to delete, you have to delegate the events since the remove anchor tag will be added dynamically to the DOM. Like this $('#p_scents').on('click','.remScnt', function(){ });
This works with jQuery 1.10.1
Overall, something like this should do.
$(function () {
var scntDiv = $('#p_scents');
var i = $('.p_scnt').length;
$('#addScnt').on('click', function () {
if (i >= 4) return;
$('<p><label for="p_scnts"><input type="text" class="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
});
$('#p_scents').on('click', '.remScnt', function () {
if (i > 0) {
$(this).closest('p').remove();
i--;
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/tZPg4/13620/
Also you can improve the add functionality to something like for a cleaner code
$('#addScnt').on('click', function () {
if (i >= 4) return;
var newInput = $('<input type="text" size="20" name="p_scnt_' + i + '" placeholder="Input value" />');
var removeLink = $('Remove</p>');
var newEl = $('<p></p>').append(newInput).append(removeLink);
newEl.appendTo(scntDiv);
i++;
});

how to pass the variable in jquery click event function

I want to Pass the variable with click event in jquery
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
}
please help me
html
<input type='submit' name='action' id='edit' />
You forgot the closing paranthesis.
Your javascript code should look like:
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});
You have to initialize click even once document is loaded. Also you have syntax error in your code.
Try this one:
$(document).ready(function() {
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});
});
</script>
</head>
<body>
<input type='submit' name='action' id='edit' />
</body>
</html>
HTML button
<button id='my_button' type='button' data-id='1' data-values='1' value='6' data-whatever='20'>My button</button>
Jquery
$('#my_button').bind('click', function() {
var value = $(this)val();
var whatever = $(this).data('whatever');
var id = $(this).data('id');
var values = $(this).data('values');
console.log(value);
console.log(whatever);
console.log(id);
console.log(values);
});
Open Firefox > Inspect Element > Console Tab.
Load the codes
Click the button
See response
Initiate everything after document is ready.
$(document).ready(function() {
var get = 3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});
});
also don't use event handlers until you need it.
try:
$(document).ready(function() {
var get=3;
$('#edit').on('click', function(event){
alert('You are getting:' + get);
}
});
html:
<input type="button" id="edit" />
You can do it like this:
$(document).ready(function() {
var get = 3;
$("#edit" ).bind("click", { key: get }, function(event){
// event.data.key will have value of get
});
});
Can you try like this,
<script type="text/javascript">
function test(ev) {
var id = $(ev).attr('id');
alert(id);
}
</script>
<input id="btn" type="button" value="click" OnClick="test(this);" />
try this.
html:
<input type="button" id="edit"><br/>
jquery:
$(document).ready(function(){
var get = 3;
$("#edit").on('click',function(){
alert("Value is: " + get);
//parameter value
});
});

jQuery input number spinner

I have this code for jQuery spinner up-down number :
HTML:
<div class="container">
<div class="input-group spinner">
<input type="text" class="form-control" value="42">
<div class="input-group-btn-vertical">
<div class="btn btn-default"><i class="fa fa-caret-up"></i></div>
<div class="btn btn-default"><i class="fa fa-caret-down"></i></div>
</div>
</div>
</div>
JS:
(function ($) {
$('.spinner .btn:first-of-type').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) + 1);
});
$('.spinner .btn:last-of-type').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
});
})(jQuery);
This Worked But I need to add two option:
prevent user add number to input
set Maximum and Minimum for number
How do add this option?!
DEMO FIDDLE
Change:
<input type="text" class="form-control" value="42">
To:
<input type="number" min="0" max="10" steps="1" class="form-control" value="5">
I didn't quite understand from your question if you wanted the user to be able to change the value or not, in the case that you don't want them to change the value, just add the readonly attribute to the input field, like this
<input type="number" min="0" max="10" steps="1" class="form-control" value="5" readonly>
To do this all with jQuery which i assume you want:
$(document).ready(function(){
//Stop people from typing
$('.spinner input').keydown(function(e){
e.preventDefault();
return false;
});
var minNumber = 1;
var maxNumber = 10;
$('.spinner .btn:first-of-type').on('click', function() {
if($('.spinner input').val() == maxNumber){
return false;
}else{
$('.spinner input').val( parseInt($('.spinner input').val(), 10) + 1);
}
});
$('.spinner .btn:last-of-type').on('click', function() {
if($('.spinner input').val() == minNumber){
return false;
}else{
$('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
}
});
});
I haven't check but should be pretty accurate
Working Fiddle: http://jsfiddle.net/7jtLa3py/3/
Better Ways :
bootstrap spinner DEMO
jQuery Spinner
jQueryUI spinner
bootstrap snipper worked easy:
HTML
<input type="text" class="aSpinEdit" />
Javascript
$('.aSpinEdit').spinedit({
minimum: -10,
maximum: 50,
step: 1
});
Assuming you have to send that data back to the server, setting the input readonly attribute and adding some limits to the input value its fairly easy.
Here's the demo
http://jsbin.com/yebawihune/7/
With this you can dynamically add as many spinners as you want that are cross browser compatible (even IE). Of course you have to have included the needed js and css files for jquery.
First you have to create your input. Keep note of the id as you will use that later. I always just put the same value for the id and name parameters in the input.
<input id="elementName" name="elementName">
Then put this in your head section.
function createSpinner(elemName, elemVal, elemMin, elemMax, elemStep){
var mySpinner = $( '#' + elemName ).spinner({
min: elemMin,
max: elemMax,
step: elemStep,
change: function( event, ui ) {
var typedVal = $( '#' + elemName ).spinner( 'value' );
if (typedVal < elemMin || typedVal > elemMax) {
alert('Value must be between ' + elemMin + ' and ' + elemMax);
$('#' + elemName).spinner('value', elemVal);
}
}
});
$('#' + elemName).spinner('value', elemVal);
};
Then you just call the function, passing the needed parameters (the first parameter will be the value of the ID of your input).
createSpinner('elementName','0','0','10000','1');

Dynamically created DOM manipulation button not firing event

I have a function to add and remove a field but the remove function doesnt work somehow.
HTML:
<div id="parts">
Part
<input type="text" id="auto_part" name="auto_part" />
<br />
Description
<input type="text" id="auto_description" name="auto_description" />
<br />
</div>
Add another part
jQuery:
$(function() {
var scntDiv = $('#parts');
var i = $('#parts input').size();
$('#addField').on('click', function() {
$('<br /><div id="parts"><span>Part</span> <input type="text" id="auto_part'+i+'" name="auto_part'+i+'" /><br />').appendTo(scntDiv);
$('<span>Description</span> <input type="text" id="auto_description'+i+'" name="auto_description'+i+'" /> <br />').appendTo(scntDiv);
$('<input type="hidden" id="row_count" name="row_count" value="" />').appendTo(scntDiv);
$('Remove</div>').appendTo(scntDiv);
i++;
return false;
});
$('#removefield').on('click', function() {
if( i > 2 ) {
$(this).parents('div').remove();
i--;
}
return false;
});
});
The problem must have to do with this line:
$('#removefield').on('click', function() {
It doesnt pass that condition.
When I click on Remove it doesnt do anything at all it just scrolls to the top.
You are binding the click handler to the elements that are present in the DOM. But, your #removefield element is being dynamically added. So, the event handler is not attached to it.
You can use .on() to use event delegation and handle also future elements. Also, you may want to use classnames instead of and id attributes. id attributes need to be unique, but you can set the classname to as many elements as you want.
Remove
$("#parts").on("click", ".removefield", function() {
/* ... */
});
The reason why your "Remove" link doesn't work is because you are adding the dynamic <div> element by parts hence making it invalid markup. You should be adding it all together at once. For example,
$('#addField').on('click', function () {
var part = '<div id="parts' + i + '"><span>Part</span> <input type="text" id="auto_part' + i + '" name="auto_part' + i + '" /><br/>' +
'<span>Description</span> <input type="text" id="auto_description' + i + '" name="auto_description' + i + '" /> <br />' +
'<input type="hidden" id="row_count' + i + '" name="row_count' + i + '" value="" />' +
'Remove</div>';
scntDiv.after(part);
i++;
return false;
});
$(document).on("click", ".removefield", function() {
if( i > 2 ) {
$(this).parent('div').remove();
i--;
}
return false;
});
You can see it here.
try
$('#removefield').live("click", function() {

Add (and remove) group of textelements dynamically from a web form using javascript/jquery

im very new at javascipt (im php developer) so im really confused trying to get this working.
In my web form i have 3 textfields (name, description and year) that i need to let the user add as many he needs, clicking on a web link, also, any new group of text fields need to have a new link on the side for removing it (remove me).
I tried some tutorial and some similar questions on stackoverflow but i dont get it well. If you can show me a code example just with this function i may understand the principle. Thanks for any help!
this is the simplest thing that has come to my mind, you can use it as a starting point:
HTML
<div class='container'>
Name<input type='text' name='name[]'>
Year<input type='text' name='year[]'>
Description<input type='text' name='description[]'>
</div>
<button id='add'>Add</button>
<button id='remove'>Remove</button>
jQuery
function checkRemove() {
if ($('div.container').length == 1) {
$('#remove').hide();
} else {
$('#remove').show();
}
};
$(document).ready(function() {
checkRemove()
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
checkRemove();
});
$('#remove').click(function() {
$('div.container:last').remove();
checkRemove();
});
});
fiddle here: http://jsfiddle.net/Fc3ET/
In this way you take advantage of the fact that in PHP you can post arrays: server side you just have to iterate on $_POST['name'] to access the various submissions
EDIT - the following code is a different twist: you have a remove button for each group:
$(document).ready(function() {
var removeButton = "<button id='remove'>Remove</button>";
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
$('div.container:last').append(removeButton);
});
$('#remove').live('click', function() {
$(this).closest('div.container').remove();
});
});
Fiddle http://jsfiddle.net/Fc3ET/2/
jsFidde using append and live
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var html = "<div>" + '<input name="name{0}" type="text" />' + '<input name="description{1}" type="text" />' + '<input name="year{2}" type="text" />' + '<input type="button" value="remove" class="remove" />' + '</div>',
index = 0;
$(document).ready(function() {
$('.adder').click(function() {
addElements();
})
addElements();
$('.remove').live('click', function() {
$(this).parent().remove();
})
});
function addElements() {
$('#content').append(String.format(html, index, index, index));
index = index + 1;
}
Look at this: http://jsfiddle.net/MkCtV/8/ (updated)
The only thing to remember, though, is that all your cloned form fields will have the same names. However, you can split those up and iterate through them server-side.
JavaScript:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#addnew").click(function(e) {
$("#firstrow").clone() // copy the #firstrow
.removeAttr("id") // remove the duplicate ID
.append('<a class="remover" href="#">Remove</a>') // add a "remove" link
.insertAfter("#firstrow"); // add to the form
e.preventDefault();
});
$(".remover").live("click",function(e) {
// .live() acts on .removers that aren't created yet
$(this).parent().remove(); // remove the parent div
e.preventDefault();
});
});
</script>
HTML:
Add New Row
<form id="myform">
<div id="firstrow">
Name: <input type="text" name="name[]" size="5">
Year: <input type="text" name="year[]" size="4">
Description: <input type="text" name="desc[]" size="6">
</div>
<div>
<input type="submit">
</div>
</form>
Try enclosing them in a div element and then you can just remove the entire div.
Try this
Markup
<div class="inputFields">
..All the input fields here
</div>
Add
<div class="additionalFields">
</div>
JS
$("#add").click(function(){
var $clone = $(".inputFields").clone(true);
$clone.append($("<span>Remove</span").click(functio(){
$(this).closest(".inputFields").remove();
}));
$(".additionalFields").append($clone);
});
There are 2 plugins you may consider:
jQuery Repeater
jquery.repeatable
This question has been posted almost 4 years ago. I just provide the info in case someone needs it.

Categories