I need to simulate a click, and send the value of an element. This is because the item I need to click exists several times on the page with the same ID, but I only want trigger the behavior of one.
The element looks like this
<input type="submit" value="Login" class="um-button" id="um-submit-btn">
My code so far is
$("#user_password-36").on('keyup', function (e) {
if (e.keyCode == 13) {
$("#um-submit-btn").click();
}
});
But I think I need to be able to send the value, which is 'Login'. Otherwise it triggers the wrong submit button.
I appreciate this is not a good solution, but I need to make this work without modifying the existing code that runs the login system.
Even though it's a bad idea to have multiple elements with the same id (your case is a problem that comes with such usage), you can select it by specifying the value as well as the id:
$("#um-submit-btn[value='Login']").click();
Using this method, you can add the keyup handler to multiple elements instead of just one for a button with a given value. However, You must use a class for the element you need to attach this handler to. You may also use classes for other duplicate elements as well.
If somehow the element with class user_password-36 shares the same parent as this button:
<div>
<input class='user_password-36' />
<input id='um-submit-btn' />
</div>
you can use this
$(".user_password-36").on('keyup', function (e) {
if (e.keyCode == 13) {
$(this).parent().find("#um-submit-btn").click();
}
});
Also, if somehow they share same parent but are nested in any way:
<div id='parentId'>
<div>
<input class='user_password-36' />
</div>
<div>
<div>
<input id='um-submit-btn' />
</div>
</div>
</div>
then supply the id (or class) of their common parent
$(".user_password-36").on('keyup', function (e) {
if (e.keyCode == 13) {
$(this).parents('#parentId').find("#um-submit-btn").click();
}
});
You can also trigger the click event by using trigger()
$("#um-submit-btn[value='Login']").trigger( "click" );
Related
I have an onblur='validate(this)' on a text field but I do not want the validate code to run when a cancel button is clicked.
function validate(oField) {
if (document.getElementById('Cancel').clicked != true) {
console.log("Cancel clicked");
}
}
<input id='reviewername'
name='reviewername'
type='text'
class='$class'
value='$reviewername'
tabindex=1
size=$size
onkeydown='setKeyCode(event)'
onblur='validate(this)'/>;
<input type='submit'
name='Button'
id='Cancel'
value='Cancel'>;
The document.getElementById('Cancel').clicked is always 'undefined'.
I have tried addListener(), probably incorrectly, as well as other newbie tricks with no success!
What I am trying to do is check whether the Cancel button is clicked while the text field has the focus. Immediately I click the button, the text field event 'onblur' runs. I want to check for the button click as the first part of the javascript validate() function.
Is what I am attempting even possible?
Please help before I lose the rest of my hair.
You can use àddListener() if you name it correctly as addEventListener().
Then, you can set some variable when the cancel button is clicked and use that variable in replacement to your document.getElementById(...).clicked.
cancel_clicked = false;
function validate(oField) {
if (cancel_clicked != true) {
console.log("Cancel not clicked");
} else {
console.log("Cancel clicked");
}
}
<input id='reviewername'
name='reviewername'
type='text'
class='$class'
value='$reviewername'
tabindex=1
size=$size
onkeydown='setKeyCode(event);'
onblur='validate(this);'/>
<input type='submit'
name='Button'
id='Cancel'
value='Cancel'
onclick='cancel_clicked = true;'/>
Browsers are removing direct event listener attachment to DOM elements, it's better to use javascript to add the event listeners, instead of the onlick or onblur attributes on DOM elements, this is what I've noticed lately.. So you are more safe with using addEventListener, also do watch out for your spelling too incases where you get undefined,or you are loading your script before your DOM tree.. As a thumb rule, load your javascript file last.
I am studying some source code of a website and would like to know how to trigger programmatically the ajax autocomplete on this text box. I tried to include just the relevant code.
html:
<div class="input-text xxl-width completer">
<input type="text" placeholder="" id="textBoxText" name="textBoxText" class="predictiveText" autocomplete="off">
<div class="autocompleter-wrapper" style="display: none;">
</div>
</div>
javascript:
var w = this.$scope,
u = i.keyCodes,
v = this,
t = {
$predictiveLookup: w,
$predictiveInput: w.find("input.predictiveText"),
},
t.$predictiveInput.keydown(i.keyExecutor.onAllKeysExcept(function() {
v.isKeyDown = true
}, [u.enter, u.keyUp, u.keyDown, u.escape]));
t.$predictiveInput.keyup(i.keyExecutor.onAllKeysExcept(function() {
v.checkCompletion(n);
v.isKeyDown = false
}, [u.enter, u.keyUp, u.keyDown, u.escape]));
When I call $(elem).keyup(); or $(elem).keydown(); Nothing happens. Is there any way to trigger these events programmatically?
Use trigger:
$(elem).trigger('click');
Execute all handlers and behaviors attached to the matched elements for the given event type.
Docs: http://api.jquery.com/trigger/
It may be that $(elem).keyup() is indeed triggering your event correctly but that it's then falling foul of some logic somewhere inside keyExecutor.onAllKeysExcept which is comparing the pressed key against the supplied blacklist when no key is actually being pressed, meaning event.which is undefined.
You can simulate a specific key being pressed, perhaps one you would expect not to affect the input, using the following:
var e = $.Event('keyup');
e.which = 40; // (code for down arrow key say)
$(elem).trigger(e);
keyup and keydown are original event handlers of the elements.
You can't call them in some of the browsers directly after you used $() on them.
You can use .trigger('eventtype')
or you can access the original element and call the original elements handlers on it like:
$(elem)[0].keyup()
$(elem)[0].keydown()
or to make sure its browser independent but still operating with the original element:
$(elem).toArray()[0].keyup()
$(elem).toArray()[0].keydown()
I tried using the "input" event on the text box but it doesn't work. I've read a few posts on Stack Overflow but none of them worked.
Here's my most recent HTML and Javascript code using onchange:
function updateResults(){
document.write("Wroks");
}
<input id="search-box" onchange="updateResults();"> </input>
I tried changing HTML to onchange="updateResults;" but didn't work.
I also tried changing HTML to onchange="updateResults(event);" and then Javascript to function updateResults(event){...}
Nothing that I tried worked.
Looks fine to me. If you make any changes then you'll see the function get called as soon as you lose focus (onchange only happens when you blur). If you want more immediate results you can use oninput instead, like so:
function updateResults(){
document.write("Wroks");
}
<input id="search-box" oninput="updateResults();" />
Another way is to use event listeners, if you want to keep javascript out of the markup:
function updateResults() {
document.write("Wroks");
}
document.getElementById("search-box").addEventListener("input", updateResults);
<input id="search-box" />
The above however will only work if the DOM has already been loaded when the javascript is run. You could put it in an onload event, or include the javascript after the DOM markup.
Alternatively you could attach the event listener to the document and check for the ID whenever the event is triggered. There are pros and cons to this method. Since the function doesn't attach to the element directly, the DOM will not need to be loaded yet. If the element is removed and a new one with the same ID is added, it will still work. Also, if you add your content dynamically after the page loads, you will not need to worry about attaching the listener later. However, this function will be called every time any input on the page is registered, which theoretically could slow the page down (e.g. if you have a lot of these types of listeners), although probably minimally.
function updateResults() {
document.write("Wroks");
}
document.addEventListener("input", function(e) {
if (e.target.id === "search-box") {
updateResults();
}
});
<input id="search-box" />
document.write("Wroks"); will replace everything in your window with "Wroks".
try this:
<input id="search-box" onchange="updateResults();"> </input>
<script>
function updateResults(){
console.log('Works');
}
</script>
You also may want to consider using jQuery because then you could do a lot more out of the box with this. for example:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<input id="search-box">
<script>
$('#search-box').on('change',function(){
console.log($(this).val());
})
</script>
The above code will give you the value of the input on change.
try:
<input id="search-box" onchange="javascript:updateResults();"> </input>
or:
<input id="search-box" onchange="javascript:document.updateResults();"> </input>
It is a bit unclear whether you want the JavaScript to fire when the user finishes updating the textbox, or after every character is input.
This will fire after the user "commits" to their input, often by clicking something else.
HTML
<input id="search-box" />
JavaScript
function updateResults(){
alert("Works");
}
document.getElementById("search-box").addEventListener("change", updateResults, false);
This will fire after every key is pressed (and so forth).
HTML
<input id="search-box" />
JavaScript
function updateResults(){
alert("Works");
}
document.getElementById("search-box").addEventListener("input", updateResults, false);
As far as I understand the question, you want to know when a user types in one letter/number and then call your function.
This would be "onkeyup":
<input type="text" onkeyup="myFunction()">
You could also use onkeydown. See also http://www.w3schools.com/jsref/dom_obj_event.asp
When you use onchange, this works too, but only after the input is finished. Either when the user presses enter or after leaving the textbox.
If all of this doesn't work, turn on Javascript in your Browser.
I'm having a problem capturing Tab Keydown events on date inputs. Say I have a form with five inputs, the first and last of which are date inputs (the html here is for reference... I know it's missing ID, tabindex, etc.):
<form id="heyImAForm">
<input type="date" id="in1" />
<input type="text" id="notimportant2" />
<input type="text" id="notimportant3" />
<input type="text" id="notimportant4" />
<input type="date" id="in5" />
</div>
What I'd like to do is call a method when the user Shift-Tabs out of the first input, and when the user Tabs out of the last input.
The problem is, I'd like to preserve the native Tab key behavior for date inputs, which is to move between days/months/years. So, something like this:
$('#in1').keydown(function(e) {
if (e.which == 9 && e.shiftKey) {
doAThing();
}
});
$('#in5').keydown(function(e) {
if (e.which == 9) {
doADifferentThing();
}
});
.... "works", but effectively kills that native Tab key behavior. So, long story short, is there a way to only trigger the Tab key event if the focus shifts away from the date input, as opposed to moving between day/month/year?
After trying a few things I think the best solution would be what you see here but please read on to get a full understanding of what I am doing. We are setting the focusout when the user hits shift-tab on the first element or shift without tab on the second element. We must unbind this action if the user hit something else so we don't fire the action if they shift-tab but stay within the element then shift out of it. So try something like this:
$('#in1').keydown(function(e) {
if (e.which == 9 && e.shiftKey) {
$(document).mousedown(function(){
$('#in1').unbind('focusout');
$(document).unbind('mousedown');
});
$('#in1').focusout(function(){
doAThing();
});
} else {
$('#in1').unbind('focusout');
$(document).unbind('mousedown');
}
});
$('#in5').keydown(function(e) {
if (e.which == 9 && !e.shiftKey) {
$(document).mousedown(function(){
$('#in5').unbind('focusout');
$(document).unbind('mousedown');
});
$('#in5').focusout(function(){
doADifferentThing();
});
} else {
$('#in5').unbind('focusout');
$(document).unbind('mousedown');
}
});
You can see we are also setting mousedown of the entire document when the shift-tab(in1) or tab-without-shift(in5) is being hit. In the mousedown we are unbinding the focusout so if the focus leaves because of a mouse click we don't fire doAThing(). We also unbind mousedown on the document because you don't want it firing every time the user clicks after tabbing(in5) or shift-tabbing(in1) on those elements.
You may also be interested in seeing what I did on this fiddle. This isn't the best solution because the setTimeout's can cause some problems and undesired effect in many cases.
Also, in your provided code the closing tag should be </form> not </div>.
Consider the following code (http://jsfiddle.net/FW36F/1/):
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].checked;">toggle</button>
If you click the checkbox, you get an alert telling you if it's checked or not. Great. However, if you click the toggle button, the checkbox changes it's checked state but the onchange event is NOT fired.
Essentially, the onchange for a checkbox only fires if the user actually clicks the checkbox, not if the checkbox is changed via JavaScript. This is be true in IE, FF, and Chrome. It appears that this behavior is to specification also.
However, I really need some kind of event to fire if, for any reason, the checkbox's checked state changes. Is this possible?
Oh yeah, and jQuery is not allowed. And please no setTimeout/setInterval based solutions either...
Update: Also, I should make it clear that the code above is for illustration only. In the real code, we need to ensure the state of the checkbox is checked or unchecked -- not just toggle it. Perhaps this would be better code to illustrate that:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=true;">check</button>
<button onclick="document.getElementsByTagName('input')[0].checked=false;">un check</button>
Moreover, there may be code in other areas we don't fully control, which might do a simple .checked=true/false -- we'd like to make sure we see that also.
The existing answers work just fine, even with your update. Just be smart about it and don't call click if you don't need to. Also, please don't use inline JS. That was OK 10 years ago.
<input type="checkbox" onchange="alert(this.checked)">
<button id='check'>check</button>
<button id='uncheck'>uncheck</button>
document.getElementById('check').onclick = function() {
if (!this.checked) {
this.click();
}
}
If you need to be modified when a script changes the value, in Firefox, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch
Example here http://jsfiddle.net/PPuZ8/
// In FF $ is a shortcut for document.getElementById
// It doesn't fire when set from the UI, you have to use a regular handler for that
$('cb').watch("checked", function(){
console.log('Checked state changed from script', arguments);
return true;
});
For IE you can use onpropertychange http://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx (Thanks to jivings for the reminder)
Example: http://jsfiddle.net/PPuZ8/1/
document.getElementById('cb').onpropertychange = function() {
if (event.propertyName == 'checked') {
console.log('Checked state changed onproperty change');
}
};
For other browsers, you have to poll using setInterval/setTimeout
Have the toggle button actually click the checkbox:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].click()">
toggle
</button>
If you wanted any change to the checkbox to inform you of its new position, then I would create a global method for changing the value of the checkbox, and deal with it as a proxy:
<script>
function toggleCB( state ) {
var cb = document.getElementById("cb");
arguments.length ? cb.checked = state : cb.click() ;
return cb.checked;
}
</script>
<input id="cb" type="checkbox" />
<input type="button" onClick="alert( toggleCB(true) )" value="Check" />
<input type="button" onClick="alert( toggleCB(false) )" value="Uncheck" />
<input type="button" onClick="alert( toggleCB() )" value="Toggle" />
Now anytime you set or toggle the checkbox, you'll get the checked state back.
One last thing, I would avoid using the onClick attribute, and instead bind the click events up from within your JavaScript.
Use click()
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button>
oninput is the event you need to handle ...
https://developer.mozilla.org/en/DOM/DOM_event_reference/input