JQuery: How to clone autocomplete fields? - javascript

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.

Related

add custom lint error marker for codemirror

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).addClass is not working

While following a tutorial, I see style sheet is not applied to clicked element in the list. What Could be the possible reason?
The following sample works this way if some string is added to text box and then button is clicked, a new item gets added to list. If item in the list is clicked it should be stroked through.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#taskText').keydown(function (evt) {
if (evt.keyCode == 13) {
addTask(this, evt);
}
});
$('#addTask').click(function (evt) {
addTask(document.getElementById('taskText'), evt);
});
// following statements not working
$('#tasks li').live('click', function(evt) {
$(this).addClass('done');
});});
function addTask(textBox, evt) {
evt.preventDefault();
var taskText = textBox.value;
$('<li>').text(taskText).appendTo('#tasks');
textBox.value = "";
};
</script>
<style type="text/css">
.done{
text-decoration:line-through;
}
</style>
</head>
<body>
<ul id="tasks">
</ul>
<input type="text" id="taskText" />
<input type="submit" id="addTask"/>
</body>
</html>
The live() function was removed in jQuery 1.7 and does not exist at all in jQuery 2.x.
If you check your browser's developer console, chances are you'll see an error message along those lines.
$(document).ready(function() {
$('#addTask').click(function() {
var taskText = $('#taskText').val();
var li = $('<li>' + taskText + '</li>');
$('ul#tasks').append(li);
$('#taskText').val('');
$(li).click(function() {
$(this).toggleClass('done');
});
});
});
li {
font-family: arial;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
}
.done{
text-decoration: line-through;
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul id="tasks">
<!-- List Goes Here... -->
</ul>
<!-- Textbox / Input Buttons -->
<input type="text" id="taskText" />
<input type="submit" id="addTask"/>
</body>
</html>
$('#tasks li').click(function(){
$(this).addClass('class-name');
};
should work. Check to make sure all your syntax is correct (ie. no random semicolons)
As mentioned by ceejayoz . The live() function was removed in jQuery 1.7 and does not exist at all in jQuery 2.x.
The reason your click on the list was not working is better explained on this question: Click event on dynamically generated list items using jquery
here's what the code could look like for you
$(document).ready(function() {
$('#taskText').keydown(function(evt) {
if (evt.keyCode == 13) {
addTask(this, evt);
}
});
$('#addTask').click(function(evt) {
addTask($('#taskText'), evt);
});
$('#tasks').on('click', 'li', function(evt) {
$(this).addClass('done');
});
});
function addTask(textBox, evt) {
evt.preventDefault();
var taskText = textBox.val();
$('<li>').text(taskText).appendTo('#tasks');
textBox.val("");
};
.done {
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tasks">
</ul>
<input type="text" id="taskText" />
<input type="submit" id="addTask" />

Append extra row to jqueryui autocomplete (even if autocomplete doesn't have any matches)

How should an extra row be added to the jQueryUI Autocomplete results? I've implemented Add additional link to jquery ui autocomplete list as shown below, but it will not display the extra row if autocomplete doesn't have any matches.
What I have tried...
To append an extra row to the jQueryUI autocomplete results, I came up with the below script. The extra row is added using the following:
open: function( event, ui ) {
$('<li id="add-new">Add New</li>')
.on('click', function(event) {$("#dialog-add-new").dialog("open");})
.appendTo('ul.ui-autocomplete');
}
I have three problems with my implementation:
If no results match the selected text, the new row isn't displayed. Type "On" in the input and you will see it. Type "xx" in the input and it isn't displayed. I suppose I could just have the server populate it, but seems like a waste, and would rather do it client-side.
Maybe problems if I have two ul.ui-autocomplete on the page?
The added row doesn't have the same appearance as the autocomplete rows.
The first item is the most critical. How should an extra row be added to the jQueryUI Autocomplete results even if Autocomplete doesn't have any results?
Please see http://jsbin.com/quyexu/1/ for a live demo of the below script. You could ignore the part regarding the dialog as it seems to be working. Thank you
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/ui-lightness/jquery-ui.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js" type="text/javascript"></script>
<style type="text/css">
</style>
<script type="text/javascript">
var source = [
{value: "one",id: 1},
{value: "two",id: 2},
{value: "three",id: 3}
];
$(function(){
$("#autocomplete").autocomplete({
source: source,
minLength: 1,
focus: function( event, ui ) {event.preventDefault();$(this).val( ui.item.label );},
select: function(event, ui) {
console.log(ui)
$(this).val('');//.blur();
event.preventDefault(); // cancel default behavior which updates input field
$("#my-list").append('<li data-id="'+ui.item.id+'">'+ui.item.value+'</li>');
},
open: function( event, ui ) {
console.log(event,ui,this);
$('<li id="add-new">Add New</li>')
.on('click', function(event) {$("#dialog-add-new").dialog("open");})
.appendTo('ul.ui-autocomplete');
}
});
$("#dialog-add-new").dialog({
autoOpen: false,resizable: false,height: 200,width: 380, modal: true,
open : function() {},
buttons : [
{
text : 'ADD NEW',
"class" : 'green wide',
click : function() {
//Use Ajax to save value and get associated ID
var name=$('#new-name').val();
var id=123;
$("#my-list").append('<li data-id="'+id+'">'+name+'</li>');
$("#autocomplete").val('').focus();
$(this).dialog("close");
}
},
{
text : 'CLOSE',
"class" : 'gray',
click : function() {$(this).dialog("close");}
}
]
});
});
</script>
</head>
<body>
<input type="text" id="autocomplete" />
<ul id="my-list"></ul>
<div id="dialog-add-new" class="dialog" title="Add New">
<form>
<input type="text" name="new-name" id="new-name" />
</form>
</div>
</body>
</html>
To add an extra row, use the response event. http://api.jqueryui.com/1.10/autocomplete/#event-response
http://jsbin.com/wokuma/1/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/ui-lightness/jquery-ui.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js" type="text/javascript"></script>
<style type="text/css">
</style>
<script type="text/javascript">
var source = [
{value: "one",id: 1},
{value: "two",id: 2},
{value: "three",id: 3}
];
$(function(){
$("#autocomplete").autocomplete({
source: source,
minLength: 1,
focus: function( event, ui ) {event.preventDefault();$(this).val( ui.item.label );},
select: function(event, ui) {
console.log(ui)
$(this).val('');//.blur();
event.preventDefault(); // cancel default behavior which updates input field
if(ui.item.id===0){$("#dialog-add-new").dialog("open");}
else {$("#my-list").append('<li data-id="'+ui.item.id+'">'+ui.item.value+'</li>');}
},
response: function( event, ui ) {
console.log(event,ui,this);
ui.content.push({value:"Add New", id:0, label:"Add New"});
}
});
$("#dialog-add-new").dialog({
autoOpen: false,resizable: false,height: 200,width: 380, modal: true,
open : function() {},
buttons : [
{
text : 'ADD NEW',
"class" : 'green wide',
click : function() {
//Use Ajax to save value and get associated ID
var name=$('#new-name').val();
var id=123;
$("#my-list").append('<li data-id="'+id+'">'+name+'</li>');
$("#autocomplete").val('').focus();
$(this).dialog("close");
}
},
{
text : 'CLOSE',
"class" : 'gray',
click : function() {$(this).dialog("close");}
}
]
});
});
</script>
</head>
<body>
<input type="text" id="autocomplete" />
<ul id="my-list"></ul>
<div id="dialog-add-new" class="dialog" title="Add New">
<form>
<input type="text" name="new-name" id="new-name" />
</form>
</div>
</body>
</html>

Seekbar with range of two values (min and max)

I am working on a search functionality.I need to select min price and max price with a seekbar.
I have searched a lot in google, But I found seekbar with one value.Below is the code I got.
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#slider { margin: 10px; }
</style>
<script>
$(document).ready(function () {
$("#slider").slider(
{
min: 0,
max: 100,
step: 1,
change: showValue
});
$("#update").click(function () {
$("#slider").slider("option", "value", $("#seekTo").val());
});
function showValue(event, ui) {
$("#val").html(ui.value);
}
});
</script>
</head>
<body style="font-size:62.5%;">
<p>
The jQuery UI Slider plugin makes selected elements into sliders. There are various options such as multiple handles, and ranges. The handle can be moved with the mouse or the arrow keys.
</p>
<p>
This sample demonstrates the simple usage of the slider seek to function.
For more information about slider, please procedd to http://docs.jquery.com/UI/Slider
</p>
<div id="slider"></div>
Seek To : <input id="seekTo" type="text" value="10" />
<input id="update" type="button" value="Update" />
Current Value : <span id="val">0</span>
</body>
</html>
Some one help me how to have both min and max values with single bar..
I am working on PHP website. If you have any example code in php , it will be helpful..
Additional One:
And one more doubt, If this is not a range of values,and if it is like A A+ B B+ C C+ ... How can we take them in this type of seekbar..
Use range: true option!
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#slider { margin: 10px; }
</style>
<script>
$(document).ready(function () {
$("#slider").slider(
{
range: true,
min: 0,
max: 100,
step: 1,
values: [10, 50],
change: showValue
});
$("#update").click(function () {
$("#slider").slider("option", "values", [$("#seekTo1").val(), $("#seekTo2").val()]);
});
function showValue(event, ui) {
$("#val").html(ui.values[0] + " - " + ui.values[1]);
}
});
</script>
</head>
<body style="font-size:62.5%;">
<p>
The jQuery UI Slider plugin makes selected elements into sliders. There are various options such as multiple handles, and ranges. The handle can be moved with the mouse or the arrow keys.
</p>
<p>
This sample demonstrates the simple usage of the slider seek to function.
For more information about slider, please proceed to http://docs.jquery.com/UI/Slider
</p>
<div id="slider"></div>
Seek To : <input id="seekTo1" type="text" value="10" /> <input id="seekTo2" type="text" value="50" />
<input id="update" type="button" value="Update" />
Current Value : <span id="val">0 - 50</span>
</body>
</html>

html calender(datepicker) with an addable event

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>

Categories