Why doesn't this search box select all text on click? - javascript

You can see the search box in question at: http://www.trailbehind.com. If the user tries to search twice, they have to press backspace a bunch to clear the text, but I'd like to select all text on double click, which inputs should do by default. Why doesn't mind?
When the users first clicks, I clear the input as follows:
input.onclick = clearInitialValue;
function clearInitialValue() {
this.value = "";
this.onclick = 'return True';
this.style.color = "black";
}
Another thing you might need to know to help me solve this riddle is that I used the input to instantiate a YUI autocomplete: http://developer.yahoo.com/yui/autocomplete/, but I can't find anything in the docs that explains why double-clicking the input to select text wouldn't work.

keep in mind that you can only have one method for each javascript event, so, in your example you are assinging the onclick event, make sure you do not do it again.
to have more you need to use an event listener.
var oDiv = document.getElementById('thediv');
oDiv.addEventListener('click', function (e) {
// your method here
}, true);
or simple
oDiv.addEventListener('click', clearInitialValue, true);
you metion that you are using YUI, so the code will be something like:
YAHOO.util.Event.on(oDiv, "click", clearInitialValue);
not that answers your question directly, but keep in mind when dealing with javascript events.
to answer your question, your code runs great... check out the code running at JSBIN
you can add a /edit to the url in order to edit it.

Instead of your
this.onclick = 'return True';
try
this.onclick = 'this.select(); return true';
This will select the text in the box.
Consider doing this on focus, instead of click.
If that isn't behaving like you'd like, trying turning off the YUI autocomplete, to see if that is interferring. I've seen that.
If that doesn't do it, simplify more by implementing it on a clean page, with no other JS, before sticking it into the google map.
Hope this helps.

i see one thing that could be a problem, you have
this.onclick = 'return True';
try
this.onclick = 'return true';
javascript is case sensitive.

Related

Javascript click event on anchor not working

I was trying to call the click event when hitting spacebar on keyboard on an anchor like so.
$("a").on("keypress", function (e) {
if (e.which === 32) {
$(this).click();
e.preventDefault();
}
}
This does not work however. I finally figured out a fix but I don't understand why it works. The simple fix was changing $(this).click() to $(this)[0].click()
What is the [0] doing and how is it making the click event work on the anchor?
Note: I also tried $(this).trigger("click") with no luck either.
See Roman Starkov's answer in the following link:
Jquery how to trigger click event on href element
The native DOM method does the right thing:
$('.cssbuttongo')[0].click();
^
Important!
This works regardless of whether the href is a URL, a fragment (e.g.
#blah) or even a javascript:.
Note that this calls the DOM click method instead of the jQuery click
method (which is very incomplete and completely ignores href).
So basically when you use the indexer you'll access the DOM's native click method instead of the jQuery implementation which does not work for links.
I wanted to mark this topic as duplicated but first I linked a wrong topic so I retracted the flag and now I cannot mark it again. So if someone has the power feel free to mark it as the duplicate of the linked topic. And if this answer helped upvote Roman Starkov's original answer in the link, he deserves it.
I didn't understanda exactly the scenario but that works for me, please try this:
$('a').click(function() {
alert('click...!');
});
//press enter on text area..
$('a').keypress(function(e) {
var key = e.which;
console.log('checking press key: ' + key)
if (key == 32) // the enter key code
{
$('a').click();
}
});
Feel free to rearrange...hope it helps!

How to Capture changing value of textbox

I have a webpage with a small survey. I want to pre populate some of the answers based on user inputs to previous question.
In the below code, if value of id QR~QID3 depends upon value of QID1_Total. However after the page loaded and even if the condition is met the textbox is not populated with correct value.
.addOnload(function()
{
if(document.getElementById("QID1_Total").value>15) {
document.getElementById("QR~QID3").value = "Good";
}
else{
document.getElementById("QR~QID3").value = "Average";
}
});
$("#QID1_Total").on("input", function() {
//statements goes here
});
use of on("input" will track every inputting event, include drop and paste.
know more about onInput : https://mathiasbynens.be/notes/oninput
Here is an Fiddle Example to know how trigger works :
https://jsfiddle.net/5sotpa63/
An Assumption
Let Us Say you are using a function, which holds this statement show Good and Average according to users Input.
var targetElem = document.getElementById("QID1_Total");
var showComment = (targetElem,value>15) ? "Good" : "Average";
document.getElementById("QR~QID3").value = showComment;
Above code is the shorter method of your own statement mentioned in your question.
Now on Change of the target QR~QID3 you need to load some content. you utilize the below code as follows.
$("#QR~QID3").on("input", function() {
//your next question loading statements goes here,
//statements to proceed when you show some comment Good or Average
}).trigger("input");
Hope! this could be helpful.
$('#QID1_Total').keydown(function () {
//ur code
});
as the mouse key is pressed in the input field the function is called
You need to add an event listener to the "QID1_Total" element.
If you want to run the check while the user changes the input, i.e. after each keypress use the oninput event.
If you want to run the check after the user has completed the input, use the onchange event. The onchange event will only fire after the input loses focus.
You can bind the event listeners by using the addEventListener() function like this:
document.getElementById("QID1_Total").addEventListener("input", function(){
//Code goes here
});
Here is a JSFiddle showing both methods.
You also have to use the parseInt() function on the textbox values before you can perform mathematical functions with them.

How to call a function when default browser autocomplete list item selected [duplicate]

I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.

Show alert when focusout, only once

I'm having a little problem with my script below. I'm trying to create a script where you can write some text in an input field, and when you have typed some text, you will get an alert when focus-out. The alert should only show, if the input contain text.
But the problem is, that if you're trying to write some text, delete it and then focus-out of the input, the alert do not show next time, when you actually have written something and then focus-out.
Right now, the alert function always will "disappear" when focus out, no matter if you have written any thing or not.
I have tried to add a var already_alert_me_once = true before the alert, and then put everything inside an: if(already_alert_me_once == false), but that didn't do the trick.
I have also tried to change $('#title').focusout(function() with $('#title').one('focusout', function() which almost did the trick.
Here is my current script:
// When focus on title
$('#title').focus(function () {
// Check if empty
if (!$(this).val()) {
$('#title').one('focusout', function () {
if ($(this).val()) {
alert("YEP");
}
});
}
});
..and Here's a Fiddle
So my question is; How to I do so the alert only appears when you have written something, and after that never again (unless you reload the page).
Hope you can understand what I mean.
Thanks - TheYaXxE
You can unbind the focus using:
$('#title').unbind('focus');
Working Fiddle
pretty much the easiest solution, no need for .one or focus events :)
$('#title').blur(function() {
if( $(this).val() ) {
alert('!!');
$(this).unbind('blur');
}
});
http://jsfiddle.net/T7tFd/5/
instead of putting the variable "already_alert_me_once" inside the function, make it a global variable. that way the scope will be maintained. you could also add an attribute to the #title that indicates that it has already been clicked, then check to see if that attribute exists before executing the code.

JQuery - What method can I use to get this code to run without clicking

Ok this example code contains a button. Forget about the button, it does not exist, cannot be referenced and cannot be edited.
The buttons dont exist in this example - they merely represent another process. However the fields still need to be updated from values. Sorry I couldn't explain it better.
Answer:
http://jsfiddle.net/piezack/X8D4M/56/
If you want the event to fire whenever the text inside the box changes, then I think you're best off using jquery's keyup event instead of blur:
$('#FormCustomObject6Name').keyup(
function()
{
var x = $('#FormCustomObject6Id').val();
$("a[href*='http://www.msn.com']").attr('href',('http://www.google.com/search?q='+ x));
$('a#link').text('Link has been updated');
}
);
The only problem with this is that it won't catch instances where users enter data without using their keyboard (paste via right click, etc.).
You could use a mouseover event, say over the button or the link.
I changed this
$('.butter').mouseover(function(){
to have a mouseover the button.
Example: http://jsfiddle.net/X8D4M/39/
You can trigger events on objects yourself manually by using trigger(event).
So this might work for you:
$('button.butter').trigger('click');
Did you try just triggering a click?
$('button.butter').click();
Here's what you're looking for.
$('#FormCustomObject6Name').trigger('blur');
Okay, this is probably not the most efficient solution, but if you use setInterval to check for the changed value you're guaranteed to cover all sources of the change.
setInterval(function(){
var id = $('#FormCustomObject6Id').val();
var name = x + $('#FormCustomObject6Name').val();
if (id.length > 0 && name.length > 0){
$("a[href*='http://www.msn.com']").attr('href',('http://www.google.com/search?q='+ id));
$('a#link').text('Link has been updated');
}
},500);

Categories

Resources