I've been trying experiments with the following, but so far to no avail:
sel = document.getElementById('myComboBox')
sel.selectedIndex = 1;
sel.options[1].selected = true;
sel[1].click();
Thanks for the help!
Wait why would you write:
sel.options[1].selected = true;
and then in the very next line write
sel[1].click();
?? The element is not an array and can't be treated as one.
The "click" event might not be the best thing to handle anyway. Probably the "change" event on the select element itself would be more reliable.
Related
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);
Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow?
I know about .change() method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup() method but it reacts also on arrow keys and so on.
I need just trigger an action every time the text in the input changes, even if it's only one letter change.
There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details:
jQuery keyboard events
Catch only keypresses that change input?
Example (except IE < 9: see links above for workaround):
$("#your_id").on("input", function() {
alert("Change to " + this.value);
});
Yes, compare it to the value it was before it changed.
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
Another option is to only trigger your changed function on certain keys. Use e.KeyCode to figure out what key was pressed.
You can also store the initial value in a data attribute and check it against the current value.
<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" />
$("#id_someid").keyup(function() {
return $(this).val() == $(this).data().initial;
});
Would return true if the initial value has not changed.
function checkChange($this){
var value = $this.val();
var sv=$this.data("stored");
if(value!=sv)
$this.trigger("simpleChange");
}
$(document).ready(function(){
$(this).data("stored",$(this).val());
$("input").bind("keyup",function(e){
checkChange($(this));
});
$("input").bind("simpleChange",function(e){
alert("the value is chaneged");
});
});
here is the fiddle http://jsfiddle.net/Q9PqT/1/
You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):
$(document).ready(function() {
$("#fieldId").bind("keyup keydown keypress change blur", function() {
if ($(this).val() != jQuery.data(this, "lastvalue") {
alert("changed");
}
jQuery.data(this, "lastvalue", $(this).val());
});
});
This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.
UPDATE: Added blur to the bind list.
I had to use this kind of code for a scanner that pasted stuff into the field
$(document).ready(function() {
var tId,oldVal;
$("#fieldId").focus(function() {
oldVal = $("#fieldId").val();
tId=setInterval(function() {
var newVal = $("#fieldId").val();
if (oldVal!=newVal) oldVal=newVal;
someaction() },100);
});
$("#fieldId").blur(function(){ clearInterval(tId)});
});
Not tested...
I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.
You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed.
To do this in a more or less clean way:
You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess.
An example is in this fiddle: http://jsfiddle.net/zeEwX/
Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed:
var inp = $('#input'),
val = saved = inp.val(),
tid = setInterval(function() {
val = inp.val();
if ( saved != val ) {
console.log('#input has changed');
saved = val;
},50);
You can also set this up using a jQuery special event.
What I wanted to do is figure out whenever the user is engaged with an INPUT or TEXTAREA element and set a variable flag to true... and set that flag to false immediately after the user is no longer engaged with them (ie. they've clicked out of the INPUT/TEXTAREA elements).
I used jQuery's docuemnt.ready function to add the onclick attribute to my body element and assign it to my getActive() function.
The code for the getActive() function is as follows:
function getActive()
{
activeObj = document.activeElement;
var inFocus = false;
if (activeObj.tagName == "INPUT" || activeObj.tagName == "TEXTAREA")
{
inFocus = true;
}
}
I'd really like to keep by project withing the jQuery framework, but can't seem to find a way of accomplishing the same logic above using JUST jQuery syntax.
You want the focus and blur event handlers. For example...
var inFocus = false;
$('input, textarea').focus(function() {
inFocus = true;
});
$('input, textarea').blur(function() {
inFocus = false;
});
I'm pretty sure that a comma will get you input OR textarea, but you get the idea if that doesn't pan out
function getActive(){
return $(document.activeElement).is('input') || $(document.activeElement).is('textarea');
}
For the original question about figuring out if the currently focused element is any of those user input elements, below should work:
function isInputElementInFocus() {
return $(document.activeElement).is(":input");
}
Conceptually I don't like this approach for generic case where you are listening to global events (like key strocks) and trying to decide if these should be handled by your global handler or be ignored because it is meant for someone else. The reason I don't like it because it's not future safe and also who knows what else that someone can be besides input elements.
Another more robust but tricky to implement idea is to test if event is meant for an element that has tabIndex >= 0. The input elements have tabIndex === 0 set by default so it becomes more or less similar to above approach. You can easily check this by event.target.tabIndex >= 0 without need to rely on document.activeElement.
The gotchas here (if you want to be generic) is that you also need to make sure that event.target element is neither in another branch in DOM hierarchy nor there is someone else between event.currentTarget and event.target that has tabIndex >= 0. You get the idea: This can become murky but I just thought to jot it down if someone else is in need of generic solution.
You can do something like this :
var focusItem = null;
$('input, textarea').focus( function() {
focusItem = this;
});
Iis the .blur() event what you're looking for?
Very strange thing is happening with the 'change' event of the dropdown list.
Basically I have a dropdown, on change of which i have to do some cross domain web service call. This call is being made from the javascript itself.
For the first time when i change an item in the 'select' list the change event is triggered only once. Next time twice and it grows like this.
Any clue why is it behaving like this?
If code needed for reference i can share. But its a simple 'select' list and 'change' event handler there.
$("#ArtifactSort > select").change(function() {
var rankField= "";
rankField = $("#ArtifactSort > select option:selected").text();
alert('within select change event artifact: '+ rankField );
//Making the text little lighter and showing the loading icon.
//$("#ArtifactPetalContentUL").css("filter", "alpha(opacity: 30)");
$loadingIconForArtifact = addLoadingIcon("ArtifactPetalContentUL", "Artifact");
var refinedStoresLocal= new Array();
for (var storeIndex in _searchResponseForArtifact.searchResult.searchRequestProcessed.stores) {
refinedStoresLocal.push(_searchResponseForArtifact.searchResult.searchRequestProcessed.stores[storeIndex].name);
}
var refinedFiltersLocal = new Array();
for (var filterIndex in _searchResponseForArtifact.searchResult.searchRequestProcessed.filters) {
refinedFiltersLocal.push(_searchResponseForArtifact.searchResult.searchRequestProcessed.filters[filterIndex]);
}
//rankfield.
var rankLocal=new Array();
rankLocal.push(new RankingField(rankField, 1, 0));
//Request object and WS Call.
var _searchRequestForArtifactLocal = getArtifactSearchRequestObject(_queryStringLocal, _memberId, _communityId, _pageNumber, _pageSize, propertiesForArtifact, refinedStoresLocal, ClassificationClusteringObjectsForArtifact, refinedFiltersLocal, rankLocal);
getSearchResponse("successcallForArtifact", _searchRequestForArtifactLocal);
});
Thanks
Subrat.
You must be binding a new handler from within the change handler.. So, each time it runs, it adds an additional instance of the handler to be executed the next time..
Show us the handler you assign to the change event (and how you do it) for a more detailed answer..
[update]
From your code everything seems fine.. Do check the two functions you call though, ( addLoadingIcon and getSearchResponse ) in case they do any jQuery event binding, that might inadvertently apply to the select object..
Also check your RankingField constructor in case it binds any events ...
I had the same issue described by the OP. I found that Chrome Dev Tools helped me verify that it was a multiple event handler issue for me. Open the Dev Tools, use the element picker to select the 'select' object in question, and check on the Event Listeners tab for change handlers.
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.