Select all text only on first click - javascript

I'm using Dojo 1.6 and want to select all the text of a textbox only at the first click. I know I can use dojo.byId("id").select(); to select the whole text, but the problem is that you can't make a subselection of text anymore. I've provided a small code example to show the problem.
require(["dojo/parser", "dijit/form/TextBox"]);
require(["dojo/query", "dojo/on", "dojo/domReady!"], function(query, on) {
query("#firstname").on("click", function(evt) {
// this will not work because I want to select 1 or more characters
if (!dojo.byId("firstname").select())
dojo.byId("firstname").select();
});
});
And the fiddle: http://jsfiddle.net/3CLz9/
So the main problem is that I can't determine if one or more characters are selected.

You could use the dojo/on module's once() function. But I don't think that this is what you want. I suppose you want to select the text each time the input field gains focus. If you want this, you should be using the onFocus event, (so replace the "click" by "focus").
The only problem now is that after you select the text, the default event will move your cursor to the selected position and unselect your text (you will see it blink). To solve that you should also bind an mouseup event handler that cancels when you just gained focus. For example:
query("#firstname").on("focus", function(evt) {
this.select();
on.once(this, "mouseup", function(evt) {
evt.preventDefault();
});
});
I also updated your fiddle.
I just noticed that you're actually using a dijit/form/TextBox widget (didn't work on your JSFiddle so that's why I didn't notice it), but you can easily do this with the selectOnClick property. Add it to your data-dojo-props and it will work.
For example:
<input type="text" name="firstname" value="testing testing"
data-dojo-type="dijit/form/TextBox"
data-dojo-props="trim:true, propercase:true, selectOnClick: true" id="firstname" />
Here is your fiddle (with a working textbox widget). If you want to do the same thing for Dojo versions below 1.7, you can do that like described in this fiddle.

Related

problems with jquery Tree Traversal

(1) I've a scenario where there are some checkbox with a "Other" (user typed option) checkbox
(2) When clicking on the checkbox of "Other", a input field will come and cover the "Other" text.
(3) User can type at there and there is an "ok" button beside the checkbox.
(4) When user click the "Ok" button, input field will be gone and user typed text will come at the place of previous "Other" text. At the same time new "Other" fields should come after previous. Also previous "Other" shouldn't expand any more as it's not "Other" anymore(for example, it's now Black).
To make this, I've written jQuery like this:
$('.otherOption input[type="checkbox"]').click(function() {
$(this).closest('.otherOption').find('.box').toggle();
});
$('.ok').click(function() {
var value = $('.optionInput').val();
$('.box').hide();
$('.otherOption p').text(value);
$('.otherOption').removeClass('otherOption');
$(this).closest('.otherOption').append('<div class="block otherOption"><input type="checkbox" /> <p>Other</p><div class="box"><input type="text" value="" placeholder="Provide your option" class="optionInput" /><button class="ok">Ok</button></div></div>');
});
I think, I can write some script correctly. But, as I ain't good at jQuery, I can't write the jquery selector(.closest(),.parents(),.next() etc) that's why, my script is not working. So, please help me to make my script correct. Thanks in advance
My fiddle
Good start. A couple things to make this work the way you want.
You code $('.otherOption').removeClass('otherOption'); removes all instances of the otherOption class which is why your append isn't working.
If you removed the line mentioned above, you're appending the new checkbox inside the wrapper of the other checkbox which I can imagine isn't the desired result. I would imagine you want the new checkbox to come .after() the old otherOption box.
These being said remove this line:
$('.otherOption').removeClass('otherOption');
and change your $(this).closest('.otherOption')... to
$(this)
.closest('.otherOption')
.removeClass('otherOption')
.after('<div class="block otherOption"><input type="checkbox" /> <p>Other</p><div class="box"><input type="text" value="" placeholder="Provide your option" class="optionInput" /><button class="ok">Ok</button></div></div>');
A side note - cause you'll wonder later - your .click() function's won't work more than once. .click() binds to all matching objects on the page load. So any items added dynamically after page load will not work. Look into using jQuery's .on() method. This will ensure you're code works on all matching items no matter when they're added to the DOM.
Edit: One other thing, I noticed that when you repetitively added items, it always added the text from the first box b/c you are not removing the used text boxes. I've added $(this).closest('.box').remove(); to the end of the JS code to fix this issue.
Here's a working fiddle with jQuery's .on() implemented http://jsfiddle.net/a695jk2d/4/
Don't just copy and paste it, understand it.
It might make more sense to simply insert a new structure above your already existing "Other" option. Why replace it's text, and add a whole new 'other' option block? This version will insert a new option above the "Other" option. This way you also only need to bind to the element once as well.
$( '.ok' ).click(function () {
var value = $( '.optionInput' ).val();
$( '.optionInput' ).val('');
$( this ).parent().parent().find( '.box, p' ).toggle();
$( '.otherOption input[type="checkbox"]' ).attr( 'checked', false );
$( '#optionContainer' ).append(
'<div class="block"><input type="checkbox" /> <p>' + value + '</p></div>'
);
});
jsFiddle

React when Browser Text Input Changed through Mouse Action

I have a text input field and a checkbox. The checkbox must be disabled if and only if there is input in the text field. I have a solution that works great for most scenarios:
HTML:
<input type="text" id="search" />
<input type="checkbox" id="cb" />
<label for="cb">Enabled only if no search term</label>
jQuery:
$('#search').keyup(function (e) {
var enable = $(this).val() == 0;
if (enable) {
$('#cb').removeAttr('disabled');
} else {
$('#cb').attr('disabled', 'disabled');
}
});
See it live on jsFiddle.
This works when text is typed or removed using the keyboard, and when text is pasted using the keyboard.
It fails if the user pastes text using the right-click context menu, or if the user presses the little "X" that IE adds to the input field to allow the input field to be cleared.
Question
How can I improve the code so that it also works in those scenarios? Waiting for the textbox to lose focus would provide an inferior user experience.
The Real Time Validation jQuery Plugin solves this issue. However, it does not seem to work currently with delegated events.
Implementing this requires binding events to the keyup event, and a couple other events if you want to detect text changes on cut and paste. Even if you're a JavaScript god it's tedious to keeping writing this logic over and over again. Be smart and use the ZURB text change event plugin instead.
You can use the jquery change method:
http://jsfiddle.net/WDMCX/1/
$('#search').change(function() {
if( $(this).val() === '' ){
$('#cb').attr('disabled', 'disabled');
} else {
$('#cb').removeAttr('disabled');
}
});

html <input type="text" /> onchange event not working

I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the onchange event property to make it happen but it doesn't work. I still need to press the submit button to make it work. I read about AJAX and I am thinking to learn about this. Do I still need AJAX to make it work or is simple JavaScript enough? Please help.
index.php
<script type="text/javascript" src="javascript.js"> </script>
<form action="index.php" method="get">
Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
<input type="submit" value="Compute" />
</form>
javascript.js
function checkInput(textbox) {
var textInput = document.getElementById(textbox).value;
alert(textInput);
}
onchange is only triggered when the control is blurred. Try onkeypress instead.
Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.
For static and dynamic inputs:
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
For static inputs only:
$('.my-class').on('input', function(){
alert('Input changed');
});
JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/
HTML5 defines an oninput event to catch all direct changes. it works for me.
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc
Read more about the change event here
Read more about the input event here
use following events instead of "onchange"
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
Firstly, what 'doesn't work'? Do you not see the alert?
Also, Your code could be simplified to this
<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />
function checkInput(obj) {
alert(obj.value);
}
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
A couple of comments that IMO are important:
input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.
The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input
The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)
Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...
jQuery has nothing to do with this. This is all in HTML standard.
If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.
My two cents.
onkeyup worked for me. onkeypress doesn't trigger when pressing back space.
It is better to use onchange(event) with <select>.
With <input> you can use below event:
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
when we use onchange while you are typing in input field – there’s no event. But when you move the focus somewhere else, for instance, click on a button – there will be a change event
you can use oninput
The oninput event triggers every time after a value is modified by the user.Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.
<input type="text" id="input"> oninput: <span id="result"></span>
<script>
input.oninput = function() {
console.log(input.value);
};
</script>
If we want to handle every modification of an <input> then this event is the best choice.
I have been facing the same issue until I figured out how to do it. You can utilize a React hook, useEffect, to write a JS function that will trigger after React rendering.
useEffect(()=>{
document.title='fix onChange with onkeyup';
const box = document.getElementById('changeBox');
box.onkeyup = function () {
console.log(box.value);
}
},[]);
Note onchange is not fired when the value of an input is changed. It is only changed when the input’s value is changed and then the input is blurred. What you’ll need to do is capture the keypress event when fired in the given input and that's why we have used onkeyup menthod.
In the functional component where you have the <Input/> for the <form/>write this
<form onSubmit={handleLogin} method='POST'>
<input
aria-label= 'Enter Email Address'
type='text'
placeholder='Email Address'
className='text-sm text-gray-base w-full mr-3 py-5 px-4 h-2 border border-gray-primary rounded mb-2'
id='changeBox'
/>
</form>
Resulting Image :
Console Image
try onpropertychange.
it only works for IE.

Dojo: dojo onblur events

I have a form setup with dojo 1.5. I am using a dijit.form.ComboBox and a dijit.form.TextBox
The Combobox has values like "car","bike","motorcycle" and the textbox is meant to be an adjective to the Combobox.
So it doesn't matter what is in the Combobox but if the ComboBox does have a value then something MUST be filled in the TextBox. Optionally, if nothing is in the ComboBox, then nothing can be in the TextBox and that is just fine. In fact if something isn't in the Combobox then nothing MUST be in the text box.
In regular coding I would just use an onBlur event on the text box to go to a function that checks to see if the ComboBox has a value. I see in dojo that this doesn't work... Code example is below...
Vehicle:
<input dojoType="dijit.form.ComboBox"
store="xvarStore"
value=""
searchAttr="name"
name="vehicle_1"
id="vehicle_1"
/>
Descriptor:
<input type="text"
dojoType="dijit.form.TextBox"
value=""
class=lighttext
style="width:350px;height:19px"
id="filter_value_1"
name="filter_value_1"
/>
My initial attempt was to add an onBlur within the Descriptor's <input> tag but discovered that that doesn't work.
How does Dojo handle this? Is it via a dojo.connect parameter? Even though in the example above the combobox has an id of "vehicle_1" and the text box has an id of "filter_value_1", there can be numerous comboboxes and textboxes numbering sequentially upward. (vehicle_2, vehicle_3, etc)
Any advice or links to resources would be greatly appreciated.
To add the onBlur event you should use dojo.connect():
dojo.connect(dojo.byId("vehicle_1"), "onBlur", function() { /* do something */ });
If you have multiple inputs that you need to connect this to, consider adding a custom class for those that need to blur and using dojo.query to connect to all of them:
Vehicle:
<input dojoType="dijit.form.ComboBox"
store="xvarStore"
class="blurEvent"
value=""
searchAttr="name"
name="vehicle_1"
id="vehicle_1"
/>
dojo.query(".blurEvent").forEach(function(node, index, arr) {
dojo.connect(node, "onBlur", function() { /* do something */ });
});
In the function that is passed to dojo.connect you could add in some code to strip out the number on the end and use it to reference each filter_value_* input for validation.
dojo.connect()
Combobox documention
onBlur seems to work just fine for me, even in the HTML-declared widgets. Here's a very rudimentary example:
http://jsfiddle.net/kfranqueiro/BWT4U/
(Have firebug/webkit inspector/IE8 dev tools open to see console.log messages.)
However, for a more ideal solution to this, you might also be interested in some other widgets...
http://dojotoolkit.org/reference-guide/dijit/form/ValidationTextbox.html
http://dojotoolkit.org/reference-guide/dijit/form/Form.html
Hopefully this can get you started.

Remove disabled attribute onClick of disabled form field

I have a form field that starts out disabled and has an onClick to enable it. The onClick doesn't fire (at least in FF) nor does a simple alert(1);.
The hacky version is to show a fake form field in its place that "looks" like it's disabled (grayed out style) and onClick, hide it and show the correct field enabled, but that's ugly.
Example Code
This works:
<input type="text" id="date_end" value="blah" onClick="this.disabled=true;">
This works:
<label for="date_end_off" onClick="document.getElementById('date_end').disabled=false">Test</label>
<input type="text" id="date_end" value="blah" onClick="alert(1);" disabled>
This fails:
<input type="text" id="date_end" value="blah" onClick="alert(1);" disabled>
This fails:
<input type="text" id="date_end" value="blah" onClick="document.getElementById('date_end').disabled=false" disabled>
I came across this thread in another forum so I assume I'll have to go about it a different way.
http://www.webdeveloper.com/forum/showthread.php?t=186057
Firefox, and perhaps other browsers,
disable DOM events on form fields that
are disabled. Any event that starts at
the disabled form field is completely
canceled and does not propagate up the
DOM tree. Correct me if I'm wrong, but
if you click on the disabled button,
the source of the event is the
disabled button and the click event is
completely wiped out. The browser
literally doesn't know the button got
clicked, nor does it pass the click
event on. It's as if you are clicking
on a black hole on the web page.
Work around:
Style the date fields to look as if
they are disabled.
Make a hidden "use_date" form field
with a bit value to determine
whether to use the date fields during processing.
Add new function to onClick of the date fields which will
change the style class to appear
enabled and set the "use_date" value
to 1.
Use readonly instead of disabled
For checkboxes at least, this makes them look disabled but behave normally (tested on Google Chrome). You'll have to catch the click and prevent the default action of the event as appropriate.
Using jQuery, I attach an event handler to the parents of my input controls.
<script type="text/javascript">
$(function() {
// disable all the input boxes
$(".input").attr("disabled", true);
// add handler to re-enable input boxes on click
$("td:has(.input)").click(function() {
$(".input", this).removeAttr("disabled");
});
});
</script>
All of my input controls have the class "input" and they exist in their own table cells. If you at least wrapped your input tags in a div, then this should work without a table as well.
Citing Quirksmode.org:
"A click event on a disabled form field does not fire events in Firefox and Safari. Opera fires the mousedown and mouseup events, but not the click event. IE fires mousedown and mouseup, but not click, on the form. All these implementations are considered correct."
Quirksmode's compatibility table is great to find out more about such problems.
I recently had a very similar problem and solved it by placing the input in a div and moving the onClick to the div.
<div onClick="myEnableFunction('date_end');">
<input type="text" id="date_end" value="blah" disabled>
</div>
Enabling a disabled element on click kind of defeats the purpose of disabling, don't you think? If you really want the behavior you're describing, just style it 'disabled' and remove those styles on click.
Don't implement the logic of the onClick event in the onClick's value of the input field. That's probably why it's not working in Firefox. Instead define a function as the onClick's value. For example:
<input type="text" id="date_end" value="blah" onClick="doSomething()" disabled>
<script type="text/javascript">
function doSomething()
{
alert("button pressed");
}
</script>
It will also be worth looking into JQuery. You can use it to add or remove attributes from elements and all kinds of other stuff. For instance you can remove the disabled from the the input field by writing a function like this:
<script type="text/javascript">
function doSomething()
{
alert("button pressed");
$("#date_end").removeAttr('disabled'); //removes the disabled attribut from the
//element whose id is 'date_end'
}
</script>
OR you can add it as follows:
$("#date_end").attr('disabled','true');
The Jquery site is here
You can add a div over the input that is disabled: check it out
<div onclick="javascript:document.forma.demo1.disabled=false;" style="border:0px solid black; padding:00px;">
<input type=text name="demo1" disabled style="width:30;">
</div>
In order to enable a disabled element on the client side, lets say in response to a checkbox checked or something, I ended up having to use a combination of JS and jQuery, see below:
//enable the yes & no RB
function enable()
{
var RBNo = "rbnBusinessType";
var RBYes = "rbnBusinessType";
//jQuery approach to remove disabled from containing spans
$("#" + RBYes).parent().removeAttr('disabled');
$("#" + RBNo).parent().removeAttr('disabled');
//enable yes and no RBs
document.getElementById(RBYes).disabled = false;
document.getElementById(RBNo).disabled = false;
}
After postback then, you'll need to access the request like the following in order to get at the values of your client side enabled elements:
this._Organization.BusinessTypeHUbZoneSmall = Request.Params["rbnBusinessTypeHUbZoneSmall"] == rbnBusinessTypeHUbZoneSmallYes.ID;
Inspiration taken from:
https://stackoverflow.com/questions/6995738/asp-javascript-radiobutton-enable-disable-not-included-in-postback-ajax for more information
If you simply want to prevent the user from typing data in your field, but instead want the field to populate on an event, my hack solution was to not disable the input field at all, but instead after running my onclick or onfocus functions, to call blur() so the user can not edit the field.

Categories