I'm not good at scripting and did the following by some trial and error. It seems to be working, but I wonder if it's the right way to reset the text field if there's a value:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Reset</title>
<style>
</style>
</head>
<body>
<input type="text" id="box">
<input type="button" value="Reset" onclick="zero();">
<script>
var box = document.getElementById('box');
function zero() {
if (box.value && confirm('Sure?')) {
box.value = '';
alert('Done!');
}
}
</script>
</body>
</html>
Let me outline some problems in your code - you stated you are looking for the right way.
You are using the outdated inline event model (putting Javascript into HTML attributes), which has several drawbacks. You said you are not good in scripting. If you want to learn it, you could learn it the right way, you have nothing to lose. I suggest using addEventListener.
You could make your function reusable. In its current state, it is only useful to reset a very specific input element, and this is not really what functions are for.
I created a quick little example, for illustration.
In the HTML I removed the inline onclick. I added an id for the button to be able to reference it, and added a data-reset attribute (HTML5 data- attributes), in which we can store the id for the element the button will reset:
<input type="text" id="box">
<input id="reset-button" type="button" value="Reset" data-reset="box" />
And here comes the new JS, commented:
//get the reset button from the DOM
var resetButton = document.getElementById('reset-button');
//add a click event listener to it, our reset function will handle the event
resetButton.addEventListener('click', reset);
//and the reset function
function reset() {
//`this` refers to the clicked button - we query the data- attribute
var inputId = this.getAttribute('data-reset');
//get the right input element
var input = document.getElementById(inputId);
//and then what you already had
if (input.value && confirm('Sure?')) {
input.value = '';
alert('Done!');
}
}
Working demo
Now the code uses the modern event model, and the function is reusable on any other button or for a different text field - you just have to change the data- attribute.
I don't say this is the very very best way, but I wanted to keep it easy and understandable.
function zero() {
var box = document.getElementById('box');
if (box.value && confirm('Sure?')) {
box.value = '';
alert('Done!');
}
}
Your code is fine, with the only exception of moving the box variable into the function scope (instead of global scope) if you only need to reference it there (better memory management as it will be collected as garbage when the function is done executing).
You are getting the input value outside of the function which is wrong.
function zero() {
var box = document.getElementById('box');
if (box.value != ""){
if(confirm('Sure?')){
box.value = '';
alert('Done!');
}
}
}
Demo
Related
I have several input fields in line that acts like a crossword answer line:
Each square has its own input field. The reason for this is amongst other things that sometimes a square can be pre-populated. Now, on desktop browser the cursor jumps to the next input field whenever a char is entered. That works really well using something like:
$(this).next('input').focus();
But the problem on mobile safari (we test on ios) is that I don’t know how to automatically "jump" to the next input field programatically. The user can do it via the the "next" button, but is there a way to do this automatically?
I know that the focus() trigger has some limitations on ios, but I’ve also seen some workaround using synthesized clicks etc.
I found a workaround that might work for you.
Apparently IOS/Safari only "accepts" the focus when inside a touch event handler. I triggered a touch event and inserted the .focus() inside it. I tried this on my iPhone3S and iPhone5S with Safari and it works:
var focused = $('input:first'); //this is just to have a starting point
$('button').on('click', function () { // trigger touch on element to set focus
focused.next('input').trigger('touchstart'); // trigger touchstart
});
$('input').on('touchstart', function () {
$(this).focus(); // inside this function the focus works
focused = $(this); // to point to currently focused
});
Demo here
(press next button in demo)
Programmatically moving to the next input field in a mobile browser without dismissing the keyboard appears to be impossible. (This is terrible design, but it's what we have to work with.) However, a clever hack is to swap the input element positions, values, and attributes with Javascript so that it looks like you are moving to the next field when in fact you are still focused on the same element. Here is code for a jQuery plug-in that swaps the id, name, and value. You can adapt it to swap other attributes as necessary. Also be sure to fix up any registered event handlers.
$.fn.fakeFocusNextInput = function() {
var sel = this;
var nextel = sel.next();
var nextval = nextel.val();
var nextid = nextel.attr('id');
var nextname = nextel.attr('name');
nextel.val(sel.val());
nextel.attr('id', sel.attr('id'));
nextel.attr('name', sel.attr('name'));
sel.val(nextval);
sel.attr('id', nextid);
sel.attr('name', nextname);
// Need to remove nextel and not sel to retain focus on sel
nextel.remove();
sel.before(nextel);
// Could also return 'this' depending on how you you want the
// plug-in to work
return nextel;
};
Demo here: http://jsfiddle.net/EbU6a/194/
UIWebview has the property keyboardDisplayRequiresUserAction
When this property is set to true, the user must explicitly tap the elements in the web view to display the keyboard (or other relevant input view) for that element. When set to false, a focus event on an element causes the input view to be displayed and associated with that element automatically.
https://developer.apple.com/documentation/uikit/uiwebview/1617967-keyboarddisplayrequiresuseractio
I hope this is what you are looking for-
$(document).ready(function() {
$('input:first').focus(); //focus first input element
$('input').on('keyup', function(e) {
if(e.keyCode == 8) { //check if backspace is pressed
$(this).prev('input').focus();
return;
}
if($(this).val().length >= 1) { //for e.g. you are entering pin
if ($(this).hasClass("last")) {
alert("done");
return;
}
$(this).next('input').focus();
}
});
$('input').on('focus', function() {
if(!$(this).prev('input').val()){
$(this).prev('input').focus();
}
});
});
check code here-
https://jsbin.com/soqubal/3/edit?html,output
Add this line in your config file in ios section
preference name="KeyboardDisplayRequiresUserAction" value="false"
I encounter the same problem on safari ios. on login page, I programmatically focus on next input field after user input one sms code.
I trigger the auto focus on input change event. I fixed the problem by adding a delay.
For details, see the code below
<InputItem
value={item}
type='number'
maxLength={1}
ref={el => this[`focusInstRef${index}`] = el}
onChange={(value) => {
value&&index !== 5 && setTimeout(() => {this[`focusInstRef${index + 1}`].focus()}, 5);
vAppStore.setSmsCodeArr(value, index);}
}
/>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#hidebox {position:absolute; border: none; background:transparent;padding:1px;}
#hidebox:focus{outline: 0;}
</style>
</head>
<body>
<input type="text" maxlength="1" onkeyup="keyUp(this)" onkeydown="keyDown(this)" size="2" id="hidebox" at="1">
<input type="text" maxlength="1" size="2" id="mFirst" at="1" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mSecond" at="2" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mThird" at="3" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mFourth" at="4" onfocus="onFocus(this)">
</li>
<script type="text/javascript">
window.onload = function() {
document.getElementById("mFirst").focus();
}
var array = ["mFirst","mSecond","mThird","mFourth"];
function keyUp(e) {
var curId = array[Number(e.getAttribute("at"))-1];
var nextId = array[Number(e.getAttribute("at"))];
var curval= e.value;
var letters = /^[0-9a-zA-Z]+$/;
if(e.value.match(letters)){
document.getElementById(curId).value = curval;
if(e.getAttribute("at") <= 3){
var nextPos = document.getElementById(nextId).offsetLeft;
e.setAttribute("at",Number(e.getAttribute("at"))+1);
e.style.left = nextPos+"px";
}
e.value = ""
}else {
e.value = "";
}
}
function keyDown(e) {
var curId = array[Number(e.getAttribute("at"))-1];
document.getElementById(curId).value = "";
}
function onFocus(e) {
document.getElementById("hidebox").focus();
document.getElementById("hidebox").setAttribute("at",Number(e.getAttribute("at")));
document.getElementById("hidebox").style.left = e.offsetLeft+"px";
document.getElementById("hidebox").style.top = e.offsetTop+"px";
}
</script>
</body>
</html>
How can i remove the style class applied to a textbox on the click event? I'm calling the textbox element using getElementsByName(). Here's my code:
<input id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
function clearText(element)
{
id = element.getAttribute("id");
var textElement = document.getElementById(id);
textElement.value = "";
var element = document.getElementsByName("popUpText");
var count = 0;
for (count = 0; count < 2; count++) {
var id = element.item(count);
id.classname = "";
}
}
In the above script, im not getting the id in the variable id. Right now the values are like "#inputTextBoxName". Please help.
you can use removeClass();
you can manege your styling using attr();
exp:
$("#yourid").attr("style","float: right");
or remove class using
$("#yourid").removeClass("yourClass");
It is case sensitive so
id.className = '';
If you're trying to remove the class from the textbox when you click on the textbox itself, that code is far, far longer than it needs to be.
HTML:
<input type="text" id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
Javascript:
<script>
function clearText(element) {
element.className = '';
element.value = '';
}
</script>
That said, inline event handlers (ie. declaring an onclick attribute on your HTML element) are a bad practice to get into.
Also, if you pass in a reference to an element, get its id, then call document.getElementById() with said id, you end up with two references to the same element. Yes, it should work, but totally pointless.
This is my jsfiddle(http://jsfiddle.net/mZGsp/). I was trying to answer a question here but my code won't work. Here is the code:
JS
var stateOfClick = null;
function initiateLine(){
document.getElementById('test').innerHtml = "Started";
}
function endLine(){
document.getElementById('test').innerHtml = "Line Ended";
}
function createLines(){
if(!stateOfClick) {
initiateLine();
stateOfClick = 1;
} else {
endLine();
}
}
HTML
<body>
<input type="text" id="test" onclick="createlines()">
</body>
A couple of things,
change createlines() to createLines (camel-case).
change <element>.innerHtml to <element>.value
Inside JSFiddle, don't wrap your code inside a function, as then createLines won't be global which it needs to be for the onclick to work.
Here's a working example.
Not even this simple example will work on jsFiddle. You need to attach the event listener with JavaScript:
document.getElementById("someElement").onclick = function() {
//Do stuff
}
For input element you must use the value attribute not the innerHTML field.
function initiateLine(){
document.getElementById('test').value = "Started";
}
also you've misspelled the innerHTML function (though not the primary problem). innerHTML is used for html elements that can contain other elements such as a div containg a p element. Input and option elements all have a value attribute that can be used to extract or set their values.
and thanks for looking.
Currently I am implementing code from this example. In my aspx file, I have Label1 and Textbox1 defined. In my aspx.cs file, I am setting the Label1.Text property to a random string in the Page_Load method.
In the .js file I have included, I have:
var Label1, TextBox1;
Sys.Application.add_init(AppInit);
function AppInit(sender) {
Label1 = $get('Label1');
TextBox1 = $get('TextBox1');
$addHandler(Label1, "click", Label1_Click);
$addHandler(TextBox1, "blur", TextBox1_Blur);
$addHandler(TextBox1, "keydown", TextBox1_KeyDown);
}
Now, I want to add more labels (and corresponding textboxes), but I do not want the overhead of defining separate handlers for each of the additional events, i.e. I want to avoid this:
$addHandler(Label1, "click", Label1_Click);
$addHandler(TextBox1, "blur", TextBox1_Blur);
$addHandler(TextBox1, "keydown", TextBox1_KeyDown);
$addHandler(Label2, "click", Label2_Click);
$addHandler(TextBox2, "blur", TextBox2_Blur);
$addHandler(TextBox2, "keydown", TextBox2_KeyDown);
...
How can I pass a parameter to the handler that will identify the sender accurately, and have the handler use 'this' or something. Also of note, I want to be able to identify the index of the Label (1,2,3...) because I have to edit the corresponding textbox as well. FOr instance, the current implementation of Label1_Click looks like this:
function Label1_Click() {
TextBox1.value = Label1.innerHTML;
Label1.style.display = 'none';
TextBox1.style.display = '';
TextBox1.focus();
TextBox1.select();
}
Thanks, you guys.
Well, $addHandlers can help speed up the process of adding handlers... also, in JS you can attach miscellaneous data to objects by doing: Label1["somenewproperty"] = value; and so you can attach certain attributes and check in the event handlers... that does take up resources though, so be careful how much you do this...
On some level, how is JS supposed to know the objects you want to listen to and what order the objects are in, to reduce the amount of code? Maybe storing an array of textboxes and labels, and referring to those objects by index, but on some level, you can't get away from certain plumbing code.
HTH.
You can try creating a delegate. For example with your labels:
function AppInit(sender) {
$addHandler(Label1, "click", Function.createDelegate(this, LabelClick());
$addHandler(Label2, "click", Function.createDelegate(this, LabelClick());
}
function LabelClick(sender)
{
/..
}
I know this is an old question but yesterday I faced this very same problem and here is the solution I came of with.
I don't like it a lot but haven't found an easier way: I use a custom CssClass for every label I want to be linked with a textbox by this method (and the same for the textbox).
Then I iterate them and attach the corresponding handler depending on if it is a label or a button.
var labels;
var texts;
Sys.Application.add_init(AppInit);
function AppInit(sender) {
labels = document.getElementsByClassName('lblDynamic');
texts = document.getElementsByClassName('txtDynamic');
for (i = 0; i < labels.length; i++)
{
$addHandler(labels[i], "click", Label1_Click);
}
for (i = 0; i < texts.length; i++) {
$addHandler(texts[i], "blur", TextBox1_Blur);
$addHandler(texts[i], "keydown", TextBox1_KeyDown);
}
}
The next step is to access the generic control inside the method handler. This is quite easy with the this reference. Example:
function TextBox1_KeyDown(event) {
if (event.keyCode == 13) {
event.preventDefault();
this.blur();
}
}
But there is a problem here: How do I know that a certain label pairs with a certain textbox? I use a very similar id for both controls. ASP will add it's viewstate weird nomenclature after rendering the page so I need to use very dirty tricks to get rid of the extra text. Then I iterate the textbox controls and if one matches the label on the handled event then I can work with them like in the example you posted:
function Label1_Click()
{
var offset = this.id.indexOf('lbl') + 3;
for (j = 0; j < texts.length; j++)
{
if (texts[j].id.substring(offset) == this.id.substring(offset))
{
texts[j].value = this.innerHTML;
this.style.display = 'none';
texts[j].style.display = '';
texts[j].focus();
}
}
}
In this case my label and textbox are declared this way. Note the very similar nomenclature:
<asp:Label runat="server" CssClass="lblDynamic" ID="lblExerciseName">My Text</asp:Label>
<asp:TextBox runat="server" CssClass="txtDynamic" ID="txtExerciseName" Style="display: none;" />
Hope it helps :)
there are many ways, but this one works perfectly in any browser and you don't need a library.
I append an onclick handler to every input on this page and give it 2 parameters, that I get from a 2-dimensional array. I used a closure to make sure the handler still has access to the given parameters. I also made me a global object (p from page), so I don't clutter the global namespace with variables.
<!DOCTYPE html>
<html>
<head>
<script>
var p = {
onload: function() {
var btns = document.getElementsByTagName("input");
var parameters = [["btn1 p1", "btn1 p2"], ["btn2 p1", "btn2 p2"]];
for(var i = 0, ceiling = btns.length; i < ceiling; i++) {
btns[i].onclick = function(par1, par2) {
return function() {
p.btnOnclick(par1, par2);
};
}(parameters[i][0], parameters[i][1]);
}
},
btnOnclick: function(par1, par2) {
alert("par1: " + par1 + " | par2: " + par2);
}
};
</script>
</head>
<body onload="p.onload()">
<input type="button" value="button1"/>
<input type="button" value="button2"/>
</body>
</html>
i would like to replicate that you see a regular input text and when you click it changes into textarea.
is this a hidden layer or is it actually changing the input to textarea? how to do it?
I do believe it's always a textarea and on focus they just change the height of the textarea.
Edit: yes, it is. They use scripting to do everything with a textarea, there is no input field.
<textarea onfocus='CSS.addClass("c4b900e3aebfdd6a671453", "UIComposer_STATE_INPUT_FOCUSED");CSS.removeClass("c4b900e3aebfdd6a671453_buttons", "hidden_elem");window.UIComposer && UIComposer.focusInstance("c4b900e3aebfdd6a671453");' id="c4b900e3aebfdd6a671453_input" class="UIComposer_TextArea DOMControl_placeholder" name="status" title="What's on your mind?" placeholder="What's on your mind?">
What's on your mind?
</textarea>
One method that I found was to have a text area that begins with a smaller width and height and then to dynamically resize it.
function sz(t) {
a = t.value.split('\n');
b=1;
for (x=0;x < a.length; x++) {
if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
}
b+= a.length;
if (b > t.rows) t.rows = b;
}
then you would call your function with an onclick event
onclick="function sz(this)"
I found this here
Fellgall Javascript
One problem that he does mention is that this only functions on browsers that support it.
You can combine the jQuery widget you can find here with some coding
Example:
<div id="myform">
<form>
<textarea></textarea>
<button type="submit" style="display:none;">Post</button>
</form>
</div>
<script>
$(document).ready(function(){
var widget = $('#myform textarea');
var button = $('#myform button');
var tarea = widget[0];
// turn the textarea into an expandable one
widget.expandingTextArea();
var nullArea = true;
tarea.value = "What's on your mind?";
widget.focus(function() {
button.css('display', 'block');
if (nullArea) {
tarea.value = "";
nullArea = false;
}
});
widget.blur(function() {
if ($.trim(tarea.value) == "") {
tarea.value = "What's on your mind?";
button.css('display', 'none');
nullArea = true;
}
});
});
</script>
This code will hide by default the post button and will show it only when the textarea is focused or when you already have written something into it (you may want to hide/show a div instead or anything you want).
If jQuery is an option for you at all, there's a jQuery plugin that does just this called Jeditable.
Check out the demos here.
One way to do this is to code a dynamic textarea. This article explains how to do it: http://www.felgall.com/jstip45.htm
Another way to do it is to change the type of the object. Let's say you place your input text in a div tag (its ID being "commentBox". The code would then be:
//when you click on the textbox
function makeTextArea()
{
document.forms[0].getElementById("commentBox").innerHTML = "<textarea id=\"comments\" onBlur=\"backToTextBox()\"></textarea>";
document.forms[0].getElementById("comments").focus();
}
//when you click outside of the textarea
function backToTextBox()
{
document.forms[0].getElementById("commentBox").innerHTML = "<input type=\"text\" id=\"comments\" onFocus=\"makeTextArea()\"/>";
}