Hi I am looking to allow uses to add events into a calender(using date-picker at the moment) by entering data into text-boxes then clicking on a date on the calender then hitting submit. I want events to be highlighted and when a date is clicked on (with an event on it) the event pops up with the information.
Tried to search but I did not have any luck.
Thank you
EDIT: Changed a bit of the code so it compiled properly
I would also like to simply reference the date that is selected so that I may use it to record the data. To use this program simply type in your values than hit refresh and the new values will be loaded into the 13th of may.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>jQuery & jQueryUI Base - jsFiddle demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.7/themes/black-tie/jquery-ui.css">
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js"></script>
<style type='text/css'>
table.ui-datepicker-calendar tbody td.highlight > a {
background: url("images/ui-bg_inset-hard_55_ffeb80_1x100.png") repeat-x scroll 50% bottom #FFEB80;
color: #363636;
border: 1px solid #FFDE2E;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var equip = document.getElementById('equipment').value;
var size = document.getElementById('size').value;
var surface = document.getElementById('surface').value;
var orderNumber = document.getElementById('orderNumber').value;
var responsible = document.getElementById('responsible').value;
var events = [
{ Title: "Equipment: " + equip + "\nSize: " + size, Date: new Date("05/13/2013") },
{ Title: "Dinner", Date: new Date("02/25/2011") },
{ Title: "Meeting with manager", Date: new Date("03/01/2011") }
];
$("div").datepicker({
beforeShowDay: function(date) {
var result = [true, '', null];
var matching = $.grep(events, function(event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
result = [true, 'highlight', null];
}
return result;
},
onSelect: function(dateText) {
var date,
selectedDate = new Date(dateText),
i = 0,
event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
event = events[i];
}
i++;
}
if (event) {
alert(event.Title);
}
}
});
});//]]>
addLow()
</script>
</head>
<body>
Equipment: <input type='text' id='equipment' /> <br />
Size: <input type='text' id='size' /> <br />
Required on Surface: <input type='radio' id='surface' /> <br />
Work Order Number: <input type='text' id='orderNumber' /> <br />
Responsible: <input type='text' id='responsible' /> <br />
<div></div>
<button type="button" onclick="addLow()">Add Lowering Event</button><br>
</body>
</html>
Related
I receive the errors in my code from an external API. It gives me the
1)line number
2) error description
I could achieve the highlighting process but I need to add a lint error marker on the left side of the textarea.
The following code enable me to add lint marker when the page is load by definingoption called 'lintWith', However, I need to add these lint markers when I click on the button.
The is the code I'm using:
<html>
<head>
<link rel="stylesheet" href="codemirror/lib/codemirror.css">
<script src="codemirror/lib/codemirror.js"></script>
<script src="codemirror/addon/edit/matchbrackets.js"></script>
<script src="codemirror/mode/python/python.js"></script>
<!-- <script src="codemirror/addon/selection/active-line.js"></script> -->
<link rel="stylesheet" href="codemirror/addon/lint/lint.css">
<script src="codemirror/addon/lint/lint.js"></script>
<script src="codemirror/addon/lint/javascript-lint.js"></script>
<script src="cm-validator-remote.js"></script>
<style type="text/css">
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
.CodeMirror-empty { outline: 1px solid #c22; }
</style>
</head>
<body>
<div><textarea id="code" name="code" placeholder="Code goes here...">
mycode
pass
a__ = 5
Check
Hello World
123456
</textarea></div>
</body>
<script type="text/javascript">
function check_syntax(code, result_cb)
{
var error_list = [{
line_no: 2,
column_no_start: 14,
column_no_stop: 17,
fragment: "def doesNothing:\n",
message: "invalid syntax.......",
severity: "error"
}, {
line_no: 4,
column_no_start: 1,
column_no_stop: 3,
fragment: "a__ = 5\n",
message: "convention violation",
severity: "error"
}]
result_cb(error_list);
}
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: { name: "python",
version: 2,
singleLineStringErrors: false },
lineNumbers: true,
indentUnit: 4,
tabMode: "shift",
gutters: ["CodeMirror-lint-markers"],
lintWith: {
"getAnnotations": CodeMirror.remoteValidator,
"async": true,
"check_cb": check_syntax
}
});
function AddLintMarker(){
// I want to add the lintWith markers when click on this button
// i've tried like this editor.setOption("lintWith.getAnnotations",CodeMirror.remoteValidator ) but it doesn't work
}
</script>
<input type="button" value="add boxes" onclick="AddLintMarker()">
</html>
Here the code lint marker is added when the page is load because it is assigned to the editor but I want the lint maker to shows only when I click on the button and provide values to the check_syntx function,
and for the lintWith it is defined in the lint.js as the following :
CodeMirror.defineOption("lintWith", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
clearMarks(cm);
cm.off("change", onChange);
CodeMirror.off(cm.getWrapperElement(), "mouseover", cm._lintState.onMouseOver);
delete cm._lintState;
}
if (val) {
var gutters = cm.getOption("gutters"), hasLintGutter = false;
for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
var state = cm._lintState = new LintState(cm, parseOptions(val), hasLintGutter);
cm.on("change", onChange);
CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
startLinting(cm);
}
});
You need to use setGutterMarker method from CodeMirror. It takes line, markerId and markerElement and put it to the needed line on the gutter area.
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
indentUnit: 4,
gutters: ["CodeMirror-lint-markers"],
});
function makeMarker() {
var marker = document.createElement("div");
marker.innerHTML = `<div>⚠️</div>`;
marker.setAttribute("title", "Some text");
return marker;
}
editor.doc.setGutterMarker(1, "CodeMirror-lint-markers", makeMarker());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.3/codemirror.min.js"
integrity="sha512-/8pAp30QGvOa8tNBv7WmWiPFgYGOg2JdVtqI8vK+xZsqWHnNd939v9s+zJHXZcJe5wPD44D66zz+CLTD3KacYA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.3/codemirror.min.css"
integrity="sha512-uf06llspW44/LZpHzHT6qBOIVODjWtv4MxCricRxkzvopAlSWnTf6hpZTFxuuZcuNE9CBQhqE0Seu1CoRk84nQ=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<textarea id="code" name="code" placeholder="Code goes here...">
mycode
pass
a__ = 5
Check
Hello World
123456
</textarea>
</body>
</html>
This example prompts for barcode scan, and then places the value into "scan-input" box. This works great for ONE input/ONE button.
My issue is i want to be able to add multiple inputs/buttons, and have the scan then place the value in the corresponding input text box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'/>
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN
</button>
</div>
<script>
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, { engineLocation: engineLocation });
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
const scanInput = document.getElementById("scan-input");
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>#scan:after {display:none;}</style>
</html>`
I want to be able to add multiple buttons/inputs. and have the corresponding button place it into the scan-input spot.
`<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN</button>
<input id="scan-input2" type="text" placeholder="Scan Receiver #2...">
<button id="scan2" onclick="scan()">SCAN</button>`
[text1] [button1] ----- scan places value into text1
[text2] [button2] ----- scan places value into text2
Here's a slightly adapted version of your HTML (using a digit in every id will help us keep things simpler):
<input type="text" id="scan-input1" />
<button type="button" id="scan1">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2">SCAN</button>
Then, in our JavaScript, we can use the following function to send a message to scan-input1 if scan1 is pressed, scan-input2 if scan-2 is pressed, and so on:
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
document.getElementById(`scan-input${num}`).value = "Scan Complete";
});
});
The code above:
Adds a click event listener to every button,
Gets the number from the id of whichever button is clicked,
Uses that number to target the correct input.
The advantage of the solution above is that it scales automatically. As long as you follow the same naming convention for each id (scan3, scan-input3, etc.), every a new button and input will have identical behaviour.
Edit: Your Code
Below, I've inserted my suggestion into your code - only changing the bare minimum:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input type="text" id="scan-input1" />
<button type="button" id="scan1" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input3" />
<button type="button" id="scan3" placeholder="Scan Receiver...">SCAN</button>
</button>
</div>
<script>
let scanInput;
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
scanInput = document.getElementById(`scan-input${num}`);
scan();
});
});
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, {
engineLocation: engineLocation
});
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>
#scan:after {
display: none;
}
</style>
</html>`
In order to add a feature to a existing application I'm attempting to use JavaScript to add together input fields which need to stay as text field types and show the end result text field as a total of those fields. I can easily make it work adding the numbers together. However the numbers will be typed in with commas and decimals every time. When this happens the adding breaks and doesn't work. Anyone have any ideas of how I could possibly make this work?
HTML CODE
<form method="post">
<input type="text" id="the_input_id">
<input type="text" id="the_input_id1">
<input type="text" id="total">
JavaScript
$(function() {
$('#the_input_id').keyup(function() {
updateTotal();
});
$('#the_input_id1').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#the_input_id').val());
var input2 = parseInt($('#the_input_id1').val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('#total').val($('#the_input_id').val());
}
if(!input1){
$('#total').val($('#the_input_id1').val());
}
} else {
$('#total').val(input1 + input2);
}
};
var output_total = $('#total');
var total = input1 + input2;
output_total.val(total);
});
How about something like this?
var num1 = "1,000,000.00"
var num2 = "1,000,000.25"
var re = /,/gi;
var num1a = num1.replace(re,''); // strip commas
var num2a = num2.replace(re, ''); // strip commas
var sum = Number(num1a) + Number(num2a); // convert to Number and add together
console.log(sum); // before formatting
var total = Number(sum).toLocaleString(); // formatted
console.log(total)
Read my comment above, then take a look here:
//<![CDATA[
/* js/external.js */
$(function(){
var num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.text('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.text('Numbers Required').addClass('er');
}
else if(s === ''){
total.text('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.text('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.text('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.text('Second Input Requires Number').addClass('er');
}
else{
total.text(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:0 3px;
}
.er{
color:#900;
}
#total{
display:inline-block;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<input type='text' id='num1' /> +
<input type='text' id='num2' /> =
<div class='er' id='total'>Awaiting Input</div>
</div>
</body>
</html>
Note that you can use + in front of a String to cast it to a number... and that JavaScript has a Floating Point Number Math issue.
Here is a <form> example:
//<![CDATA[
/* js/external.js */
$(function(){
var form = $('#form'), num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.val('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.val('Numbers Required').addClass('er');
}
else if(s === ''){
total.val('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.val('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.val('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.val('Second Input Requires Number').addClass('er');
}
else{
total.val(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
form.submit(function(e){
console.log(form.serialize());
// run a bunch of tests using if conditions and the like before AJAXing - $.post example shown
/*
$.post('sendToPage.php', form.serialize(), function(jsonResult){
// should get echo json_encode($objOrAssocArray); from PHP as jsonResult now
}, 'json');
*/
// prevents old school submission
e.preventDefault();
});
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:3px 5px;
}
.symbol{
display:inline-block; width:18px; text-align:center;
}
.er{
color:#900;
}
#total{
width:calc(100% - 236px);
}
input[type=submit]{
width:100%; height:30px; background:#007; color:#fff; border:0; border-radius:5px; margin-top:4px; cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<form id='form'>
<input type='text' id='num1' name='num1' /><div class='symbol'>+</div><input type='text' id='num2' name='num2' /><div class='symbol'>=</div><input type='text' class='er' id='total' name='total' value='Awaiting Input' readonly='readonly' />
<input type='submit' id='sub' value='Submit Test' />
</form>
</div>
</body>
</html>
Maybe something like this by simply extracting only numbers from any string the user inputs:
$(function () {
var $firstInput = $('#first');
var $secondInput = $('#second');
var $totalInput = $('#total')
$firstInput.keyup(updateTotal);
$secondInput.keyup(updateTotal);
function extractNumbers(str, def) {
var onlyNumbers = '';
for (var i = 0; i < str.length; ++i) {
var currChar = str.charAt(i);
if (!isNaN(currChar)) {
onlyNumbers += currChar;
}
}
return parseInt(onlyNumbers) || def;
}
function updateTotal () {
var valInput1 = extractNumbers($firstInput.val(), 0)
var valInput2 = extractNumbers($secondInput.val(), 0)
var total = valInput1 + valInput2;
$totalInput.val(total);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input type="text" placeholder="first number..." id="first">
<input type="text" placeholder="second number..." id="second">
<input type="text" placeholder="total number..." id="total">
</body>
</html>
Here is my HTML -
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> My Shopping List</title>
<link rel="stylesheet" type="text/css" href="shoppinglist.css">
<link href='http://fonts.googleapis.com/css?family=Quicksand:300,400|Advent+Pro:300' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="shoppinglist.js"></script>
</head>
<body>
<div class="container">
<p id="shoppinglist"> My Shopping List App</p>
<input type="text" name="user" class="entertext">
<input type="button" value="Enter" class="returnkey">
<br>
<br>
<ol></ol>
</div>
</body>
</html>
Here is my JavaScript -
$(document).ready(function () {
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$("input[type='text']").keyup(function(event) {
if(event.keyCode == 13) {
$("input[type='button']").click();
}
});
$("ol").on("click", "input[type='checkbox']", function() {
$(this).parent().remove();
});
});
How do I create JavaScript for someone whose entering empty? So something to prevent them from empty text input?
You can check if the value of the text input is equal to a blank string:
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
//start new code
if ($.trim(item) === '') {
alert("Please Enter Something!");
return false;
}
//end new code
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$.trim() removes any extra white-space, to make sure the input doesn't just have white-space as a value.
Something like this?
$('.returnkey').on('click', function() {
var string = $.trim($('.entertext').val());
if (string == '') {
alert('Field is empty');
return false;
}
}
I am using Jörn Zaefferer's jquery autocomplete plugin, and I can't seem to figure out how to make it work when I clone an autocomplete field. It almost works, in that the cloned autocomplete field displays the choices when the I type in text, but I cannot select items. At first I thought it was a browser-compatibility issue, but it happens in both FF3 and Safari, so I'm guessing there's a gotcha I've missed.
Here is a working example of what I'm doing:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Autocomplete Clone Demo</title>
<style>
body {
margin: 40px;
}
.hide_element {
display: none;
}
</style>
<link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
<script type="text/javascript">
function setAutocomplete()
{
var users = [
{ name: "Fred", id: "1" },
{ name: "Barney", id: "2" },
{ name: "Wilma", id: "3" }
];
$(".user_selector").autocomplete(users,
{
mustMatch: true,
matchContains: true,
minChars: 2,
formatResult: function(row) { return row.name; },
formatItem: function(row, i, max) { return row.name; }
}
);
}
var current= 0;
var addParticipantFields = function()
{
current++;
$newParticipant = $("#template").clone(true);
$newParticipant.removeAttr("id");
$newParticipant.removeClass("hide_element");
$prefix = "extra" + current;
$newParticipant.children("div").children(":input").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("name",$prefix+$currentElem.attr("name"));
});
$newParticipant.appendTo("#participantsField");
setAutocomplete();
}
$(document).ready(function() {
setAutocomplete();
$("#addParticipant").live("click", addParticipantFields);
});
</script>
</head>
<body>
<h1>Test Autocomplete Cloning</h1>
<form id="demo" method="post" action="">
<fieldset id="participantsField">
<label>Participants</label>
<div class="participant">
<input class="user_selector" name="user" size="30"/>
</div>
</fieldset>
<!-- This is the template for adding extra participants -->
<div class="participant hide_element" id="template">
<input class="user_selector" name="_user" size="30"/>
</div>
<p><input type="button" id="addParticipant" value="Add Another Participant"></p>
<p><input class="button" type="submit" value="Submit"/></p>
</form>
</body>
</html>
Make
$newParticipant = $("#template").clone(true);
like so
$newParticipant = $("#template").clone();
Your example works for me in FF when you don't clone events on #template.
first of all:
$newParticipant.children("div").children(":input").length == 0
so there is no children returned by this line.
Use
$newParticipant.children()
instead. It returns 1 chield instead. But steel don't work for me. Have to think more.