Question

In my jQuery Mobile code, I have some onClick and onKeyPress events but they are not firing. I am converting my client's website to a mobile version that includes lot of javascript functions. I don't know if it works if I convert everything into jQuery but I prefer not to do so and would like to keep the javascript functions as it is.

Is there a way to make this work entirely with javascript and not with jQuery?

onClick="javascript:alert('test');" seems to work fine. It's just the functions that are not being called.

http://jsfiddle.net/jetlag/CtkTV/1/

HTML:

<div data-role="fieldcontain">
  <label for="textA">Input A</label>
  <input class="inputField" id="textA" value="" type="text" onFocus="javascript:clearText(this);" value="This is default text A" />
</div>
<div data-role="fieldcontain">
  <label for="textB">Input B</label>
  <input class="inputField" id="textB" value="" type="text" onKeyPress="javascript:keyPressEvent(e);" onFocus="javascript:clearText(this);" value="This is default text B" />
 </div>
 <div class="ui-grid-b">
   <div class="ui-block-a"><input type="button" id="goButton" onClick="javascript:goButtonPress();" value="Go" />
   </div>
   <div class="ui-block-b"><input type="button" id="testButton" onClick="javascript:alert('Alerted!');" value="Alert" />
   </div>
</div>

Javascript:

function keyPressEvent(e) {
  var evt = e || window.event;
  var keyPressed = evt.which || evt.keyCode;
  if (keyPressed == 13) {
    document.getElementById('goButton').click();
    evt.cancel = true;
  }
}

function goButtonPress() {
  alert('Button Pressed");
}
Was it helpful?

Solution 2

There is no e it should be event in your markup. i.e javascript:keyPressEvent(event)

 <input class="inputField" id="textB" value="" type="text" onKeyPress="javascript:keyPressEvent(event);" onFocus="javascript:clearText(this);" value="This is default text B" />

Also Your quotes are at wrong:-

function goButtonPress() {
  alert('Button Pressed"); <-- here quotes should match
}

Fiddle

See events

OTHER TIPS

Working example: http://jsfiddle.net/Gajotres/aLB6T/

While there's nothing wrong with inline java script you should not use it when working with jQuery Mobile. Because of its architecture it can cause big problems. That is why if possible use classic jQuery.

$(document).on('pagebeforeshow', '#index', function(){ 
    $(document).on('click', '#testButton', function(){ 
        alert('Alerted!');       
    });

    $(document).on('click', '#goButton', function(){ 
        alert('Button Pressed');      
    });        

    $(document).on('keypress', '#textB, #textA', function(evt){ 
        var keyPressed = evt.which || evt.keyCode;
        alert(keyPressed);
        if (keyPressed == 13) {
            document.getElementById('goButton').click();
            evt.cancel = true;
        }     
    });    
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top