convert script from jQuery 1.9 to 1.8 - jquery-1.9

this script works in jQuery 1.9, but does not work in 1.8. How to convert this script to jQuery 1.8 ?
NOT Working Demo on jsfiddle
Working Demo on jsfiddle
HTML
<div id="container">
<div id="c1" class="aaa" style="text-align:right; color:red top:100px; ">child 1</div>
<div id="c2" class="aaa" style="text-align:left; top:200px; ">child 2</div>
</div>
jQuery script
$("#container").children().each( function () {
alert("element ID = " + $(this).attr('id'));
var styleProps = $(this).css(["width",
"height",
"color",
"background-color",
"text-align",
"left",
"top",
"right",
"bottom"]);
$.each(styleProps, function (prop, value) {
alert(prop + " = " + value);
});
});

The css function accepting an array wasn't implemented until 1.9.
You'll probably have to do it by hand if you're using 1.8 (loop through the values one at a time).
var styleNames = ["width", "height", "color", ...etc... ];
var i;
var $elem = jQuery(this);
for (i = 0; i < styleNames.length; ++i) {
alert(styleNames[i] + " = " + $elem.css(styleNames[i]));
}

Related

Form OnClick ReferenceError: comment is not defined

I'm trying to update my comment system and have run in to a snag. This is the error firebug is showing : ReferenceError: comment is not defined : comment(1000);
I'm at a loss to what the issue is - any ideas?
<div class="comment_heading">Leave a Comment</div>
<div class="post_comment">
<textarea name="txtpostcomment" id="txtpostcomment-1000" class="txtpostcomment"></textarea>
<button class="btnpostcomment" id="btnpostcomment-1000" onclick="comment(1000);" type="button">Send</button>
<input type="hidden" name="token" id="token" value="19vtyWh5iOpeKamXAQl3udqU9mMjnfKv/LnWr70M2jE=">
</div>
<script>
function comment(postid1)
{
var txt = $('#txtpostcomment-'+postid1);
var btn = $('#btnpostcomment-'+postid1);
var comment1 = $(txt).val();
var token = $("#token").val();
$(btn).css('background-image', 'url(/comments/submit-busy.gif)');
$(btn).attr('disabled', true);
var dataString = 'commenting=1&postid=' + postid1 + '&comment=' + comment1 + '&name=' + name + '&token=' + token;
.ajax({
url: "/comments/submit.php",
type: "POST",
data: dataString,
cache: false,
success: function()
{
$('.post_comment .error_msg').remove();
$('.comment-list-'+postid1).prepend(msg.html);
$(txt).val('');
},
error: function()
{
$('.post_comment .error_msg').value = 'Error - Please try again';
}
});
$(btn).css('background-image', 'none');
$(btn).attr('disabled', false);
$(txt).attr('disabled', false);
}
</script>
Solved .. all I needed to change was :
.ajax({
To :
$.ajax({

Auto complete with multiple keywords

I want . Auto complete text box with multiple keyword. it's from database. if I use jQuery and do operation in client side mean. If the database size is huge, it leads to some issues. I need to know how this is done on the server side and get proper result.
I have already seen this topic but the operation is done on the client side. I need it from the database directly.
<html>
<head>
<title>Testing</title>
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.srchHilite { background: yellow; }
</style>
<script src="scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
NewAuto();
});
function NewAuto() {
var availableTags = ["win the day", "win the heart of", "win the heart of someone"];
alert(availableTags); // alert = win the day,win the heart of,win the heart of someone
$("#tags").autocomplete({
source: function(requestObj, responseFunc) {
var matchArry = availableTags.slice(); // Copy the array
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches.
$.each(srchTerms, function(J, term) {
var regX = new RegExp(term, "i");
matchArry = $.map(matchArry, function(item) {
return regX.test(item) ? item : null;
});
});
// Return the match results.
responseFunc(matchArry);
},
open: function(event, ui) {
// This function provides no hooks to the results list, so we have to trust the selector, for now.
var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
var srchTerm = $.trim($("#tags").val()).split(/\s+/).join('|');
// Loop through the results list and highlight the terms.
resultsList.each(function() {
var jThis = $(this);
var regX = new RegExp('(' + srchTerm + ')', "ig");
var oldTxt = jThis.text();
jThis.html(oldTxt.replace(regX, '<span class="srchHilite">$1</span>'));
});
}
});
}
</script>
</head>
<body>
<div>
<label for="tags">
Multi-word search:
</label>
<input type="text" id="tags" />
</div>
</body>
</html>
take a look to Select2 it may help you.
Select2 is a jQuery based replacement for select boxes. It supports
searching, remote data sets, and infinite scrolling of results.
link
In your code, you have provided source as array. As you mentioned in comments, problem is how to get the data to source in jquery.
To make this work,
You need to do following
load jquery in header, which is you have already done.
Provid array,string or function for the source tag. [See api for
the source tag][1]
[1]: http://api.jqueryui.com/autocomplete/#option-source
In your serverside script, provid Jason encoded string.
If you check the API, you can see they have clear mentioned this.
Here is the jquery code
$(function() {
$( "#option_val" ).autocomplete({
dataType: "json",
source: 'search.php',
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
Here is the php code, Sorry if you use differnt serverside script language.
<?php
// Create connection
$con=mysqli_connect("localhost","wordpress","password","wordpress");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result=mysqli_query($con,"select * from wp_users");
while($row = mysqli_fetch_array($result))
{
$results[] = array('label' => $row['user_login']);
}
echo json_encode($results);
mysqli_close($con);
?>

How to initialize and load values for MultiSelect / Numeric / FileUpload within a KendoUI Custom Popup Editor?

I'm trying out KendoUI Web and I'm trying to get the multiselect, numeric, and fileupload widgets to display and function correctly in my custom popup editor. When clicking the Edit button the popup does not display multiselect, numeric, and fileupload correct and I cannot load the default value from the grid row into the multiselect widget (for example '1,2' in the sample data. When i click the Save button within the popup editor all the fields should populate into my text box (which seem to be working ok). I would like to stick to the HTML method of initializing widgets rather than using MVC.
If someone could please help with my issues.
I am unsure how to initialize the widgets (multiselect, numeric, and fileupload) because if i put the javascript initialization in the template, I get errors.
I cannot load default values from the grid row into my multiselect dropdown.
Does anyone know what needs to be done to get this to work correctly?
Here is my current code at http://jsfiddle.net/Xwtq3/
<h2>")
Users</h2>")
")
<div id=""example"" class=""k-content"">")
")
<input name=""txtAdvancedSearchString"" type=""text"" onchange=""javascript:setTimeout('__doPostBack")
")
(\'txtAdvancedSearchString\',\'\')', 0)"" onkeypress=""if (WebForm_TextBoxKeyHandler(event) == false) return false;"" ")
")
id=""txtAdvancedSearchString"" />")
<script>")
var mydata = [{")
guid: ""D007DD39-540B-4bc3-9900-39A8B931EB19"",")
fullname: ""Jeff"",")
email: ""jeffkent#testemail.com"",")
groups: ""1,2"",")
administrator: ""1"",")
url: ""jeff.jpg""")
}, {")
guid: ""E8CFD49A-3B85-4093-AE52-F55C73E12A7B"",")
fullname: ""Frank"",")
email: ""testemail#email.com"",")
groups: ""3,4"",")
administrator: ""1"",")
url: ""todd.jpg""")
}];")
</script>")
<div id=""grid""></div>")
<div id=""details""></div>")
<script>")
var wnd,")
detailsTemplate;")
")
$(document).ready(function() {")
")
")
var grid = $(""#grid"").kendoGrid({")
dataSource: {")
pageSize: 20,")
data: mydata")
},")
pageable: true,")
groupable: true,")
selectable: ""row"",")
reorderable: true,")
sortable: true,")
filterable: true,")
columnMenu: true,")
height: 430,")
columns: [{")
field: ""fullname"",")
title: ""Full Name""")
}, {")
field: ""email"",")
title: ""Email""")
}, {")
field: ""groups"",")
title: ""Groups""")
}, {")
field: ""administrator"",")
title: ""User Role""")
}, {")
field: ""url"",")
title: ""File URL""")
}, {")
command: {")
text: ""Edit"",")
click: showDetails")
},")
title: "" "",")
width: ""140px""")
}]")
}).data(""kendoGrid"");")
")
wnd = $(""#details"")")
.kendoWindow({")
title: ""Download"",")
modal: true,")
visible: false,")
resizable: false,")
width: 300")
}).data(""kendoWindow"");")
")
detailsTemplate = kendo.template($(""#template"").html());")
});")
")
function showDetails(e) {")
e.preventDefault();")
")
")
var dataItem = this.dataItem($(e.currentTarget).closest(""tr""));")
wnd.content(detailsTemplate(dataItem));")
wnd.center().open();")
}")
</script>")
<script type=""text/x-kendo-template"" id=""template"">")
<div id = ""details-container"" > <h2 > View / Edit User </h2>")
<table cellspacing=""6"" cellpadding=""3"">")
<tr>")
<td><label ID=""lblID"" for=""txtID"">ID:</label > <br /> <input type = ""text""")
id = ""txtID""")
class = ""k-textbox""")
placeholder = """"")
value = ""#= guid #"" > </input></td > </tr>")
<td><label ID=""lblFirstName"" for=""txtFirstName"">First Name:</label > <br /> <input type = ""text""")
id = ""txtFirstName""")
class = ""k-textbox""")
placeholder = """"")
value = ""#= fullname #"" > </input></td > </tr>")
<tr>")
<td>")
<!--MultiSelect Dropdown-->")
")
<select name=""groups"" id=""groups"" class=""k-item"" multiple=""multiple"" data-role=""dropdownlist"">")
<option value=""1"">HR</option > < option value = ""2"" > 1099 < /option>")
<option value=""3"">Insurance Form</option > < option value = ""4"" > Claim Form < /option>")
<option value=""4"">Timeoff Requests</option >")
")
</select>")
")
<!--MultiSelect Dropdown end--></td >")
")
</tr>")
<tr><td> ")
<input id=""txtMaxAdmins"" type=""number"" value=""#=administrator#"" min=""0"" max=""100"" />")
")
")
")
</td></tr >")
")
")
<tr> <td> <label")
for = ""upload"" > Document Types: </label>")
Choose a transparent .png for best results<br /> <input id = ""upload""")
type = ""file"" value=""#=url#"" />")
")
")
</td></tr> <tr > <td colspan = ""2"" > <button ID = ""btnSave""")
class = ""k-button""")
onclick = ""CallServer()"" > Save </button></td> </tr>")
</table> </div>")
</script>")
<script>")
function CallServer() {")
var userinput = ($(""#txtID"").val()) + '|' + ($(""#txtFirstName"").val()) + '|' + ($(""#groups"").val());")
document.getElementById(""txtAdvancedSearchString"").value = userinput;")
")
//alert(userinput);")
__doPostBack('__Page', 'e');")
}")
</script>")
</div>")
You need to tell KendoUI to use the html elements as kendo controls.

Can't get the autocomplete search form to work

I'm implementing a search form that displays suggestions as you start typing but can't get it to work..the problem is that when you start typing it doesn't shows any suggestion. Can you help me to get the code right? Many thanks!
This is the code:
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<div><input id="autocomplete" type="text"></div>
<script>
$("input#autocomplete").autocomplete({
source: [
{ id : "Google", value : "Google"},
{ id : "Yahoo", value : "Yahoo"},
],
minLength: 1,
open: function(event, ui) {
$("ul.ui-autocomplete").unbind("click");
var data = $(this).data("autocomplete");
console.log(data);
for(var i=0; i<=data.options.source.length-1;i++)
{
var s = data.options.source[i];
$("li.ui-menu-item a:contains(" + s.value + ")").attr("href", "/" + s.id);
}
}
});
/*
$("input#autocomplete").bind("autocompleteselect", function(event, ui) {
//alert(ui.item.id + ' - ' + ui.item.value);
//document.location.href = ui.item.id + '/' + ui.item.value;
//event.preventDefault;
} );
*/
</script>
Here Is the code:
<div id="search">
<input list="results" id="project" onkeydown="if (event.keyCode == 13) { checkInput(this.value); return false; }" />
</div>
The avaible results...
<datalist id="results">
<option>Demo</option>
<option>Example</option>
<option>pizza</option>
</datalist>
Finally the javascript
function checkInput(searchQuery)
{
if(searchQuery=="Home")
{
window.location = "Home.html";
}
else if(searchQuery == "Contact")
{
window.location = "Contact.html";
}
else if(searchQuery == "Sitemap")
{
window.location = "Sitemap.html";
}
else
{
window.location = "noresult.html";
}
}
So that way when ever someone goes to search they have a limited amount of options in the pre-populated list and which ever one they select leads them to your target page! I can't take all the credit, but I hope that helps!

Editing and deleting a newly added table row using Jquery

I'm adding new rows dynamically to the existing table, the first column of the table holds the Edit & Delete buttons. I'm facing 2 problems with this:
Not able to Edit and Delete newly added rows, tried .live but couldn't make it work
Not able to get the record id of the newly added rows (ajax returns the record when new rows are added).
Code looks like this:
Adding new rows:
<script type="text/javascript">
$(function() {
$('#btnSubmit').click(function() {
var oEmployee = new Object();
oEmployee.Title = $("#Title").val();
oEmployee.Middlename = $("#MiddleName").val();
oEmployee.Lastname = $("#LastName").val();
oEmployee.Email = $("#Email").val();
var DTO = {'employee': oEmployee};
var options = {
type: "POST",
url: "WebService.asmx/InsertEmployee",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d != "") {
if (parseInt(response.d) >= 1) {
var contactID;
contactID = parseInt(response.d);
$('#tblEmployee tbody tr:first').after("<tr id=" + contactID + "><td><input type='button' class='newContactID' value='Edit'/> <input type='button' value='Delete'/></td><td align=center>" + contactID + "</td><td align=center>" + oEmployee.Title + "</td><td align=center>" + oEmployee.Middlename + "</td><td align=center>" + oEmployee.Lastname + "</td><td align=center>" + oEmployee.Email + "</td><tr>"); // need to hook up editing and deleting function to the newly added rows }
else {
alert("Insert Failed \n" + response.d);
}
}
}
};
//Call the webservice
$.ajax(options);
});
});
</script>
Code for editing and deleting:
$(function() {
$("#tblEmployee > tbody > tr ").each(function() {
var TRID = $(this).attr("id");
$(this).find("td:first > input[value=Edit]").click(function() {
ResetOtherRowEdit();
ChangeTableCellToTextbox(TRID);
$(this).hide();
$("#tblEmployee > tbody > tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
return false;
});
$(this).find("td:first > input[value=Update]").click(function() {
UpdateRow(TRID);
});
$(this).find("td:first > input[value=Delete]").click(function() {
DeleteRow(TRID);
});
$(this).find("td:first > input[value=Cancel]").click(function() {
CancelEdit(TRID);
});
});
});
What is the best way to approach this? Editing and deleting of records work fine when they're pulled off the database.
Update
This is how the code looks like now, just began dabbling with Jquery a month back, still trying to get my head around it.
$(function() {
$("#tblEmployee > tbody > tr ").live('click', function(e) {
var TRID = $(this).attr("id");
var $target = $(e.target);
if ($target.is('#btnEdit')) {
$(this).find("td:first > input[value=Edit]").click(function() {
ResetOtherRowEdit();
ChangeTableCellToTextbox(TRID);
$(this).hide();
$("#tblEmployee > tbody > tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
return false;
});
}
else if ($target.is('#btnUpdate')) {
$(this).find("td:first > input[value=Update]").click(function() {
UpdateRow(TRID);
});
}
else if ($target.is('#btnCancel')) {
$(this).find("td:first > input[value=Cancel]").click(function() {
CancelEdit(TRID);
});
}
else if ($target.is('#btnDelete')) {
$(this).find("td:first > input[value=Delete]").click(function() {
DeleteRow(TRID);
});
}
});
});
HTML codes looks like this:
<ItemTemplate>
<tr id='<%# Eval("ContactID") %>'>
<td width="10%">
<input type="button" value="Edit" id="btnEdit"/>
<input type="button" value="Delete" id="btnDelete"/>
<input type="button" value="Update" style="display:none" id="btnUpdate" />
<input type="button" value="Cancel" style="display:none" id="btnCancel"/>
</td>
<td width="10%" align="center"><%# Eval("ContactID")%></td>
<td width="20%" align="center"><%# Eval("Title")%></td>
<td width="20%" align="center"><%# Eval("MiddleName")%></td>
<td width="20%" align="center"><%# Eval("LastName")%></td>
<td width="20%" align="center"><%# Eval("EmailAddress")%></td>
</tr>
</ItemTemplate>
You could take advantage of DOM traversal and .live() to make this work. Add a listener using .live() to the rows of the table. Inside this method, determine which element was clicked (e.currentTarget). You can use a simple conditional to check if it was a button that needs to react. Then, use DOM traversal to nail down what you want to have happen. For example, if e.currentTarget is the delete button, the you can use $(this).closest('tr').remove(); to delete the row. If you need to interact with the data through ajax, make your ajax function support passing in whatever valus you'd need (id) to perform the delete. In order to obtain the id, you'll need to get it from the ajax call and put it somewhere inside the DOM so you can retrieve it when you need it. You can always toss in a 'title' attribute when the tr is generated.
Here is a same script with php
http://www.amitpatil.me/add-edit-delete-rows-dynamically-using-jquery-php/
// Add new record
$(document).on("click","."+editbutton,function(){
var id = $(this).attr("id");
if(id && editing == 0 && tdediting == 0){
// hide editing row, for the time being
$("."+table+" tr:last-child").fadeOut("fast");
var html;
html += "<td>"+$("."+table+" tr[id="+id+"] td:first-child").html()+"</td>";
for(i=0;i<columns.length;i++){
// fetch value inside the TD and place as VALUE in input field
var val = $(document).find("."+table+" tr[id="+id+"] td[class='"+columns[i]+"']").html();
input = createInput(i,val);
html +='<td>'+input+'</td>';
}
html += '<td><img src="'+updateImage+'"> <img src="'+cancelImage+'"></td>';
// Before replacing the TR contents, make a copy so when user clicks on
trcopy = $("."+table+" tr[id="+id+"]").html();
$("."+table+" tr[id="+id+"]").html(html);
// set editing flag
editing = 1;
}
});