Iphone Development - How to display a numeric keyboard? - iphone

I'm working on a mobile website which is NOT a native iPhone app but rather a simple m.somedomain.com website which is developed in c# asp.net .
Objective :
On clicking one of the text boxes how do I display the numeric keyboard only ?
Note : The website is NOT in HTML5 and is not part of a webview inside a Native app but rather a standalone regular website
My textbox is a regular asp.net text box :
<asp:TextBox runat="server" CssClass="reference_input" Text="1234567" />

EDIT: I found here that you can use
<input type="text" pattern="[0-9]*" />
to tell mobile safari to set the numeric keyboard as default, without needing to specify the telephone keyboard.
EDIT 2 (from comments below): You can also use javascript to force numeric input as so:
<input type="text" pattern="[0-9]*" onKeypress="if(event.keyCode < 48 || event.keyCode > 57){return false;}" />

If you use type="tel" instead of type="text" it will bring up a numeric keyboard.

For Salesforce (not HTML input type='number'), below java-script should make the iPad, iPhone numeric keypad defaultly appear. (This solution should work for asp.net control as well)
<apex:page standardController="Account" >
<head>
<script type="text/javascript">
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
}
else
{
window.onload = function()
{
if (oldonload)
{
oldonload();
}
func();
}
}
}
addLoadEvent(function()
{
try{
var ctl = document.getElementById('{!$Component.frm.txtNumeric}');
type = document.createAttribute("type");
type.nodeValue = "number";
ctl.setAttributeNode(type);
}catch(err)
{
alert(err);
}
});
</script>
</head>
<body>
<apex:form id="frm" >
This is a numeric input <apex:inputfield id="txtNumeric" value="{!account.name}" style="width:200px;" />
</apex:form>
</body>
</apex:page>

Related

Why Is my script freezing up when I hit enter?

The majority of the Add-on is good but whenever I hit enter (which is, in my opinion, the most common way to submit a form, for example, a login form), but all it does is blank out.
I've tried linking the script with a onkeydown like so:
<div onkeydown="handle(event)">blagh blagh blagh</div>
but I still get the same results:
<html>
<form id='myForm' style="font-family:Georgia;">
<table>
<tr><td><h2>Enter your Password</h2></td></tr>
<tr><td><p>DO NOT HIT ENTER ON YOUR KEYBOARD!!!!!</p></td></tr>
<tr><td><input name='password' type='password' value="" onkeypress="handle(event)"></td></tr>
<tr><td><div id="submitbuttcontainer"><img id="submitloader" style="display:none;" src='https://lh6.googleusercontent.com/-S87nMBe6KWE/TuB9dR48F0I/AAAAAAAAByQ/0Z96LirzDqg/s27/load.gif' /><input id="submitbutt" type='button' onclick='showWorking();google.script.run.withSuccessHandler(onSuccess).decodeForRequest(document.getElementById("myForm"));' name="Submit" value="Submit"></div></td></tr>
</table>
</form>
<script>
function onSuccess(obj) {
document.getElementById('submitbutt').style.display="block";
document.getElementById('submitloader').style.display="none";
if(obj.status == 'success') {
google.script.host.closeDialog();
browser.msgbox('Access Granted', browser.buttons.OK)
}
else {
browser.msgbox('ALERT!!','!OOF!','Incorrect Password. Please retry', browser.buttons.OK);
}
}
function showWorking() {
document.getElementById('submitbutt').style.display="none";
document.getElementById('submitloader').style.display="block";
}
function handle(e){
if(e.keyCode === 13)
document.getElementById('submitbuttcontainer').click();
}
</script>
</html>
All I'm trying to do is get the form to submit when I hit enter and not blank out. I always hit enter to submit a form but in this case all it does is blank out the form and all I have is whiteness.
Here's the link for the complete source code (don't know if this will work because I'm in a school district):
https://script.google.com/a/bcsdschools.net/d/1_YUx4ZP3qEWVcFMc-MvfEYX2S34r7-b4M0iRlE_JQa81T3ZubN5OeISa/edit)
Problem
Hitting enter key results in form submission (which is explicitly forbidden in Apps Script due to its client-to-server communication implementation).
Solution 1 - handle inputs individually
Add preventDefault() to a keydown event if key is enter (btw, keypress event is deprecated, see reference on MDN, use the keydown / keyup instead):
var ENTER_CODE = 13;
function handle(e) {
if(e.keyCode === ENTER_CODE) {
e.preventDefault();
document.getElementById('submitbuttcontainer').click();
}
}
Solution 2 - handle form submit
You can listen for a submit event on your form instead and invoke preventDefault() as the only statement in event handler or handle form submission at the same time if you expect form to be submitted on enter key hit:
//assumption: form is initiated elsewhere in code;
form.addEventListener('submit', (event) => {
event.preventDefault();
//handle submission;
});
You can also prevent all forms from being submitted to make the setup flexible:
(() => {
const { forms } = document;
Object.values(forms).forEach(
form => form.addEventListener("submit", (e) => e.preventDefault())
);
})();
Or, alternatively, use event delegation and register one listener on the document since the event bubbles up:
document.addEventListener("submit", (e) => e.preventDefault());
Suggestion
Please, use addEventListener instead of on[event name here] attributes. This way is much more flexible and has the benefit of being concise and easy for others to read.
References
Handling forms in Apps Script guide
Why use addEventListener? MDN reference
I wanted to try to give you a complete answer, but I have to admit that I may know less about event handlers than you. But this seems to work for me.
aq4.html:
<html>
<head>
<script>
window.onload=function() {
preventFormSubmit1();
}
function preventFormSubmit1() {
console.log('preventFormSubmit1');
var form=document.forms['myForm'];
form.addEventListener('submit',function(e) {
e.preventDefault();
});
}
function handleFormSubmit(formObject) {
console.log('handleFormSubmit');
var first=document.forms['myForm']['first'].value;
var last=document.forms['myForm']['last'].value
var sheet=document.forms['myForm']['sheet'].value;
console.log('%s,%s,%s',first,last,sheet);
if(first.length>0 && last.length>0 && sheet.length>0) {
google.script.run
.withSuccessHandler(function(msg){
var div=document.getElementById('output');
div.innerHTML=msg;
var inputs=document.querySelectorAll('input[type=text]');
inputs[0].focus();
for(var i=0;i<inputs.length;i++) {
inputs[i].value='';
}
})
.processForm(formObject);
}else{
alert("Invalid or Incomplete Data");
}
}
console.log("MyCode");
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input type="text" name="first" /> First<br />
<input type="text" name="last" /> Last<br />
<select name="sheet">
<option value="Sheet1">Sheet1</option>
<option value="Sheet2">Sheet2</option>
</select> Sheet<br />
<input id="sub" type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
aq1.gs:
function processForm(formObject) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(formObject.sheet);
sh.appendRow([formObject.first,formObject.last]);
return Utilities.formatString('First: %s<br />Last: %s<br />Sheet: %s', formObject.first,formObject.last,formObject.sheet);
}
function runOne() {//This loads the dialog
var userInterface=HtmlService.createHtmlOutputFromFile('aq4').setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Form Example")
}

<form action="https://www.google.com/search" method="GET"> has to redirect to the website when I type a URL in the input field

I have a simple search input box in my webpage that has google search action to it.This is the code.
<div className="search-container">
<form action="https://www.google.com/search" method="GET">
<input type="search" id="search" name="q" placeholder="Search Google or type URL" />
<button className="icon" type="submit"><i className="small material-icons">search</i></button>
</form>
</div>
This is the image of search box
So if i type anything for example like apple, it searches google for apple and displays the content. But if I type a url like http://facebook.com, it again searches google and displays the search result for facebook.
But I need it to redirect to that particular website when I enter a url. If i enter http://facebook.com and press enter, It must redirect me to the facebook website and not to the google search results page for facebook.
Please help me out in this. Thanks in advance.
Effectively what you want here is for the one button to do two different things (search via google, or redirect to a URL). Because you want one element to do two different things, I would recommend using Javascript so that the page can decide which thing to do.
The following code will take in a string from an input box and either redirect if it starts with "HTTP://" or searches google if it doesn't:
<html>
<head>
<script>
function search(query){
if(query.slice(0, 7) == "http://"){
window.location.href = query
}
else{
window.location.href = "https://www.google.com/search?q=" + query
}
}
</script>
</head>
<body>
<label for="url">Enter a URL or search query</label>
<input type="text" name="search" id="search">
<button type="submit" onclick="search(document.getElementById('search').value)">search</button>
</body>
</html>
You can add JS to check whether the input value is a URL.
function go() {
const val = document.getElementById('input').value
window.open(
(isURL(val) ? '' :
'https://google.com/search?q=') + val,
'_blank')
}
function isURL(url) {
try {
new URL(url)
return true
} catch (e) {
return false
}
}
<input type="text" id="input" placeholder="Search Google or type URL" />
<button onclick="go()">Search</button>

Can't change / get value of input after being opened with FeatherLight?

I've met a weird behavior. I'm trying to get / set the value of an input textbox After FeatherLight lightbox is closed. I get "Undefined" when trying to fetch the value of the textbox (again, after it was opened and closed via Featherlight). You can see my source code here:
https://jsfiddle.net/hgyba4dg/
The only relevant part is the html code. try running the code on JSFiddle and see the input's value (the textbox's value). You'll see that you'll get "undefined" after closing the Featherlightbox. Here is the html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var storeData = null;
function openFeatherLight()
{
if (!storeData)
{
storeData = $.featherlight($('#MyDiv'), { 'persist' : true , 'beforeOpen' : sayHi , 'beforeClose' : sayBye, 'afterClose' : changeInputValueAfterClose });
}
else
{
storeData.open();
}
}
function sayHi()
{
alert('Value of textbox BEFORE opening FeatherLight LightBox Is: ' + $('#MyTextBox').val());
}
function sayBye()
{
alert('Value of textbox BEFORE CLOSING the FeatherLight LightBox Is: ' + $('#MyTextBox').val());
}
function changeInputValueAfterClose()
{
$('#MyTextBox').val("Bla");
alert('Current Value Of Input TextBox After Change is: ' + $('#MyTextBox').val());
alert('We get "Undefined". Why?');
}
</script>
</head>
<body>
<div id="Shit" style="display: none;">
<div id="MyDiv">
Text
<form id="MyForm">
<input type="text" value="Initial_Value_Set_By_Me_For_Testings" id="MyTextBox">
</form>
</div>
</div>
<input name="Button1" type="button" value="Open FeatherLight" class="AddToMenuButton" onclick="openFeatherLight();">
</body>
</html>
After the first time, the DOM elements remain detached (I open to reinsert it one day...). So $('#MyTextBox') won't work afterwards. Either keep a reference to it, or use storeData.$content.find('#MyTextBox')

Use code captcha in two forms

I have two forms on a page containing Google captcha code, but only one code works. Does anyone know if you can use the same code with the same key on two forms on the same page?,
Thks,
Yes, you can. But you have to explicitly render the widget as mentioned on the developer guide
you should use something like this on your front end(taken from the developer guide):
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : 'your_site_key'
});
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
I just wanted a HTML snipped which I can insert multiple times, each time displaying another captcha. Also, I did not want to take care for specific IDs assigned to the containers, which would be very annoying when multiple formulars still appearing on one page will be designed and rendered independently. Here is my solution.
<div class="g-recaptcha"></div>
<script type="text/javascript"><![CDATA[
function renderCaptchas() {
var captchaNodes = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < captchaNodes.length; i++) {
var captchaNode = captchaNodes[i];
if (!captchaNode.captchaRendered) {
captchaNode.captchaRendered = true;
grecaptcha.render(captchaNode, {"sitekey": "YOUR_SITE_KEY"});
}
}
}
]]></script>
<script src="https://www.google.com/recaptcha/api.js?onload=renderCaptchas&render=explicit" async="async" defer="defer"></script>

little 'x' in textfield input on the iphone in mobileSafari?

I have been looking everywhere for this without any luck. If you go to google.com on the iphone when you focus in on the search field a little 'x' appears all the way in the right and if you touch it it clears the current value of the field. Anybody know how to accomplish this?
I used the develop menu in Safari and changed the user agent to iPhone. Viewing the source on Google, it looks like they've set their html up like this:
<div class="gp2">
<input class="gp7" id="query" type="text" name="q" size="30" maxlength="2048" autocorrect="off" autocomplete="off" />
<a class="clear" id="clearQuery" href="#">
<img src="data:image/gif;base64,R0lGODlhAQABAID%2FAMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D" alt="" />
</a>
and are using this javascript:
function initClearQueryLink(query,clearQuery){
clearQuery.setAttribute("title","Clear");
clearQuery.addEventListener("mousedown",clearQueryBox,true);
query.addEventListener("keyup",_handleClearQueryLink,false)
}
function _handleClearQueryLink(){
var query=document.getElementById("query");
var clearQuery=document.getElementById("clearQuery");
if(clearQuery)
if(query.value.length>0){
clearQuery.style.display="inline";
clearQuery.style.visibility="visible"
} else{
clearQuery.style.display="none";
clearQuery.style.visibility="hidden"
}
}
function clearQueryBox(event){
var query=document.getElementById("query");
var clearQuery=document.getElementById("clearQuery");
query.value="";
clearQuery.style.display="none";
clearQuery.style.visibility="hidden";
hideSuggest();
if(event)event.preventDefault()
}
This is a special type of input developed by Apple and not approved by the W3C. If you use it, it works fine on browsers that don't recognize it.
<input type="search" name="q" />
There are other parameters, including domain name and search results so the user can use their search history. Google for how to use those.
The trick is to listen for/bind event on mousedown that way the click event never fires and your input element doesn't lose focus. As in the google example above.
A really good resource for iPhone web development is iphonewebdev.
However it seems like this particular feature is not part of Apple's API (at least from my research), rather a pure javascript / css implementation.
You can re-create it with something like this:
<script>
window.onload = function() {
var btn = document.getElementById("clear_input");
btn.onclick = function() {
var div = btn.parentNode;
var input = div.getElementsByTagName("input")[0];
input.value = "";
return false;
}
}
</script>
<div>
<input type="text" />X
</div>
You should style the X to be an image so that it blends inside the input. And of course I strongly recommend using a JavaScript framework if you can.
Jquery mobile provides this:
http://jquerymobile.com/test/docs/forms/search/
And this is my jQuery version, it hides it at the start, and if the user deletes what is typed it will remove the 'x'. Also when they have removed the text with the button it will hide the 'x' too.
html:
<input type="search" name="search" id="search" />
X
JavaScript:
$('.clear_input').hide();
$('#search').keyup(function() {
var search = $(this).val().replace(/^\s+|\s+$/g,"");
if (search.length >= 1) {
$('.clear_input').show();
} else {
$('.clear_input').hide();
}
$('.clear_input').click(function() {
$('#search').val('');
$('.clear_input').hide();
});
});
The JavaScript version is faster than the jQuery version of course.