Search Results

Search found 23356 results on 935 pages for 'jquery ui'.

Page 3/935 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How to change Jquery UI Slider handle

    - by Tom
    I want to modify the stock JQuery UI slider so that the handle has a arrow on it rather than being a square. i.e. I want to use a custom image as the handle. There are a few tutorials that do it: http://jqueryfordesigners.com/slider-gallery/ http://www.ryancoughlin.com/2008/11/04/using-the-jquery-ui-slider/ http://www.keepthewebweird.com/creating-a-nice-slider-with-jquery-ui/ But I can't get it to work. The following code results in a stationary handle image: <!DOCTYPE html> <html> <head> <link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" /> <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script> <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script> <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script> <style type="text/css"> #myhandle {position: absolute;z-index: 100;height: 25px;width: 35px;top: auto;background: url(http://stackoverflow.com/content/img/so/vote-arrow-down.png) no-repeat;} </style> <script type="text/javascript"> $(document).ready(function(){ $("#slider").slider({handle: '#myhandle'}); }); </script> </head> <body> <div id="slider"><div id="myhandle"></div></div> </body> </html> It is as if JQuery doesn't pick up that I want to use the myhandle id for the handle. I'm wondering: Do I need a plugin for JQuery to recognise the handle option? (it is not documented in http://docs.jquery.com/UI/Slider). Or perhaps it only worked in an old version of JQuery? Any ideas?

    Read the article

  • jQuery UI autocomplete not working in IE

    - by Peter Di Cecco
    Hi all, I've got the new autocomplete widget in jQuery UI 1.8rc3 working great in Firefox. It doesn't work at all in IE. Can someone help me out? HTML: <input type="text" id="ctrSearch" size="30"> <input type="hidden" id="ctrId"> Javascript: $("#ctrSearch").autocomplete({ source: "ctrSearch.do", minLength: 3, focus: function(event, ui){ $('#ctrSearch').val(ui.item.ctrLastName + ", " + ui.item.ctrFirstName); return false; }, select: function(event, ui){ $('#ctrId').val(ui.item.ctrId); return false; } }); Result (IE 8): The red box is the <ul> element created by jQuery. I also get this error: Line: 116 Error: Invalid argument. When I open it in the IE8 script debugger, it highlights f[b]=d on line 116 of jquery.min.js. Note that I'm using version 1.4.2 of jQuery hosted on Google's servers (https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js). I've tried removing some of the options, but even when I call .autocomplete() with no options, or with only the source option, I still get the same result. Once again, it's working in Firefox, but not in IE. Any suggestions? Thanks.

    Read the article

  • JQUERY, Compare two Text Blocks, and then animate only the new text

    - by nobosh
    I have two blocks of text Text Block 1 - Currently displayed on the page: "Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa" But now Block 1 on the backend is: "Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsaadskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasdadskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsaadskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasdadskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsaadskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsaadskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsaadskadskl1lksad klasd klasd dsa Ahd Hd ahaSdjdajs dadjs jasd adskadskl1lksad klasd klasd dsa" I'd like to update the original Block 1 that's on the page, with the Block 2 that's on the server to the page. And I'd like to append, and not flash the entire block. So only the new stuff is flashed. Any ideas on how to do this in JQUERY?

    Read the article

  • Drag and drop not working while using JQuery UI dialog

    - by user327854
    Hi Guys ! I m using jquery ui.core.js with version 1.7.2 and jquery-1.4.2.js . I got the issue saying "proto.plugins"(query ui.core.js for draggable module) is undefined ,hence i am not able to perform the drag option.My Code is given below. $("#linkfortag").click(function(){ var $dialog=$("<div id='testing'></div>").dialog({autoOpen:false}); $dialog.dialog("destroy"); $dialog.draggable(); alert("$dialog is" + $dialog.html()); $dialog.dialog('open'); $dialog.dialog({title:'Add Tag',resizable:true,closeOnEscape:true,modal:true,minWidth:250,buttons:{ 'Add Tag':function() { alert($(this).children().children().children(':input').attr('value')); var value=$("#addTag").attr('value'); var formobj=$(this).children(); validate_usertagform(value); } ,'Cancel': function() {$(this).dialog('close');}}}); $dialog.bind("dialogbeforeclose",function(event,ui){ alert("Dialog is gng to close"); alert("<<<<<<<<<<<<<<<<<UI IS>>>>>>>>>>>>>>>>>>>>>>" + ui); }); $dialog.bind("drag",function(event,ui){ alert("<<<<<<<<<<<<<<<<<drag is>>>>>>>>>>>>>" + event); }); $dialog.dialog( "option", "closeText", '' ); $dialog.dialog("option","draggable",true); }); Please help me on this........

    Read the article

  • JQuery Mobile: Fire Mobileinit Event

    - by Yousef_Jadallah
     Many people asked that the Mobileinit event didn't work. Simplicity just you need to follow this sequence: <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css" />     <script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>     <script>         $(document).bind("mobileinit", function () {             alert('mobileinit is fired');         });     </script>     <script src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script> Hope that helps.  

    Read the article

  • Extending jQuery with jQuery.Extend

    - by Jalpesh P. Vadgama
    We all know that jQuery is a great JavaScript framework. It’s provide lots of functionalities and most used framework in programming world. But sometimes we need a functionality that does not provided by jQuery by default. At that time we need to extend jQuery. We can extend jQuery with jQuery.Extend  Method. You can get complete information from the following link. http://api.jquery.com/jQuery.extend/ It merges the contents of two or more objects together into the first object. More on my personal blog @www.dotnetjalps.com

    Read the article

  • jquery plus minus sign on collaps and expand

    - by user295189
    hi I am using the code below. What I wanted is to have a + or - sign on expanded or collapsed view. How can I do that. Here is the code Thanks in advance! XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX <!--//---------------------------------+ // Developed by Roshan Bhattarai | // http://roshanbh.com.np | // Fell Free to use this script | //---------------------------------+--> <title>Collapsible Message Panels</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ //hide the all of the element with class msg_body $(".msg_body").show(); //toggle the componenet with class msg_body $(".msg_head").click(function(){ $(this).next(".msg_body").slideToggle(100); }); }); </script> <style type="text/css"> body { margin: 10px auto; width: 570px; font: 75%/120% Verdana,Arial, Helvetica, sans-serif; } p { padding: 0 0 1em; } .msg_list { margin: 0px; padding: 0px; width: 383px; } .msg_head { padding: 5px 10px; cursor: pointer; position: relative; background-color:#FFCCCC; margin:1px; } .msg_body { padding: 5px 10px 15px; background-color:#F4F4F8; } </style> </head> <body> <div align="center"> <p>Click on the each news head to toggle </p> </div> <div class="msg_list"> <p class="msg_head">Header-1 </p> <div class="msg_body"> orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit </div> <p class="msg_head">Header-2</p> <div class="msg_body"> orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit </div> </div> </body> </html>

    Read the article

  • jQuery.post() issues with passing data to jQuery UI

    - by solefald
    Hello, I am trying to get jQuery.post() to run my php script and then open a jQuery UI dialog with the data that php script returns. Its supposed to come back as a form with a table and a textarea in it. It works great with alert(data); and i get a pop-up with all my data. The problem starts if i turn off alert(). Now it opens 2 dialogs. One containing only the table, without textarea, and the second one absolutely empty. What am i doing wrong here? How come all my data shows up in the alert(), but not in dialog? What do i need to do to fix it? Oh, and do i need to also include $.ajax() before the $.post()? Thank you. $.post("/path/to/script.php", { id: this.id, value: value }, function(data){ // THIS WORKS //alert(data); // THIS DOES NOT WORK $(data).dialog({ autoOpen: true, width: 400, modal: true, position: 'center', resizable: false, draggable: true, title: 'Pending Changes' }); } );

    Read the article

  • jquery Uncaught SyntaxError: Unexpected token )

    - by js00831
    I am getting a jquery error in my code... can you guys tell me whats the reason for this when you click the united states red color button in this link you will see this error http://jsfiddle.net/SSMX4/88/embedded/result/ function checkCookie(){ var cookie_locale = readCookie('desired-locale'); var show_blip_count = readCookie('show_blip_count'); var tesla_locale = 'en_US'; //default to US var path = window.location.pathname; // debug.log("path = " + path); var parsed_url = parseURL(window.location.href); var path_array = parsed_url.segments; var path_length = path_array.length var locale_path_index = -1; var locale_in_path = false; var locales = ['en_AT', 'en_AU', 'en_BE', 'en_CA', 'en_CH', 'de_DE', 'en_DK', 'en_GB', 'en_HK', 'en_EU', 'jp', 'nl_NL', 'en_US', 'it_IT', 'fr_FR', 'no_NO'] // see if we are on a locale path $.each(locales, function(index, value){ locale_path_index = $.inArray(value, path_array); if (locale_path_index != -1) { tesla_locale = value == 'jp' ? 'ja_JP':value; locale_in_path = true; } }); // debug.log('tesla_locale = ' + tesla_locale); cookie_locale = (cookie_locale == null || cookie_locale == 'null') ? false:cookie_locale; // Only do the js redirect on the static homepage. if ((path_length == 1) && (locale_in_path || path == '/')) { debug.log("path in redirect section = " + path); if (cookie_locale && (cookie_locale != tesla_locale)) { // debug.log('Redirecting to cookie_locale...'); var path_base = ''; switch (cookie_locale){ case 'en_US': path_base = path_length > 1 ? path_base:'/'; break; case 'ja_JP': path_base = '/jp' break; default: path_base = '/' + cookie_locale; } path_array = locale_in_path != -1 ? path_array.slice(locale_in_path):path_array; path_array.unshift(path_base); window.location.href = path_array.join('/'); } } // only do the ajax call if we don't have a cookie if (!cookie_locale) { // debug.log('doing the cookie check for locale...') cookie_locale = 'null'; var get_data = {cookie:cookie_locale, page:path, t_locale:tesla_locale}; var query_country_string = parsed_url.query != '' ? parsed_url.query.split('='):false; var query_country = query_country_string ? (query_country_string.slice(0,1) == '?country' ? query_country_string.slice(-1):false):false; if (query_country) { get_data.query_country = query_country; } $.ajax({ url:'/check_locale', data:get_data, cache: false, dataType: "json", success: function(data){ var ip_locale = data.locale; var market = data.market; var new_locale_link = $('#locale_pop #locale_link'); if (data.show_blip && show_blip_count < 3) { setTimeout(function(){ $('#locale_msg').text(data.locale_msg); $('#locale_welcome').text(data.locale_welcome); new_locale_link[0].href = data.new_path; new_locale_link.text(data.locale_link); new_locale_link.attr('rel', data.locale); if (!new_locale_link.hasClass(data.locale)) { new_locale_link.addClass(data.locale); } $('#locale_pop').slideDown('slow', function(){ var hide_blip = setTimeout(function(){ $('#locale_pop').slideUp('slow', function(){ var show_blip_count = readCookie('show_blip_count'); if (!show_blip_count) { createCookie('show_blip_count',1,360); } else if (show_blip_count < 3 ) { var b_count = show_blip_count; b_count ++; eraseCookie('show_blip_count'); createCookie('show_blip_count',b_count,360); } }); },10000); $('#locale_pop').hover(function(){ clearTimeout(hide_blip); },function(){ setTimeout(function(){$('#locale_pop').slideUp();},10000); }); }); },1000); } } }); } }

    Read the article

  • jQuery Templates on Microsoft Ajax CDN

    - by Stephen Walther
    The beta version of the jQuery Templates plugin is now hosted on the Microsoft Ajax CDN. You can start using the jQuery Templates plugin in your application by referencing both jQuery 1.4.2 and jQuery Templates from the CDN. Here are the two script tags that you will want to use when developing an application: <script type="text/javascript" src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js”></script> <script type="text/javascript" src=”http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js”></script> In addition, minified versions of both files are available from the CDN: <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> Here’s a full code sample of using jQuery Templates from the CDN to display pictures of cats from Flickr: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Cats</title> <style type="text/css"> html { background-color:Orange; } #catBox div { width:250px; height:250px; border:solid 1px black; background-color:White; margin:5px; padding:5px; float:left; } #catBox img { width:200px; height: 200px; } </style> </head> <body> <h1>Cat Photos!</h1> <div id="catBox"></div> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> <script id="catTemplate" type="text/x-jquery-tmpl"> <div> <b>${title}</b> <br /> <img src="${media.m}" /> </div> </script> <script type="text/javascript"> var url = "http://api.flickr.com/services/feeds/groups_pool.gne?id=44124373027@N01&lang=en-us&format=json&jsoncallback=?"; // Grab some flickr images of cats $.getJSON(url, function (data) { // Format the data using the catTemplate template $("#catTemplate").tmpl(data.items).appendTo("#catBox"); }); </script> </body> </html> This page displays a list of cats retrieved from Flickr: Notice that the cat pictures are retrieved and rendered with just a few lines of code: var url = "http://api.flickr.com/services/feeds/groups_pool.gne?id=44124373027@N01&lang=en-us&format=json&jsoncallback=?"; // Grab some flickr images of cats $.getJSON(url, function (data) { // Format the data using the catTemplate template $("#catTemplate").tmpl(data.items).appendTo("#catBox"); }); The final line of code, the one that calls the tmpl() method, uses the Templates plugin to render the cat photos in a template named catTemplate. The catTemplate template is contained within a SCRIPT element with type="text/x-jquery-tmpl". The jQuery Templates plugin is an “official” jQuery plugin which will be included in jQuery 1.5 (the next major release of jQuery). You can read the full documentation for the plugin at the jQuery website: http://api.jquery.com/category/plugins/templates/ The jQuery Templates plugin is still beta so we would really appreciate your feedback on the plugin. Let us know if you use the Templates plugin in your website.

    Read the article

  • jQuery Templates - XHTML Validation

    - by hajan
    Many developers have already asked me about this. How to make XHTML valid the web page which uses jQuery Templates. Maybe you have already tried, and I don't know what are your results but here is my opinion regarding this. By default, Visual Studio.NET adds the xhtml1-transitional.dtd schema <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> So, if you try to validate your page which has jQuery Templates against this schema, your page won't be XHTML valid. Why? It's because when creating templates, we use HTML tags inside <script> ... </script> block. Yes, I know that the script block has type="text/html" but it's not supported in this schema, thus it's not valid. Let's try validate the following code Code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head>     <title>jQuery Templates :: XHTML Validation</title>     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>     <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>          <script language="javascript" type="text/javascript">         $(function () {             var attendees = [                 { Name: "Hajan", Surname: "Selmani", speaker: true, phones: [070555555, 071888999, 071222333] },                 { Name: "Denis", Surname: "Manski", phones: [070555555, 071222333] }             ];             $("#myTemplate").tmpl(attendees).appendTo("#attendeesList");         });     </script>     <script id="myTemplate" type="text/html">          <li>             ${Name} ${Surname}             {{if speaker}}                 (<font color="red">speaks</font>)             {{else}}                 (attendee)             {{/if}}         </li>     </script>      </head>     <body>     <ol id="attendeesList"></ol> </body> </html> To validate it, go to http://validator.w3.org/#validate_by_input and copy paste the code rendered on client-side browser (it’s almost the same, only the template is rendered inside OL so LI tags are created for each item). Press CHECK and you will get: Result: 1 Errors, 2 warning(s)  The error message says: Validation Output: 1 Error Line 21, Column 13: document type does not allow element "li" here <li> Yes, the <li> HTML element is not allowed inside the <script>, so how to make it valid? FIRST: Using <![CDATA][…]]> The first thing that came in my mind was the CDATA. So, by wrapping any HTML tag which is in script blog, inside <![CDATA[ ........ ]]> it will make our code valid. However, the problem is that the template won't render since the template tags {} cannot get evaluated if they are inside CDATA. Ok, lets try with another approach. SECOND: HTML5 validation Well, if we just remove the strikethrough part bellow of the !DOPCTYPE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> our template is going to be checked as HTML5 and will be valid. Ok, there is another approach I've also tried: THIRD: Separate template to an external file We can separate the template to external file. I didn’t show how to do this previously, so here is the example. 1. Add HTML file with name Template.html in your ASPX website. 2. Place your defined template there without <script> tag Content inside Template.html <li>     ${Name} ${Surname}     {{if speaker}}         (<font color="red">speaks</font>)     {{else}}         (attendee)     {{/if}} </li> 3. Call the HTML file using $.get() jQuery ajax method and render the template with data using $.tmpl() function. $.get("/Templates/Template.html", function (template) {     $.tmpl(template, attendees).appendTo("#attendeesList"); }); So the complete code is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head>     <title>jQuery Templates :: XHTML Validation</title>     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>     <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>          <script language="javascript" type="text/javascript">         $(function () {             var attendees = [                 { Name: "Hajan", Surname: "Selmani", speaker: true, phones: [070555555, 071888999, 071222333] },                 { Name: "Denis", Surname: "Manski", phones: [070555555, 071222333] }             ];             $.get("/Templates/Template.html", function (template) {                 $.tmpl(template, attendees).appendTo("#attendeesList");             });         });     </script>      </head>     <body>     <ol id="attendeesList"></ol> </body> </html> This document was successfully checked as XHTML 1.0 Transitional! Result: Passed If you have any additional methods for XHTML validation, you can share it :). Thanks,Hajan

    Read the article

  • How to write a jquery ui plugin?

    - by Haris
    I want to write a jquery ui plugin? I can't find a useful tutorial which will guide me from start. I've never written a plugin for jquery before. I want to prevent draggables from overlappping on each other. I found a plugin for jquery ui but it doesn't work with version 1.7.1 of jQuery UI Please help!

    Read the article

  • jQuery Validation hiding or tearing down jquery Modal Dialog on submit

    - by Programmin Tool
    Basically when clicking the modal created submit button, and calling jQuery('#FormName').submit(), it will run the validation and then call the method assigned in the submitHandler. After that it is either creating a new modal div or hiding the form, and I don't get why. I have debugged it and noticed that after the method call in the submitHandler, the form .is(':hidden') = true and this is true for the modal div also. I'm positive I've done this before but can't seem to figure out what I've done wrong this time. The odd this is a modal div is showing up on the screen, but it's completely devoid of content. (Even after putting in random text outside of the form. It's like it's a whole new modal div) Here are the set up methods: function setUpdateTaskDiv() { jQuery("#UpdateTaskForm").validate({ errorLabelContainer: "#ErrorDiv", wrapper: "div", rules: { TaskSubject: { required: true } }, messages: { TaskSubject: { required: 'Subject is required.' } }, onfocusout: false, onkeyup: false, submitHandler: function(label) { updateTaskSubject(null); } } ); jQuery('#UpdateDiv').dialog({ autoOpen: false, bgiframe: true, height: 400, width: 500, modal: true, beforeclose: function() { }, buttons: { Submit: function() { jQuery('#UpdateTaskForm').submit(); }, Cancel: function() { ... } } }); where: function updateTaskSubject(task) { //does nothing, it's just a shell right now } Doesn't really do anything right now. Here's the html: <div id="UpdateDiv"> <div id="ErrorDiv"> </div> <form method="post" id="UpdateTaskForm" action="Calendar.html"> <div> <div class="floatLeft"> Date: </div> <div class="floatLeft"> </div> <div class="clear"> </div> </div> <div> <div class="floatLeft"> Start Time: </div> <div class="floatLeft"> <select id="TaskStartDate" name="TaskStartDate"> </select> </div> <div class="clear"> </div> </div> <div> <div class="floatLeft"> End Time: </div> <div class="floatLeft"> <select id="TaskEndDate" name="TaskEndDate"> </select> </div> <div class="clear"> </div> </div> <div> <div class="floatLeft"> Subject: </div> <div class="floatLeft"> <textarea id="TaskSubject" name="TaskSubject" cols="30" rows="10"></textarea> </div> <div class="clear"> </div> </div> <div> <input type="hidden" id="TaskId" value="" /> </div> <div class="clear"></div> </form> </div> Odd Discovery Turns out that the examples that I got this to work all had the focus being put back on the modal itself. For example, using the validator to add messages to the error div. (Success or not) Without doing this, the modal dialog apparently thinks that it's done with what it needs to do and just hides everything. Not sure exactly why, but to stop this behavior some kind of focus has to be assigned to something within the div itself.

    Read the article

  • Looking into the jQuery LazyLoad Plugin

    - by nikolaosk
    I have been using JQuery for a couple of years now and it has helped me to solve many problems on the client side of web development.  You can find all my posts about JQuery in this link. In this post I will be providing you with a hands-on example on the JQuery LazyLoad Plugin.If you want you can have a look at this post, where I describe the JQuery Cycle Plugin.You can find another post of mine talking about the JQuery Carousel Lite Plugin here. Another post of mine regarding the JQuery Image Zoom Plugin can be found here. You can have a look at the JQuery Overlays Plugin here . There are times when when I am asked to create a very long page with lots of images.My first thought is to enable paging on the proposed page. Imagine that we have 60 images on a page. There are performance concerns when we have so many images on a page. Paging can solve that problem if I am allowed to place only 5 images on a page.Sometimes the customer does not like the idea of the paging.Believe it or not some people find the idea of paging not attractive at all.In that case I need a way to only load the initial set of images and as the user scrolls down the page to load the rest.So as someone scrolls down new requests are made to the server and more images are fetched. I can accomplish that with the jQuery LazyLoad Plugin.This is just a plugin that delays loading of images in long web pages.The images that are outside of the viewport (visible part of web page) won't be loaded before the user scrolls to them. Using jQuery LazyLoad Plugin on long web pages containing many large images makes the page load faster. In this hands-on example I will be using Expression Web 4.0.This application is not a free application. You can use any HTML editor you like. You can use Visual Studio 2012 Express edition. You can download it here.  You can download this plugin from this link. I launch Expression Web 4.0 and then I type the following HTML markup (I am using HTML 5)<!DOCTYPE html><html lang="en">  <head>    <title>Liverpool Legends</title>    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>        <script type="text/javascript" src="jquery.lazyload.min.js" ></script></head>  <body>    <header>                <h1>Liverpool Legends</h1>    </header>        <div id="main">             <img src="barnes.JPG" width="800" height="1100" /><p />        <img src="dalglish.JPG" width="800" height="1100" /><p />                <img class="LiverpoolImage" src="loader.gif" data-original="fans.JPG" width="1200" height="900" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="lfc.JPG" width="1000" height="700" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="Liverpool-players.JPG" width="1100" height="900" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="steven_gerrard.JPG" width="1110" height="1000" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="robbie.JPG" width="1200" height="1000" /><p />          </div>            <footer>        <p>All Rights Reserved</p>      </footer>                    <script type="text/javascript">                $(function () {                    $("img.LiverpoolImage").lazyload();                });        </script>     </body>  </html> This is a very simple markup. I have  added references to the JQuery library (current version is 1.8.3) and the JQuery LazyLoad Plugin. Firstly, I add two images         <img src="barnes.JPG" width="800" height="1100" /><p />        <img src="dalglish.JPG" width="800" height="1100" /><p />  that will load immediately as soon as the page loads. Then I add the images that will not load unless they become active in the viewport. I have all my img tags pointing the src attribute towards a placeholder image. I’m using a blank 1×1 px grey image,loader.gif.The five images that will load as the user scrolls down the page follow.         <img class="LiverpoolImage" src="loader.gif" data-original="fans.JPG" width="1200" height="900" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="lfc.JPG" width="1000" height="700" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="Liverpool-players.JPG" width="1100" height="900" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="steven_gerrard.JPG" width="1110" height="1000" /><p />        <img class="LiverpoolImage" src="loader.gif" data-original="robbie.JPG" width="1200" height="1000" /><p /> Then we need to rename the image src to point towards the proper image placeholder. The full image URL goes into the data-original attribute.The Javascript code that makes it all happen follows. We need to make a call to the JQuery LazyLoad Plugin. We add the script just before we close the body element.         <script type="text/javascript">                $(function () {                    $("img.LiverpoolImage").lazyload();                });        </script>We can change the code above to incorporate some effects.          <script type="text/javascript">  $("img.LiverpoolImage").lazyload({    effect: "fadeIn"  });    </script> That is all I need to write to achieve lazy loading. It it true that you can do so much with less!!I view my simple page in Internet Explorer 10 and it works as expected. I have tested this simple solution in all major browsers and it works fine. You can test it yourself and see the results in your favorite browser. Hope it helps!!!

    Read the article

  • How to use jQuery Date Range Picker plugin in asp.net

    - by alaa9jo
    I stepped by this page: http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/ and let me tell you,this is one of the best and coolest daterangepicker in the web in my opinion,they did a great job with extending the original jQuery UI DatePicker.Of course I made enhancements to the original plugin (fixed few bugs) and added a new option (Clear) to clear the textbox. In this article I well use that updated plugin and show you how to use it in asp.net..you will definitely like it. So,What do I need? 1- jQuery library : you can use 1.3.2 or 1.4.2 which is the latest version so far,in my article I will use the latest version. 2- jQuery UI library (1.8): As I mentioned earlier,daterangepicker plugin is based on the original jQuery UI DatePicker so that library should be included into your page. 3- jQuery DateRangePicker plugin : you can go to the author page or use the modified one (it's included in the attachment),in this article I will use the modified one. 4- Visual Studio 2005 or later : very funny :D,in my article I will use VS 2008. Note: in the attachment,I included all CSS and JS files so don't worry. How to use it? First thing,you will have to include all of the CSS and JS files into your page like this: <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="Scripts/jquery-ui-1.8.custom.min.js" type="text/javascript"></script> <script src="Scripts/daterangepicker.jQuery.js" type="text/javascript"></script> <link href="CSS/redmond/jquery-ui-1.8.custom.css" rel="stylesheet" type="text/css" /> <link href="CSS/ui.daterangepicker.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .ui-daterangepicker { font-size: 10px; } </style> Then add this html: <asp:TextBox ID="TextBox1" runat="server" Font-Size="10px"></asp:TextBox><asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" /> <span>First Date:</span><asp:Label ID="FirstDate" runat="server"></asp:Label> <span>Second Date:</span><asp:Label ID="SecondDate" runat="server"></asp:Label> As you can see,it includes TextBox1 which we are going to attach the daterangepicker to it,2 labels to show you later on by code on how to read the date from the textbox and set it to the labels Now we have to attach the daterangepicker to the textbox by using jQuery (Note:visit the author's website for more info on daterangerpicker's options and how to use them): <script type="text/javascript"> $(function() { $("#<%= TextBox1.ClientID %>").attr("readonly", "readonly"); $("#<%= TextBox1.ClientID %>").attr("unselectable", "on"); $("#<%= TextBox1.ClientID %>").daterangepicker({ presetRanges: [], arrows: true, dateFormat: 'd M, yy', clearValue: '', datepickerOptions: { changeMonth: true, changeYear: true} }); }); </script> Finally,add this C# code: protected void SubmitButton_Click(object sender, EventArgs e) { if (TextBox1.Text.Trim().Length == 0) { return; } string selectedDate = TextBox1.Text; if (selectedDate.Contains("-")) { DateTime startDate; DateTime endDate; string[] splittedDates = selectedDate.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (splittedDates.Count() == 2 && DateTime.TryParse(splittedDates[0], out startDate) && DateTime.TryParse(splittedDates[1], out endDate)) { FirstDate.Text = startDate.ToShortDateString(); SecondDate.Text = endDate.ToShortDateString(); } else { //maybe the client has modified/altered the input i.e. hacking tools } } else { DateTime selectedDateObj; if (DateTime.TryParse(selectedDate, out selectedDateObj)) { FirstDate.Text = selectedDateObj.ToShortDateString(); SecondDate.Text = string.Empty; } else { //maybe the client has modified/altered the input i.e. hacking tools } } } This is the way on how to read from the textbox,That's it!. FAQ: 1-Why did you add this code?: <style type="text/css"> .ui-daterangepicker { font-size: 10px; } </style> A:For two reasons: 1)To show the Daterangepicker in a smaller size because it's original size is huge 2)To show you how to control the size of it. 2- Can I change the theme? A: yes you can,you will notice that I'm using Redmond theme which you will find it in jQuery UI website,visit their website and download a different theme,you may also have to make modifications to the css of daterangepicker,it's all yours. 3- Why did you add a font size to the textbox? A: To make the design look better,try to remove it and see by your self. 4- Can I register the script at codebehind? A: yes you can 5- I see you have added these two lines,what they do? $("#<%= TextBox1.ClientID %>").attr("readonly", "readonly"); $("#<%= TextBox1.ClientID %>").attr("unselectable", "on"); A:The first line will make the textbox not editable by the user,the second will block the blinking typing cursor from appearing if the user clicked on the textbox,you will notice that both lines are necessary to be used together,you can't just use one of them...for logical reasons of course. Finally,I hope everyone liked the article and as always,your feedbacks are always welcomed and if anyone have any suggestions or made any modifications that might be useful for anyone else then please post it at at the author's website and post a reference to your post here.

    Read the article

  • jQuery animate() - multiple selectors and variables, a unique animate() call

    - by ozke
    Hi guys, I am resizing several divs in a loop with animate() in jQuery. At the same time I am moving (left property, no resizing at all) the div where they are contained. Problem is, despite they have same duration the resize animate calls finish before the move call. They are out of sync. Is there any way of creating a list of selectors and its properties and then run a unique animate() call? Or, is there any alternative to make multiple animations happen at the same time? I've seen there's a property called step that happens every time animate loop happens but, again, each animate() call has it's own step call. Thanks in advance :)

    Read the article

  • jQuery dialog breaking after closing - I'm using dialog destroy

    - by pedalpete
    I've got a few demo videos I've been making as tutorials, and I'm using a link to open a dialog box and put the demo video in that box. I use the same div to show other notes on the page when a user selects to view a complete note. The code I use to show the notes is jQuery('span.Notes').live('click', function(){ var note=jQuery(this).data('note'); jQuery('div#showNote').text(note); jQuery('div#showNote').append(''); jQuery('div#showNote').dialog({ modal: true, close: function(){ jQuery('div#showNote').dialog('destroy').empty(); } }); }); The code I use for the demo videos is VERY similar. jQuery('a.demoVid').click(function(){ var videoUrl=jQuery(this).attr('href'); jQuery('div#showNote').dialog({ modal: true, height: 400, width: 480, close: function(){ jQuery('div#showNote').dialog('destroy').empty(); } }); swfobject.embedSWF(videoUrl,'showNote','480','390','8.0.0'); return false; }); I can click on as many notes as I want, and the dialog opens up and shows the note. However, when I click the demoVid, the dialog opens, but then closing the dialog kills any other 'showNote' dialogs on the page, so I can't open any more notes, or demo videos.

    Read the article

  • jQuery plugin for Facebook "Like" Button

    - by ming yeow
    On lots of sites now, you can see a Facebook "Like" Button. - When depressed, it changes background color. - When mouse-overed, it allows you to write some additional text I love this interface - lightweight action, but allow for expression of more data if the user wants to. Anyone has written a similar plugin?

    Read the article

  • jQuery event handler queue

    - by resopollution
    Overview of the problem In jQuery, the order in which you bind a handler is the order in which they will be executed if you are binding to the same element. For example: $('#div1').bind('click',function(){ // code runs first }); $('#div1').bind('click',function(){ // code runs second }); But what if I want the 2nd bound code to run first? . My current solution Currently, my solution is to modify the event queue: $.data(domElement, 'events')['click'].unshift({ type : 'click', guid : null, namespace : "", data : undefined, handler: function() { // code } }); . Question Is there anything potentially wrong with my solution? Can I safely use null as a value for the guid? Thanks in advance. .

    Read the article

  • Get reference to all instances of jquery ui widget?

    - by Hailwood
    I am writing a jquery UI widget that simply wraps the bootstrap popover plugin, In the widget you can pass in the option 'singular', if this is passed in then it should call a function of all other instances of the plugin. something like $('#one').myWidget(); $('#two').myWidget(); $('#three').myWidget(); $('#four').myWidget(); $('#one').myWidget('show'); //stuff from widget one is now visible $('#two').myWidget('show'); //stuff from widget one and two are now visible $('#three').myWidget('show'); //stuff from widget one, two and three are now visible $('#two').myWidget('hide'); //stuff from widget one and three are now visible $('#four').myWidget('show', {singular:true}); //stuff from widget four is now visible So, I imagine the show function looking like: show: function(options){ options = options || {}; if(options.singular){ var instances = '????'; // how do I get all instances? $.each(instances, function(i, o){ o.myWidget('hide'); }); } this.element.popover('show'); } So, question being, how would I get a reference to all elements that have the myWidget widget on them?

    Read the article

  • Seperate html pages for each screen in Jquery mobile

    - by vrs
    I am newbie to Jquery Mobile, so far what ever examples i searched contains only one html page for whole application, with multipe div tags where each page/screen is defined as div tag with data-role as page with some header and footers optionally. Based on user actions, we are hiding some div's(pages) and showing only expected page. Also, this multi-page template seems to be standard design, as written by some blogs. Are there any other designing ways? what I would like to have is multipe html pages, for ex one for login, one for home, one for contact etc. Other wise it is difficult to understand/code/debug issues, especially people from Java background like me.So, what I want is some kind of MVC design with JQueryMobile, like each view/screen as sepearate html associated with one js (Controller). Can we have multiple html pages in JqueryMobile app? If possible how to pass data/ maintain session between them? Any samples are most welcome. Thanks In Advance. Note: Also I don't want server side includes, may app contains 10 to 15 screens, each page will make a webservice call and fetch some data and map it to UI.

    Read the article

  • jQuery Mobile Download Builder

    - by Yousef_Jadallah
    Now you can customize your jQuery Mobile download by selecting the specific modules you need by using jQuery Mobile Download Builder that was released yesterday June 30, 2012. You can select specific form element, transition type, widget and some core functionalities and Utilites.. Here you can find jQuery Mobile Download Builder RC1. http://jquerymobile.com/download-builder Thanks for jQuery Mobile team for there efforts....(read more)

    Read the article

  • Looking into the JQuery Overlays Plugin

    - by nikolaosk
    I have been using JQuery for a couple of years now and it has helped me to solve many problems on the client side of web development.  You can find all my posts about JQuery in this link. In this post I will be providing you with a hands-on example on the JQuery Overlays Plugin.If you want you can have a look at this post, where I describe the JQuery Cycle Plugin.You can find another post of mine talking about the JQuery Carousel Lite Plugin here. Another post of mine regarding the JQuery Image Zoom Plugin can be found here.I will be writing more posts regarding the most commonly used JQuery Plugins. With the JQuery Overlays Plugin we can provide the user (overlay) with more information about an image when the user hovers over the image. I have been using extensively this plugin in my websites. In this hands-on example I will be using Expression Web 4.0.This application is not a free application. You can use any HTML editor you like. You can use Visual Studio 2012 Express edition. You can download it here.  You can download this plugin from this link. I launch Expression Web 4.0 and then I type the following HTML markup (I am using HTML 5) <html lang="en"> <head>    <link rel="stylesheet" href="ImageOverlay.css" type="text/css" media="screen" />    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>    <script type="text/javascript" src="jquery.ImageOverlay.min.js"></script>         <script type="text/javascript">        $(function () {            $("#Liverpool").ImageOverlay();        });    </script>   </head><body>    <ul id="Liverpool" class="image-overlay">        <li>            <a href="www.liverpoolfc.com">                <img alt="Liverpool" src="championsofeurope.jpg" />                <div class="caption">                    <h3>Liverpool Football club</h3>                    <p>The greatest club in the world</p>                </div>            </a>        </li>    </ul></body></html> This is a very simple markup. I have added references to the JQuery library (current version is 1.8.3) and the JQuery Overlays Plugin. Then I add 1 image in the element with "id=Liverpool". There is a caption class as well, where I place the text I want to show when the mouse hovers over the image. The caption class and the Liverpool id element are styled in the ImageOverlay.css file that can also be downloaded with the plugin.You can style the various elements of the html markup in the .css file. The Javascript code that makes it all happen follows.   <script type="text/javascript">        $(function () {            $("#Liverpool").ImageOverlay();        });    </script>        I am just calling the ImageOverlay function for the Liverpool ID element.The contents of ImageOverlay.css file follow .image-overlay { list-style: none; text-align: left; }.image-overlay li { display: inline; }.image-overlay a:link, .image-overlay a:visited, .image-overlay a:hover, .image-overlay a:active { text-decoration: none; }.image-overlay a:link img, .image-overlay a:visited img, .image-overlay a:hover img, .image-overlay a:active img { border: none; }.image-overlay a{    margin: 9px;    float: left;    background: #fff;    border: solid 2px;    overflow: hidden;    position: relative;}.image-overlay img{    position: absolute;    top: 0;    left: 0;    border: 0;}.image-overlay .caption{    float: left;    position: absolute;    background-color: #000;    width: 100%;    cursor: pointer;    /* The way to change overlay opacity is the follow properties. Opacity is a tricky issue due to        longtime IE abuse of it, so opacity is not offically supported - use at your own risk.         To play it safe, disable overlay opacity in IE. */    /* For Firefox/Opera/Safari/Chrome */    opacity: .8;    /* For IE 5-7 */    filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);    /* For IE 8 */    -MS-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";}.image-overlay .caption h1, .image-overlay .caption h2, .image-overlay .caption h3,.image-overlay .caption h4, .image-overlay .caption h5, .image-overlay .caption h6{    margin: 10px 0 10px 2px;    font-size: 26px;    font-weight: bold;    padding: 0 0 0 5px;    color:#92171a;}.image-overlay p{    text-indent: 0;    margin: 10px;    font-size: 1.2em;} It couldn't be any simpler than that. I view my simple page in Internet Explorer 10 and it works as expected. I have tested this simple solution in all major browsers and it works fine.Have a look at the picture below. You can test it yourself and see the results in your favorite browser. Hope it helps!!!

    Read the article

  • jQuery UI Dialog Error: b("<div></div>").addClass("ui-widget-overlay") is undefined

    - by Mithun
    I have the below code for my a Dialog box for a which contains a dropdown field KPMS.ServiceRequests.Status = { showOptions : function(requestId, userId, requestType) { var url = BASE_URL+'service_requests/status_options/'; $("#dialog-modal").dialog("destroy"); $("#dialog-modal").load(url, {"request_id": requestId, "user_id": userId, "request_type":requestType}).dialog( { modal: true, title: "Update Status", buttons: { Cancel : function() { $(this).dialog('close'); }, Update: function() { alert(1); } } } ); } } There is an anchor tag to populate the Dialog <a onclick="KPMS.ServiceRequests.Status.showOptions(9, 11, 'SR'); return false;" title="Update status" href="http://localhost/kitco/pms/#9"><img alt="[E]" title="Update" src="http://localhost/kitco/pms/images/edit.png"></a> My problem is When i click the link for the first time the dialog box is populating properly. Then I closed the dialog using the cancel button, then again clicked the link to open the dialog and closed it. For the third click on the link I'm getting the below Javascript error, and Dialog box is not opened Error: b("<div></div>").addClass("ui-widget-overlay") is undefined Source File: http://localhost/kitco/pms/js/jquery-ui-1.8rc3.custom.min.js Line: 199 How to solve this problem?

    Read the article

  • Using jQuery to Insert a New Database Record

    - by Stephen Walther
    The goal of this blog entry is to explore the easiest way of inserting a new record into a database using jQuery and .NET. I’m going to explore two approaches: using Generic Handlers and using a WCF service (In a future blog entry I’ll take a look at OData and WCF Data Services). Create the ASP.NET Project I’ll start by creating a new empty ASP.NET application with Visual Studio 2010. Select the menu option File, New Project and select the ASP.NET Empty Web Application project template. Setup the Database and Data Model I’ll use my standard MoviesDB.mdf movies database. This database contains one table named Movies that looks like this: I’ll use the ADO.NET Entity Framework to represent my database data: Select the menu option Project, Add New Item and select the ADO.NET Entity Data Model project item. Name the data model MoviesDB.edmx and click the Add button. In the Choose Model Contents step, select Generate from database and click the Next button. In the Choose Your Data Connection step, leave all of the defaults and click the Next button. In the Choose Your Data Objects step, select the Movies table and click the Finish button. Unfortunately, Visual Studio 2010 cannot spell movie correctly :) You need to click on Movy and change the name of the class to Movie. In the Properties window, change the Entity Set Name to Movies. Using a Generic Handler In this section, we’ll use jQuery with an ASP.NET generic handler to insert a new record into the database. A generic handler is similar to an ASP.NET page, but it does not have any of the overhead. It consists of one method named ProcessRequest(). Select the menu option Project, Add New Item and select the Generic Handler project item. Name your new generic handler InsertMovie.ashx and click the Add button. Modify your handler so it looks like Listing 1: Listing 1 – InsertMovie.ashx using System.Web; namespace WebApplication1 { /// <summary> /// Inserts a new movie into the database /// </summary> public class InsertMovie : IHttpHandler { private MoviesDBEntities _dataContext = new MoviesDBEntities(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; // Extract form fields var title = context.Request["title"]; var director = context.Request["director"]; // Create movie to insert var movieToInsert = new Movie { Title = title, Director = director }; // Save new movie to DB _dataContext.AddToMovies(movieToInsert); _dataContext.SaveChanges(); // Return success context.Response.Write("success"); } public bool IsReusable { get { return true; } } } } In Listing 1, the ProcessRequest() method is used to retrieve a title and director from form parameters. Next, a new Movie is created with the form values. Finally, the new movie is saved to the database and the string “success” is returned. Using jQuery with the Generic Handler We can call the InsertMovie.ashx generic handler from jQuery by using the standard jQuery post() method. The following HTML page illustrates how you can retrieve form field values and post the values to the generic handler: Listing 2 – Default.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Add Movie</title> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> </head> <body> <form> <label>Title:</label> <input name="title" /> <br /> <label>Director:</label> <input name="director" /> </form> <button id="btnAdd">Add Movie</button> <script type="text/javascript"> $("#btnAdd").click(function () { $.post("InsertMovie.ashx", $("form").serialize(), insertCallback); }); function insertCallback(result) { if (result == "success") { alert("Movie added!"); } else { alert("Could not add movie!"); } } </script> </body> </html>     When you open the page in Listing 2 in a web browser, you get a simple HTML form: Notice that the page in Listing 2 includes the jQuery library. The jQuery library is included with the following SCRIPT tag: <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> The jQuery library is included on the Microsoft Ajax CDN so you can always easily include the jQuery library in your applications. You can learn more about the CDN at this website: http://www.asp.net/ajaxLibrary/cdn.ashx When you click the Add Movie button, the jQuery post() method is called to post the form data to the InsertMovie.ashx generic handler. Notice that the form values are serialized into a URL encoded string by calling the jQuery serialize() method. The serialize() method uses the name attribute of form fields and not the id attribute. Notes on this Approach This is a very low-level approach to interacting with .NET through jQuery – but it is simple and it works! And, you don’t need to use any JavaScript libraries in addition to the jQuery library to use this approach. The signature for the jQuery post() callback method looks like this: callback(data, textStatus, XmlHttpRequest) The second parameter, textStatus, returns the HTTP status code from the server. I tried returning different status codes from the generic handler with an eye towards implementing server validation by returning a status code such as 400 Bad Request when validation fails (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html ). I finally figured out that the callback is not invoked when the textStatus has any value other than “success”. Using a WCF Service As an alternative to posting to a generic handler, you can create a WCF service. You create a new WCF service by selecting the menu option Project, Add New Item and selecting the Ajax-enabled WCF Service project item. Name your WCF service InsertMovie.svc and click the Add button. Modify the WCF service so that it looks like Listing 3: Listing 3 – InsertMovie.svc using System.ServiceModel; using System.ServiceModel.Activation; namespace WebApplication1 { [ServiceBehavior(IncludeExceptionDetailInFaults=true)] [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class MovieService { private MoviesDBEntities _dataContext = new MoviesDBEntities(); [OperationContract] public bool Insert(string title, string director) { // Create movie to insert var movieToInsert = new Movie { Title = title, Director = director }; // Save new movie to DB _dataContext.AddToMovies(movieToInsert); _dataContext.SaveChanges(); // Return movie (with primary key) return true; } } }   The WCF service in Listing 3 uses the Entity Framework to insert a record into the Movies database table. The service always returns the value true. Notice that the service in Listing 3 includes the following attribute: [ServiceBehavior(IncludeExceptionDetailInFaults=true)] You need to include this attribute if you want to get detailed error information back to the client. When you are building an application, you should always include this attribute. When you are ready to release your application, you should remove this attribute for security reasons. Using jQuery with the WCF Service Calling a WCF service from jQuery requires a little more work than calling a generic handler from jQuery. Here are some good blog posts on some of the issues with using jQuery with WCF: http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/ http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx http://www.west-wind.com/Weblog/posts/896411.aspx http://www.west-wind.com/weblog/posts/324917.aspx http://professionalaspnet.com/archive/tags/WCF/default.aspx The primary requirement when calling WCF from jQuery is that the request use JSON: The request must include a content-type:application/json header. Any parameters included with the request must be JSON encoded. Unfortunately, jQuery does not include a method for serializing JSON (Although, oddly, jQuery does include a parseJSON() method for deserializing JSON). Therefore, we need to use an additional library to handle the JSON serialization. The page in Listing 4 illustrates how you can call a WCF service from jQuery. Listing 4 – Default2.aspx <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Add Movie</title> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="Scripts/json2.js" type="text/javascript"></script> </head> <body> <form> <label>Title:</label> <input id="title" /> <br /> <label>Director:</label> <input id="director" /> </form> <button id="btnAdd">Add Movie</button> <script type="text/javascript"> $("#btnAdd").click(function () { // Convert the form into an object var data = { title: $("#title").val(), director: $("#director").val() }; // JSONify the data data = JSON.stringify(data); // Post it $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "MovieService.svc/Insert", data: data, dataType: "json", success: insertCallback }); }); function insertCallback(result) { // unwrap result result = result["d"]; if (result === true) { alert("Movie added!"); } else { alert("Could not add movie!"); } } </script> </body> </html> There are several things to notice about Listing 4. First, notice that the page includes both the jQuery library and Douglas Crockford’s JSON2 library: <script src="Scripts/json2.js" type="text/javascript"></script> You need to include the JSON2 library to serialize the form values into JSON. You can download the JSON2 library from the following location: http://www.json.org/js.html When you click the button to submit the form, the form data is converted into a JavaScript object: // Convert the form into an object var data = { title: $("#title").val(), director: $("#director").val() }; Next, the data is serialized into JSON using the JSON2 library: // JSONify the data var data = JSON.stringify(data); Finally, the form data is posted to the WCF service by calling the jQuery ajax() method: // Post it $.ajax({   type: "POST",   contentType: "application/json; charset=utf-8",   url: "MovieService.svc/Insert",   data: data,   dataType: "json",   success: insertCallback }); You can’t use the standard jQuery post() method because you must set the content-type of the request to be application/json. Otherwise, the WCF service will reject the request for security reasons. For details, see the Scott Guthrie blog post: http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx The insertCallback() method is called when the WCF service returns a response. This method looks like this: function insertCallback(result) {   // unwrap result   result = result["d"];   if (result === true) {       alert("Movie added!");   } else {     alert("Could not add movie!");   } } When we called the jQuery ajax() method, we set the dataType to JSON. That causes the jQuery ajax() method to deserialize the response from the WCF service from JSON into a JavaScript object automatically. The following value is passed to the insertCallback method: {"d":true} For security reasons, a WCF service always returns a response with a “d” wrapper. The following line of code removes the “d” wrapper: // unwrap result result = result["d"]; To learn more about the “d” wrapper, I recommend that you read the following blog posts: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/ http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/ Summary In this blog entry, I explored two methods of inserting a database record using jQuery and .NET. First, we created a generic handler and called the handler from jQuery. This is a very low-level approach. However, it is a simple approach that works. Next, we looked at how you can call a WCF service using jQuery. This approach required a little more work because you need to serialize objects into JSON. We used the JSON2 library to perform the serialization. In the next blog post, I want to explore how you can use jQuery with OData and WCF Data Services.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >