Search Results

Search found 243 results on 10 pages for 'keyup'.

Page 9/10 | < Previous Page | 5 6 7 8 9 10  | Next Page >

  • AJAX help needed

    - by tharindu
    Hi guys.. i have problem in ajax.. im new comer for ajax...:) <script type="text/javascript"> $(document).ready(function() { $("#bcode").focus(); //prevents autocomplete in some browsers $("#bcode").attr('autocomplete', 'off').keyup(function(event) { var name = $("#bcode").val(); $("#status").empty(); if(name.length > 17 ) { selectAll(); $("#status").html('<img align="absmiddle" src="loading.gif" /> Checking availability...').show(); $.ajax({ type: "POST", url: "namecheck.php", data: "bcode="+ name, success: function(msg) { $("#status").html(msg).show(); } }); } else { $("#status").html('').addClass('err').show(); } }); }); //--> </script> i got text box value 'bcode' using '$_POST['bcode']' <input name="bcode" type="text" class="bcode" id="bcode" maxlength="18"; /> also i have menu/list in that form <select name="pallete" class="list_box" id="select"> <option value="P0" selected> </option> <option value="P1">P1</option> <option value="P2">P2</option> <option value="P3">P3</option> <option value="P4">P4</option> <option value="P5">P5</option> </select> How i can access selected item from php file by using '$_POST['pallete']' please help me. Thanks in advance..

    Read the article

  • Display a summary of form element values before submit

    - by Dirty Bird Design
    Using jquery formtowizard.js with an ajax submit. I want the last step of the form to display a summary of all form fields that were filled out. I can get it to work in isolated test cases, but not in full use. Form <form id="Commission" method="post" action="PHP/CommissionsSubmit.php"> <fieldset id="Initial"> <legend>Enter Your Information</legend> <ul> <li> <label for="FName">First Name*</label><input type="text" name="FName" id="FName"> </li> //repeat many li's </ul> </fieldset> <fieldset> <legend>Second Step</legend> //more li's </fieldset> <fieldset> <legend>Confirmation</legend> <span id="CFName"></span> </fieldset> </form> the jquery to get "#CFName" value $('#FName').keyup(function() { $('#CFName').val($(this).val()); }); I can't get the value to appear in the span "#CFName"... Could this have to do with the "serialize" function or anything going on with my $ajax submit function? its happening before submit... Please help! I apologize, but I've gone back and forth with "#CFName" being a span and an input, using .val and .html respectively

    Read the article

  • Faster Javascript text replace

    - by Stacey
    Given the following javascript (jquery) $("#username").keyup(function () { selected.username = $("#username").val(); var url = selected.protocol + (selected.prepend == true ? selected.username : selected.url) + "/" + (selected.prepend == true ? selected.url : selected.username); $("#identifier").val(url); }); This code basically reads a textbox (username), and when it is typed into, it reconstructs the url that is being displayed in another textbox (identifier). This works fine - there are no problems with its functionality. However it feels 'slow' and 'sluggish'. Is there a cleaner/faster way to accomplish this task? Here is the HTML as requested. <fieldset class="identifier delta"> <form action="/authenticate/openid" method="post" target="_top" > <input type="text" class="openid" id="identifier" name="identifier" readonly="readonly" /> <input type='text' id='username' name='username' class="left" style='display: none;'/> <input type="submit" value="Login" style="height: 32px; padding-top: 1px; margin-right: 0px;" class="login right" /> </form> </fieldset> The identifier textbox just has a value set based on the hyperlink anchor of a button.

    Read the article

  • Find class in table row

    - by meep
    Hello. Take a look at this table: <table cellpadding="0" cellspacing="0" class="order_form"> <tr> <th>Amount</th> <th>Desc</th> <th>Price</th> <th>Total</th> </tr> <tr> <td><input type="text" class="order_count" /></td> <td> <span class="order_desc">Middagstallerken</span> </td> <td> <span class="order_price">1,15</span> </td> <td> <span class="order_each_total"></span> </td> </tr> [...] </table> Upon entering amount I need to select the class "order_price" and multiply it with the value of the input "order_count" and place it in "order_each_count". I have millions of these rows so I need to find the next class in the row. I have tried using some function like this but without result: <script type="text/javascript"> $(document).ready(function(){ $('.order_count').keyup(function() { var each_price = $(this).prevUntil("tr").find("span.order_price").text(); }); }); </script> I hope someone have a good solution :-)

    Read the article

  • What's the best practice for make username check like Twitter ?

    - by Space Cracker
    I develop registration form and it have username field, and it's required to be like twitter username check ( real time check ) .. i already develop as in every textbox key up I use jquery to pass textbox.Text to page that return if is username exist or not as following code : function Check() { var userName = $('#<%= TextBox1.ClientID %>').val(); if (userName.length < 3) { $('#checkUserNameDIV').html("user name must be between 3 and 20"); return; } $('#checkUserNameDIV').html('<img src="loader.gif" />'); //setTimeout("CheckExistance('" + userName + "')", 5000); CheckExistance(userName); } function CheckExistance(userName) { $.get( "JQueryPage.aspx", { name: userName }, function(result) { var msg = ""; if (result == "1") msg = "Not Exist " + '<img src="unOK.gif" />'; else if (result == "0") msg = "Exist" ; else if (result == "error") msg = "Error , try again"; $('#checkUserNameDIV').html(msg); } ); } but i don't know if is it the best way to do that ? specially i do check every keyup .. is there any design pattern for this problem or nay good practice for doing that ?

    Read the article

  • Event triggering inside prototype

    - by shivesh
    When I try to call "Test" function I get an error. How to fix that? (no jquery!) Browser:firefox error: TypeError: this.Test is not a function <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> <script type="text/javascript"> MyClass = function(){ } MyClass.prototype = { Init: function(){ var txt = document.getElementById("text"); if (txt.addEventListener) { txt.addEventListener("keyup", this.Foo, true) } }, Foo: function(){ this.Test(); }, Test: function(){ alert('OK'); } } window.onload = function(){ obj = new MyClass; obj.Init(); } </script> </head> <body> <textarea id="text" rows="10"> </textarea> </div> </body>

    Read the article

  • JQuery:bind.blur() is not working

    - by user198880
    Hello, I need to add a row to a table.I am using jQuery to add the row.But i my Add() function everyhing is working fine except that the blur function for the input fild "txtQuantity" is not getting triggered for the newly added row.Here is my function, function Add() { var rowPart = $('#trPart0').clone(true).show().insertAfter('#tblPart tbody>tr:last'); var index = document.getElementById("hdnMaxPartId").value; $("#tblPart tbody>tr:last").attr("id", "trPart" + index); $("td:eq(0) img", rowPart).attr("id", "imgPartDelete" + index).attr("onclick", ""); $("td:eq(1) input:eq(0)", rowPart).attr("id", "hdnWODefPartId" + index); $("td:eq(1) input:eq(1)", rowPart).attr("id", "hdnPartCost" + index); $("td:eq(1) input:eq(3)", rowPart).attr("id", "txtPart" + index).attr("name", "txtPart" + index).attr("onkeyup", ""); $("td:eq(2) input", rowPart).attr("id", "txtQuantity" + index).attr("onblur", ""); $("td:eq(3) div", rowPart).attr("id", "divPartCost" + index); $("td:eq(4) div", rowPart).attr("id", "divPartUnit" + index); $("#imgPartDelete" + index).unbind().bind('click', function() { DeletePart(index); } ); $("#txtPart" + index).unbind().bind('keyup', function() { ajax_showOptions(this,"getPartForAC",event,2,"replace","div_part_list"+index); } ); $("#txtQuantity" + index).unbind().bind('blur', function() { ChangeClassForObject(this,"clsSpText_blur"); CalculateCost(index,this,"divPartCost"+index); } ); }

    Read the article

  • need help speeding up tag cloud filter for IE

    - by rod
    Hi All, Any ideas on how to speed this up in IE (performs decent in Firefox, but almost unusable in IE). Basically, it's a tag cloud with a filter text box to filter the cloud. <html> <head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#tagFilter').keyup(function(e) { if (e.keyCode==8) { $('#cloudDiv > span').show(); } $('#cloudDiv > span').not('span:contains(' + $(this).val() + ')').hide(); }); }); </script> </head> <body> <input type="text" id="tagFilter" /> <div id="cloudDiv" style="height: 200px; width: 400px; overflow: auto;"> <script type="text/javascript"> for (i=0;i<=1300;i++) { document.write('<span><a href="#">Test ' + i + '</a>&nbsp;</span>'); } </script> </div> </body> </html> thanks, rodchar

    Read the article

  • Bind event to AJAX populated list items

    - by AnPel
    I have an unordered list with no list items. I get some information from the user, I run it through my database using AJAX and the servers sends back a JSON object response. Then I append each list item I want to display to the list using something like $('blabla').append('<li>information</li>') My question is, since the li elements were not there at the time the DOM was ready, how can I bind a click event to them? Here is my full code: $(function(){ var timer; $('#f').keyup(function(){ clearTimeout(timer); timer = setTimeout(getSuggestions, 400); }); }) function getSuggestions(){ var a = $('#f')[0].value.length; if( a < 3){ if(a == 0){ $('#ajaxerror').hide(300,function(){ $('#loading').hide(300,function(){ $('#suggest').hide(300) }) }) } return; } $('#loading').slideDown(200,function(){ $.ajax({ url: '/models/AJAX/suggest.php', dataType: 'json', data: {'data' : $('#f')[0].value }, success: function(response){ $('#ajaxerror').hide(0,function(){ $('#loading').hide(100,function(){ $('#suggest ul li').remove(); for(var b = 0; b < ( response.rows * 3); b = b + 3){ $('#suggest ul').append('<li>'+response[b]+' '+response[b+1]+' '+response[b+2]+'</li>') // MISSING SOME CODE HERE TO BIND CLICK EVENT TO NEWLY CREATED LI } $('#suggest').show(300) }) }) }, error: function(){ $('#suggest').hide(0,function(){ $('#loading').slideUp(100,function(){ $('#ajaxerror').show(300) }) }) } }) }) }

    Read the article

  • How-to call server side Java from JavaScript

    - by frank.nimphius
    Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} The af:serverListener tag in Oracle ADF Faces allows JavaScript to call into server side Java. The example shown below uses an af:clientListener tag to invoke client side JavaScript in response to a key stroke in an Input Text field. The script then call a defined af:serverListener by its name defined in the type attribute. The server listener can be defined anywhere on the page, though from a code readability perspective it sounds like a good idea to put it close to from where it is invoked. <af:inputText id="it1" label="...">   <af:clientListener method="handleKeyUp" type="keyUp"/>   <af:serverListener type="MyCustomServerEvent"                      method="#{mybean.handleServerEvent}"/> </af:inputText> The JavaScript function below reads the event source from the event object that gets passed into the called JavaScript function. The call to the server side Java method, which is defined on a managed bean, is issued by a JavaScript call to AdfCustomEvent. The arguments passed to the custom event are the event source, the name of the server listener, a message payload formatted as an array of key:value pairs, and true/false indicating whether or not to make the call immediate in the request lifecycle. <af:resource type="javascript">     function handleKeyUp (evt) {    var inputTextComponen = event.getSource();       AdfCustomEvent.queue(inputTextComponent,                         "MyCustomServerEvent ",                         {fvalue:component.getSubmittedValue()},                         false);    event.cancel();}   </af:resource> The server side managed bean method uses a single argument signature with the argument type being ClientEvent. The client event provides information about the event source object - as provided in the call to AdfCustomEvent, as well as the payload keys and values. The payload is accessible from a call to getParameters, which returns a HashMap to get the values by its key identifiers.  public void handleServerEvent(ClientEvent ce){    String message = (String) ce.getParameters().get("fvalue");   ...  } Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} Find the tag library at: http://download.oracle.com/docs/cd/E15523_01/apirefs.1111/e12419/tagdoc/af_serverListener.html

    Read the article

  • MVC - Ajax form - return partial view doesnt update in <div> target

    - by Jack
    I have an index view that I want to update automatically as the user types in a client id. I got something similiar to work (only it was updating just a label) - but this will not work. What happens is the partial is just rendered by itself (not in place of the UpdateTargetID). So the data is rendered on a new page. Here is my code: Controller: public ActionResult ClientList(string queryText) { var clients = CR.GetClientLike(queryText); return PartialView("ClientIndex", clients); } Partial View: <table> <thead> <tr> <td>Client ID</td> <td>Phone1</td> <td>Phone2</td> <td>Phone3</td> <td>Phone4</td> </tr> </thead> <tbody> <% if (Model != null) { foreach (Client c in Model) { %> <tr> <td><%= Html.Encode(c.ClientID)%></td> <td><%= Html.Encode(c.WorkPhone)%></td> <td><%= Html.Encode(c.WorkPhone1)%></td> <td><%= Html.Encode(c.WorkPhone2)%></td> <td><%= Html.Encode(c.WorkPhone3)%></td> </tr> <% } } %> </tbody> Main View: Insert code messed up, so this is just copy/pasted: $(function() { $("#queryText").keyup(function() { $('#sForm').submit(); }); }); <% using (Ajax.BeginForm("ClientList", /* new { queryText = Form.Controls[2] ?? }*/"", new AjaxOptions { UpdateTargetId = "status", InsertionMode = InsertionMode.Replace }, new { @id = "sForm" })) { % <% } % <div id="status" class="status" name="status"> <%--<% Html.RenderPartial("ClientIndex", ViewData["clients"]); %> Should this be here???? --%> </div>

    Read the article

  • Using will_paginate with AJAX live search with jQuery in Rails

    - by Mark Richman
    I am using will_paginate to successfully page through records. I am also using AJAX live search via jQuery to update my results div. No problem so far. The issue I have is when trying to paginate through those live search results. I simply get "Page is loading..." with no div update. Am I missing something fundamental? # index.html.erb <form id="searchform" accept-charset="utf-8" method="get" action="/search"> Search: <input id="search" name="search" type="text" autocomplete="off" title="Search location, company, description..." /> <%= image_tag("spinner.gif", :id => "spinner", :style =>"display: none;" ) %> </form> # JobsController#search def search if params[:search].nil? @jobs = Job.paginate :page => params[:page], :order => "created_at desc" elsif params[:search] and request.xhr? @jobs = Job.search params[:search], params[:page] end render :partial => "jobs", :layout => false, :locals => { :jobs => @jobs } end # Job#search def self.search(search, page) logger.debug "Job.paginate #{search}, #{page}" paginate :per_page => @@per_page, :page => page, :conditions => ["description LIKE ? or title LIKE ? or company LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%"], :order => 'created_at DESC' end # search.js $(document).ready(function(){ $("#search").keyup(function() { $("#spinner").show(); // show the spinner var form = $(this).parents("form"); // grab the form wrapping the search bar. var url = form.attr("action"); // grab the URL from the form's action value. var formData = form.serialize(); // grab the data in the form $.get(url, formData, function(html) { // perform an AJAX get, the trailing function is what happens on successful get. $("#spinner").hide(); // hide the spinner $("#jobs").html(html); // replace the "results" div with the result of action taken }); }); });

    Read the article

  • node.js / socket.io, cookies only working locally

    - by Ben Griffiths
    I'm trying to use cookie based sessions, however it'll only work on the local machine, not over the network. If I remove the session related stuff, it will however work just great over the network... You'll have to forgive the lack of quality code here, I'm just starting out with node/socket etc etc, and finding any clear guides is tough going, so I'm in n00b territory right now. Basically this is so far hacked together from various snippets with about 10% understanding of what I'm actually doing... The error I see in Chrome is: socket.io.js:1632GET http://192.168.0.6:8080/socket.io/1/?t=1334431940273 500 (Internal Server Error) Socket.handshake ------- socket.io.js:1632 Socket.connect ------- socket.io.js:1671 Socket ------- socket.io.js:1530 io.connect ------- socket.io.js:91 (anonymous function) ------- /socket-test/:9 jQuery.extend.ready ------- jquery.js:438 And in the console for the server I see: debug - served static content /socket.io.js debug - authorized warn - handshake error No cookie My server is: var express = require('express') , app = express.createServer() , io = require('socket.io').listen(app) , connect = require('express/node_modules/connect') , parseCookie = connect.utils.parseCookie , RedisStore = require('connect-redis')(express) , sessionStore = new RedisStore(); app.listen(8080, '192.168.0.6'); app.configure(function() { app.use(express.cookieParser()); app.use(express.session( { secret: 'YOURSOOPERSEKRITKEY', store: sessionStore })); }); io.configure(function() { io.set('authorization', function(data, callback) { if(data.headers.cookie) { var cookie = parseCookie(data.headers.cookie); sessionStore.get(cookie['connect.sid'], function(err, session) { if(err || !session) { callback('Error', false); } else { data.session = session; callback(null, true); } }); } else { callback('No cookie', false); } }); }); var users_count = 0; io.sockets.on('connection', function (socket) { console.log('New Connection'); var session = socket.handshake.session; ++users_count; io.sockets.emit('users_count', users_count); socket.on('something', function(data) { io.sockets.emit('doing_something', data['data']); }); socket.on('disconnect', function() { --users_count; io.sockets.emit('users_count', users_count); }); }); My page JS is: jQuery(function($){ var socket = io.connect('http://192.168.0.6', { port: 8080 } ); socket.on('users_count', function(data) { $('#client_count').text(data); }); socket.on('doing_something', function(data) { if(data == '') { window.setTimeout(function() { $('#target').text(data); }, 3000); } else { $('#target').text(data); } }); $('#textbox').keydown(function() { socket.emit('something', { data: 'typing' }); }); $('#textbox').keyup(function() { socket.emit('something', { data: '' }); }); });

    Read the article

  • JQGrid and JQuery Autocomplete

    - by Neff
    When implementing JQGrid 4.3.0, Jquery 1.6.2, and JQuery UI 1.8.16 Ive come across an issue with the Inline edit. When the inline edit is activated, some of the elements get assigned an auto complete. When the inline edit is canceld or saved, the auto complete does not always go away (selecting text by double clicking it then hitting delete, then hitting escape to exit row edit). Leaving the auto complete controls in edit mode when the row is no longer considered in edit mode. Perhaps you can tell me if there is a problem with the initialization or if I you are aware of an event post-"afterrestorefunc" that the fields can be returned to their "original" state. Original state being displayed as data in the JQGrid row. I've tried removing the DOM after row close, .remove() and .empty(): ... "afterrestorefunc": function(){ $('.ui-autocomplete-input').remove(); } ... but that causes other issues, such as the jqgrid is not able to find the cell when serializing the row for data or edit, and requires a refresh of the page, not just jqgrid, to be able to once again see the data from that row. Auto complete functionality for the element is created on the double click of the row: function CreateCustomSearchElement(value, options, selectiontype) { ... var el; el = document.createElement("input"); ... $(el).autocomplete({ source: function (request, response) { $.ajax({ url: '<%=ResolveUrl("~/Services/AutoCompleteService.asmx/GetAutoCompleteResponse") %>', data: "{ 'prefixText': '" + request.term + "', 'contextKey': '" + options.name + "'}", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", success: function (data) { response($.map(data.d, function (item) { return { label: Trim(item), value: Trim(item), searchVal: Trim(item) } })) } }); }, select: function (e, item) { //Select is on the event of selection where the value and label have already been determined. }, minLength: 1, change: function (event, ui) { //if the active element was not the search button //... } }).keyup(function (e) { if (e.keyCode == 8 || e.keyCode == 46) { //If the user hits backspace or delete, check the value of the textbox before setting the searchValue //... } }).keydown(function (e) { //if keycode is enter key and there is a value, you need to validate the data through select or change(onblur) if (e.keyCode == '13' && ($(el).val())) { return false; } if (e.keyCode == '220') { return false } }); } Other Sources: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing http://api.jqueryui.com/autocomplete/ Update: I tried only creating the autocomplete when the element was focused, and removing it when onblur. That did not resolve the issue either. It seems to just need the autocomplete dropdown to be triggered.

    Read the article

  • jQuery bind efficiency

    - by chelfers
    I'm having issue with load speed using multiple jQuery binds on a couple thousands elements and inputs, is there a more efficient way of doing this? The site has the ability to switch between product lists via ajax calls, the page cannot refresh. Some lists have 10 items, some 100, some over 2000. The issue of speed arises when I start flipping between the lists; each time the 2000+ item list is loaded the system drags for about 10 seconds. Before I rebuild the list I am setting the target element's html to '', and unbinding the two bindings below. I'm sure it has something to do with all the parent, next, and child calls I am doing in the callbacks. Any help is much appreciated. loop 2500 times <ul> <li><input type="text" class="product-code" /></li> <li>PROD-CODE</li> ... <li>PRICE</li> </ul> end loop $('li.product-code').bind( 'click', function(event){ selector = '#p-'+ $(this).prev('li').children('input').attr('lm'); $(selector).val( ( $(selector).val() == '' ? 1 : ( parseFloat( $(selector).val() ) + 1 ) ) ); Remote.Cart.lastProduct = selector; Remote.Cart.Products.Push( Remote.Cart.customerKey, { code : $(this).prev('li').children('input').attr('code'), title : $(this).next('li').html(), quantity : $('#p-'+ $(this).prev('li').children('input').attr('lm') ).val(), price : $(this).prev('li').children('input').attr('price'), weight : $(this).prev('li').children('input').attr('weight'), taxable : $(this).prev('li').children('input').attr('taxable'), productId : $(this).prev('li').children('input').attr('productId'), links : $(this).prev('li').children('input').attr('productLinks') }, '#p-'+ $(this).prev('li').children('input').attr('lm'), false, ( parseFloat($(selector).val()) - 1 ) ); return false; }); $('input.product-qty').bind( 'keyup', function(){ Remote.Cart.lastProduct = '#p-'+ $(this).attr('lm'); Remote.Cart.Products.Push( Remote.Cart.customerKey, { code : $(this).attr('code') , title : $(this).parent().next('li').next('li').html(), quantity : $(this).val(), price : $(this).attr('price'), weight : $(this).attr('weight'), taxable : $(this).attr('taxable'), productId : $(this).attr('productId'), links : $(this).attr('productLinks') }, '#p-'+ $(this).attr('lm'), false, previousValue ); });

    Read the article

  • AJAX Issue, Works in all browsers except IE

    - by Nik
    Alright, this code works in Chrome and FF, but not IE (which is to be expected). Does anyone see anything wrong with this code that would render it useless in IE? var waittime=400; chatmsg = document.getElementById("chatmsg"); room = document.getElementById("roomid").value; sessid = document.getElementById("sessid").value; chatmsg.focus() document.getElementById("chatwindow").innerHTML = "loading..."; document.getElementById("userwindow").innerHTML = "Loading User List..."; var xmlhttp = false; var xmlhttp2 = false; var xmlhttp3 = false; function ajax_read() { if(window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); if(xmlhttp.overrideMimeType){ xmlhttp.overrideMimeType('text/xml'); } } else if(window.ActiveXObject){ try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ } } } if(!xmlhttp) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4) { document.getElementById("chatwindow").innerHTML = xmlhttp.responseText; setTimeout("ajax_read()", waittime); } } xmlhttp.open('GET','methods.php?method=r&room=' + room +'',true); xmlhttp.send(null); } function user_read() { if(window.XMLHttpRequest){ xmlhttp3=new XMLHttpRequest(); if(xmlhttp3.overrideMimeType){ xmlhttp3.overrideMimeType('text/xml'); } } else if(window.ActiveXObject){ try{ xmlhttp3=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try{ xmlhttp3=new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ } } } if(!xmlhttp3) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } xmlhttp3.onreadystatechange = function() { if (xmlhttp3.readyState==4) { document.getElementById("userwindow").innerHTML = xmlhttp3.responseText; setTimeout("user_read()", 10000); } } xmlhttp3.open('GET','methods.php?method=u&room=' + room +'',true); xmlhttp3.send(null); } function ajax_write(url){ if(window.XMLHttpRequest){ xmlhttp2=new XMLHttpRequest(); if(xmlhttp2.overrideMimeType){ xmlhttp2.overrideMimeType('text/xml'); } } else if(window.ActiveXObject){ try{ xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try{ xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ } } } if(!xmlhttp2) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } xmlhttp2.open('GET',url,true); xmlhttp2.send(null); } function submit_msg(){ nick = document.getElementById("chatnick").value; msg = document.getElementById("chatmsg").value; document.getElementById("chatmsg").value = ""; ajax_write("methods.php?method=w&m=" + msg + "&n=" + nick + "&room=" + room + "&sessid=" + sessid + ""); } function keyup(arg1) { if (arg1 == 13) submit_msg(); } var intUpdate = setTimeout("ajax_read()", waittime); var intUpdate = setTimeout("user_read()", 0);

    Read the article

  • creating a JQuery function

    - by Russell Parrott
    Sorry to bother you guys & girls again on Christmas eve, but I need help creating a reusable JQuery function. I have "badly crafted" this set of code that all works. But I would really like to put it as a function so I don't have to keep repeating everything for each form. I am not too sure about how all the if statements can be combined etc. that is why I wrote it as it is. Any help much appreciated - Oh I suppose it could also be some kind of plugin but that might be the next step if I can understand how the function works. $(':input:visible').live('blur',function(){ if($(this).attr('required')) { if($(this).val() == '' ) { $(this).css({'background-color':'#FFEEEE' }); $(this).parent('form').children('input[type=submit]').hide(); $(this).next('.errormsg').html('OOPs ... '+$(this).prev('label').html()+' is required'); $(this).focus(); $(this).attr('placeholder').hide(); } else { $(this).css({'background-color':'#FFF' , 'border-color':'#999999'}); $(this).next('.errormsg').empty(); $(this).parent('form').children('input[type=submit]').show(); } } return false; }); $(':input[max]').live('blur',function(){ if($(this).attr('max') < parseInt($(this).val()) ){ $(this).next('.errormsg').html( 'OOPs ... the maximum value is '+$(this).attr('max') ); $(this).parent('form').children('input[type=submit]').hide(); $(this).focus(); } else {} return false; }); $(':input[min]').live('blur',function(){ if($(this).attr('min') > parseInt($(this).val()) ){ $(this).next('.errormsg').html( 'OOPs ... the minimum value is '+$(this).attr('min') ); $(this).parent('form').children('input[type=submit]').hide(); $(this).focus(); } else {} return false; }); $(':input[maxlength]').live('keyup',function(){ if($(this).val()==''){ } else { $(this).next('.errormsg').html( $(this).attr('maxlength')- $(this).val().length +' chars remaining'); } return false; }); As said, help much appreciated with one small (I hope) thing, how can I break out of any function IF there are no error messages to actually submit the form?

    Read the article

  • working validation hint, working word counter but not working together

    - by Sriyani Rathnayaka
    I added a word counter to a my form's textarea... it is something like this... <div> <label>About you:</label> <textarea id="qualification" class="textarea hint_needed" rows="4" cols="30" ></textarea> <span class="hint">explain about you</span> <script type="text/javascript"> $("textarea").textareaCounter(); </script> </div> My problem is when I add textaracounter() like this my validation hint is not working.. when I remover the counter function validation hint is working... this is the jquery for hint message.. $(".hint").css({ "display":"none" }); $("input.hint_needed, select.hint_needed, textarea.hint_needed, radio.hint_needed").on("mouseenter", function() { $(this).next(".hint").css({ "display":"inline" }); }).on("mouseleave", function() { $(this).next(".hint").css({ "display":"none" }); }); this is for the word counter.. (function($){ $.fn.textareaCounter = function(options) { // setting the defaults // $("textarea").textareaCounter({ limit: 100 }); var defaults = { limit: 150 }; var options = $.extend(defaults, options); // and the plugin begins return this.each(function() { var obj, text, wordcount, limited; obj = $("#experience"); obj.after('<span style="font-weight: bold; color:#6a6a6a; clear: both; margin: 3px 0 0 150px; float: left; overflow: hidden;" id="counter-text">Max. '+options.limit+' words</span>'); obj.keyup(function() { text = obj.val(); if(text === "") { wordcount = 0; } else { wordcount = $.trim(text).split(" ").length; } if(wordcount > options.limit) { $("#counter-text").html('<span style="color: #DD0000;">0 words left</span>'); limited = $.trim(text).split(" ", options.limit); limited = limited.join(" "); $(this).val(limited); } else { $("#counter-text").html((options.limit - wordcount)+' words left'); } }); }); }; })(jQuery); can anybody tell me what is the problem there? Thank you..

    Read the article

  • color letters in a div

    - by Growler
    I've created a palindrome checker. I want to take it one step further and show the letters being compared as it is being checked. HTML: <p id="typing"></p> <input type="text" id="textBox" onkeyup="pal(this.value);" value="" /> <div id="response"></div> <hr> <div id="palindromeRun"></div> JS: To do this, I run the recursive check... Then if it is a palindrome, I run colorLetters(), which I'm trying to highlight in green each letter as it is being checked. Right now it is just rewriting palindromeRun's HTML with the first letter. I know this is because of the way I'm resetting its HTML. I don't know how to just grab the first and last letter, change only those letters' css, then increment i and j on the next setTimeout loop. var timeout2 = null; function pal (input) { var str = input.replace(/\s/g, ''); var str2 = str.replace(/\W/, ''); if (checkPal(str2, 0, str2.length-1)) { $("#textBox").css({"color" : "green"}); $("#response").html(input + " is a palindrome"); $("#palindromeRun").html(input); colorLetters(str2, 0, str2.length-1); } else { $("#textBox").css({"color" : "red"}); $("#response").html(input + " is not a palindrome"); } if (input.length <= 0) { $("#response").html(""); $("#textBox").css({"color" : "black"}); } } function checkPal (input, i, j) { if (input.length <= 1) { return false; } if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) { return true; } else { if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) { return checkPal(input, ++i, --j); } else { return false; } } } function colorLetters(myinput, i, j) { if (timeout2 == null) { timeout2 = setTimeout(function () { console.log("called"); var firstLetter = $("#palindromeRun").html(myinput.charAt(i)) var secondLetter = $("#palindromeRun").html(myinput.charAt(j)) $(firstLetter).css({"color" : "red"}); $(secondLetter).css({"color" : "green"}); i++; j++; timeout2=null; }, 1000); } } Secondary: If possible, I'd just like to have it colors the letters as the user is typing... I realize this will require a setTimeout on each keyup, but also am not sure how to write this.

    Read the article

  • Is it possible to make JQuery keydown respond faster?

    - by Drew Paul
    I am writing a simple page with JQuery and HTML5 canvas tags where I move a shape on the canvas by pressing 'w' for up, 's' for down, 'a' for left, and 'd' for right. I have it all working, but I would like the shape to start moving at a constant speed upon striking a key. Right now there is some kind of hold period and then the movement starts. How can I get the movement to occur immediately? Here the important part of my code: Your browser does not support the HTML5 canvas tag. start navigating coords should pop up here key should pop up here var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); //keypress movements var xtriggered = 0; var keys = {}; var north = -10; var east = 10; var flipednorth = 0; $(document).ready(function(e){ $("input").keydown(function(){ keys[event.which] = true; if (event.which == 13) { event.preventDefault(); } //press w for north if (event.which == 87) { north++; flipednorth--; } //press s for south if (event.which == 83) { north--; flipednorth++; } //press d for east if (event.which == 68) { east++; } //press a for west if (event.which == 65) { east--; } var msg = 'x: ' + flipednorth*5 + ' y: ' + east*5; ctx.beginPath(); ctx.arc(east*6,flipednorth*6,40,0,2*Math.PI); ctx.stroke(); $('#soul2').html(msg); $('#soul3').html(event.which ); $("input").css("background-color","#FFFFCC"); }); $("input").keyup(function(){ delete keys[event.which]; $("input").css("background-color","#D6D6FF"); }); }); </script> please let me know if I shouldn't be posting code this lengthy.

    Read the article

  • Form Search Onkeyup event

    - by Aryan
    I Have a Form In which the form should automatically search when i complete entering the 10th character in the text field but the below code is searching for each n every character i enter in the text field . . . I just want the result after completing the 10th character not for each n every character . . i have used onkeyup event and i set that value to 10 but still it is searching for each n every character... please do help me <body OnKeyPress="return disableKeyPress(event)"> <section id="content" class="container_12 clearfix" data-sort=true> <center><table class='dynamic styled with-prev-next' data-table-tools='{'display':true}' align=center> <script> function disableEnterKey(e) { var key; if(window.event) key = window.event.keyCode; //IE else key = e.which; //firefox return (key != 13); } function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","resdb.php?id="+str,true); xmlhttp.send(); } </script> <script type='text/javascript'> //<![CDATA[ $(window).load(function(){ $('#id').keyup(function(){ if(this.value.length ==10) }); });//]]> </script> <form id="form" method="post" name="form" > <tr><td><p align="center"><font size="3"><b>JNTUH - B.Tech IV Year II Semester (R07) Advance Supplementary Results - July 2012</b></font></p></td></tr> <td><p align="center"><b>Last Date for RC/RV : 8th August 2012</b></p></td> <tr><td><p align="center"></b> <input type="text" onkeyup="showUser(this.value)" onKeyPress="return disableEnterKey(event)" data-type="autocomplete" data-source="extras/autocomplete1.php" name="id" id="id" maxlength="10" placeholder=" Hall-Ticket Number">&emsp;</p></td></tr> </table> </center> </form> <center> <div id="txtHint"><b>Results will be displayed here</b></div> </center> </body>

    Read the article

  • jquery position changing with .css() behaving strange

    - by 11684
    I tried to make a moving img, and it works partially. If I press the right, up or down button, it moves right, up or down. But, if I press the left button, it jumps very fast very far to the right, and then back to the left and doesn't stop moving (I believe. I said it was fast). JSFiddle; Javascript: $(document).ready(function() { var up = down = left = right = false; var top = 100, left = 500; $("body").on("keydown", function(e) { if(e.keyCode == 39) {e.preventDefault(); if (right == false) right = setInterval(moveRight, 80);} else if(e.keyCode == 37) {e.preventDefault(); if (left == false) left = setInterval(moveLeft, 80);} else if(e.keyCode == 38) {e.preventDefault(); if (up == false) up = setInterval(moveUp, 80);} else if(e.keyCode == 40) {e.preventDefault(); if (down == false) down = setInterval(moveDown, 80);} }); $("body").on("keyup", function(e) { if(e.keyCode == 39) {clearInterval(right); right = false;} else if(e.keyCode == 37) {clearInterval(left); left = false;} else if(e.keyCode == 38) {clearInterval(up); up = false;} else if(e.keyCode == 40) {clearInterval(down); down = false;} }); function moveUp() { top -= 2; $("#player").css("top", top + "px"); } function moveDown() { top += 2; $("#player").css("top", top + "px"); } function moveLeft() { left -= 2; $("#player").css("left", left + "px"); } function moveRight() { left += 2; $("#player").css("left", left + "px"); } }); This is probably not the best way to do this, I'm open for better suggestions. Thanks for reading!

    Read the article

  • jQuery.post not working when using data type json

    - by swift
    I have been trying to utilize json in this jQuery.post because I need to return two values from my executed php. The code was working when I was not implementing json. I need to see if a promo code entered is valid for a particular broker. The two variables I need back are the instant message whether or not it's valid (this is displayed to the user) and I need to update a hidden field that will be used later while updating the database. The jQuery.post does not seem to be firing at all, but the code directly above it (the ajax-loader.gif) is working. I did re-write the whole thing at one point using jQuery.ajax, and had issues there too. Granted, I have probably been looking at this too long and have tried to re-write too many times, but any help is greatly appreciated!! Here's the jQuery.post <!-- Below Script is for Checking Promo Code Against Database--> <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#promocode").keyup(function (e) { //removes spaces from PromoCode jQuery(this).val(jQuery(this).val().replace(/\s/g, '')); var promocode = jQuery(this).val(); var brokerdealerid = document.getElementById("BrokerDealerId").value; if(promocode.length > 0 ){ jQuery("#promo-result").html('<img src="../imgs/ajax-loader.gif" />'); jQuery.post( '../check_promocode.php', {promocode:promocode, brokerdealerid:brokerdealerid}, function(data) { $("#promo-result").html(data.promoresult); $("#promo-result-valid").html(data.promovalid); }, "json"); } }); }); </script> <!-- End Script is for Checking Promo Code Against Database--> Here's relevant code from check_promocode.php: //sanitize incoming parameters if (isset($_POST['brokerdealerid'])) $brokerdealerid = sanitizeMySQL($_POST['brokerdealerid']); $promocode = sanitizeMySQL($promocode); //check promocode in db $results = mysql_query("SELECT PromotionCodeIdentifier FROM PromotionCode WHERE PromotionCodeIdentifier='$promocode' AND BrokerDealerId='$brokerdealerid' AND PromotionCodStrtDte <= CURDATE() AND PromotionCodExpDte >= CURDATE()"); //return total count $PromoCode_exist = mysql_num_rows($results); //total records //if value is more than 0, promocode is valid if($PromoCode_exist) { echo json_encode(array("promoresult"=>"Promotion Code Valid", "promovalid"=>"Y")); exit(); }else{ echo json_encode(array("promoresult"=>"Invalid Promotion Code", "promovalid"=>"N")); exit(); }

    Read the article

  • Client side code snipets

    - by raghu.yadav
    function clientMethodCall(event) { component = event.getSource(); AdfCustomEvent.queue(component, "customEvent",{payload:component.getSubmittedValue()}, true); event.cancel(); } ]]-- <af:document>      <f:facet name="metaContainer">      <af:group>        <!--[CDATA[            <script>                function clientMethodCall(event) {                                       component = event.getSource();                    AdfCustomEvent.queue(component, "customEvent",{payload:component.getSubmittedValue()}, true);                                                     event.cancel();                                    }                 </script> ]]-->      </af:group>    </f:facet>      <af:form>        <af:panelformlayout>          <f:facet name="footer">          <af:inputtext label="Let me spy on you: Please enter your mail password">            <af:clientlistener method="clientMethodCall" type="keyUp">            <af:serverlistener type="customEvent" method="#{customBean.handleRequest}">          </af:serverlistener>bean code    public void handleRequest(ClientEvent event){                System.out.println("---"+event.getParameters().get("payload"));            } tree<af:tree id="tree1" value="#{bindings.DepartmentsView11.treeModel}" var="node" selectionlistener="#{bindings.DepartmentsView11.treeModel.makeCurrent}" rowselection="single">    <f:facet name="nodeStamp">      <af:outputtext value="#{node}">    </af:outputtext>    <af:clientlistener method="expandNode" type="selection">  </af:clientlistener></f:facet>   <f:facet name="metaContainer">        <af:group>          <!--[CDATA[            <script>                function expandNode(event){                    var _tree = event.getSource();                    rwKeySet = event.getAddedSet();                    var firstRowKey;                    for(rowKey in rwKeySet){                       firstRowKey  = rowKey;                        // we are interested in the first hit, so break out here                        break;                    }                    if (_tree.isPathExpanded(firstRowKey)){                         _tree.setDisclosedRowKey(firstRowKey,false);                    }                    else{                        _tree.setDisclosedRowKey(firstRowKey,true);                    }               }        </script> ]]-->        </af:group>      </f:facet>   </af:tree> </af:clientlistener></af:inputtext></f:facet></af:panelformlayout></af:form></af:document> bean code public void handleRequest(ClientEvent event){ System.out.println("---"+event.getParameters().get("payload")); } tree function expandNode(event){ var _tree = event.getSource(); rwKeySet = event.getAddedSet(); var firstRowKey; for(rowKey in rwKeySet){ firstRowKey = rowKey; // we are interested in the first hit, so break out here break; } if (_tree.isPathExpanded(firstRowKey)){ _tree.setDisclosedRowKey(firstRowKey,false); } else{ _tree.setDisclosedRowKey(firstRowKey,true); } } ]]--

    Read the article

  • How do I do Collisions in my JavaScript Game Code Below?

    - by Henry
    I'm trying to figure out how would I add collision detection to my code so that when the "Man" character touches the "RedHouse" the RedHouse disappears? Thanks. By the way, I'm new to how things are done on this site, so thus, if there is anything else needed or so, let me know. <title>HMan</title> <body style="background:#808080;"> <br> <canvas id="canvasBg" width="800px" height="500px"style="display:block;background:#ffffff;margin:100px auto 0px;"></canvas> <canvas id="canvasRedHouse" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas> <canvas id="canvasEnemy" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas> <canvas id="canvasEnemy2" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas> <canvas id="canvasMan" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas> <script> var isPlaying = false; var requestAnimframe = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame; var canvasBg = document.getElementById('canvasBg'); var ctxBg = canvasBg.getContext('2d'); var canvasRedHouse = document.getElementById('canvasRedHouse'); var ctxRedHouse = canvasRedHouse.getContext('2d'); var House1; House1 = new RedHouse(); var canvasMan = document.getElementById('canvasMan'); var ctxMan = canvasMan.getContext('2d'); var Man1; Man1 = new Man(); var imgSprite = new Image(); imgSprite.src = 'SpritesI.png'; imgSprite.addEventListener('load',init,false); function init() { drawBg(); startLoop(); document.addEventListener('keydown',checkKeyDown,false); document.addEventListener('keyup',checkKeyUp,false); } function drawBg() { var SpriteSourceX = 0; var SpriteSourceY = 0; var drawManOnScreenX = 0; var drawManOnScreenY = 0; ctxBg.drawImage(imgSprite,SpriteSourceX,SpriteSourceY,800,500,drawManOnScreenX, drawManOnScreenY,800,500); } function clearctxBg() { ctxBg.clearRect(0,0,800,500); } function Man() { this.SpriteSourceX = 10; this.SpriteSourceY = 540; this.width = 40; this.height = 115; this.DrawManOnScreenX = 100; this.DrawManOnScreenY = 260; this.speed = 10; this.actualFrame = 1; this.speed = 2; this.isUpKey = false; this.isRightKey = false; this.isDownKey = false; this.isLeftKey = false; } Man.prototype.draw = function () { clearCtxMan(); this.updateCoors(); this.checkDirection(); ctxMan.drawImage(imgSprite,this.SpriteSourceX,this.SpriteSourceY+this.height* this.actualFrame, this.width,this.height,this.DrawManOnScreenX,this.DrawManOnScreenY, this.width,this.height); } Man.prototype.updateCoors = function(){ this.leftX = this.DrawManOnScreenX; this.rightX = this.DrawManOnScreenX + this.width; this.topY = this.DrawManOnScreenY; this.bottomY = this.DrawManOnScreenY + this.height; } Man.prototype.checkDirection = function () { if (this.isUpKey && this.topY > 240) { this.DrawManOnScreenY -= this.speed; } if (this.isRightKey && this.rightX < 800) { this.DrawManOnScreenX += this.speed; } if (this.isDownKey && this.bottomY < 500) { this.DrawManOnScreenY += this.speed; } if (this.isLeftKey && this.leftX > 0) { this.DrawManOnScreenX -= this.speed; } if (this.isRightKey && this.rightX < 800) { if (this.actualFrame > 0) { this.actualFrame = 0; } else { this.actualFrame++; } } if (this.isLeftKey) { if (this.actualFrame > 2) { this.actualFrame = 2; } function checkKeyDown(var keyID = e.keyCode || e.which; if (keyID === 38) { Man1.isUpKey = true; e.preventDefault(); } if (keyID === 39 ) { Man1.isRightKey = true; e.preventDefault(); } if (keyID === 40 ) { Man1.isDownKey = true; e.preventDefault(); } if (keyID === 37 ) { Man1.isLeftKey = true; e.preventDefault(); } } function checkKeyUp(e) { var keyID = e.keyCode || e.which; if (keyID === 38 || keyID === 87) { Man1.isUpKey = false; e.preventDefault(); } if (keyID === 39 || keyID === 68) { Man1.isRightKey = false; e.preventDefault(); } if (keyID === 40 || keyID === 83) { Man1.isDownKey = false; e.preventDefault(); } if (keyID === 37 || keyID === 65) { Man1.isLeftKey = false; e.preventDefault(); } } function clearCtxMan() { ctxMan.clearRect(0,0,800,500); } function RedHouse() { this.srcX = 135; this.srcY = 525; this.width = 265; this.height = 245; this.drawX = 480; this.drawY = 85; } RedHouse.prototype.draw = function () { clearCtxRedHouse(); ctxRedHouse.drawImage(imgSprite,this.srcX,this.srcY, this.width,this.height,this.drawX,this.drawY,this.width,this.height); }; function clearCtxRedHouse() { ctxRedHouse.clearRect(0,0,800,500); } function loop() { if (isPlaying === true){ Man1.draw(); House1.draw(); requestAnimframe(loop); } } function startLoop(){ isPlaying = true; loop(); } function stopLoop(){ isPlaying = false; } </script> <style> .top{ position: absolute; top: 4px; left: 10px; color:black; } .top2{ position: absolute; top: 60px; left: 10px; color:black; } </style> <div class="top"> <p><font face="arial" color="black" size="4"><b>HGame</b><font/><p/> <p><font face="arial" color="black" size="3"> My Game Here <font/><p/> </div> <div class="top2"> <p><font face="arial" color="black" size="3"> It will start now <font/><p/> </div>

    Read the article

< Previous Page | 5 6 7 8 9 10  | Next Page >