How do I check when an input is changed? - javascript

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.

Related

JavaScript: Simulate a click with a value

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" );

Programatically put input in editing state (just like clicked on it with mouse)

Assume there is a regular html input field
<input id="inputEl" type="text">
When I click on it with my mouse, it starts being 'editable' (an editing line at the beginning starts blinking) - just like every input field.
Using jQuery, I am trying to simulate that so without me clicking on it with mouse, it gets on that editing state.
I have tried:
$('#inputEl').click()
$('#inputEl').keydown()
$('#inputEl').focus()
$('#inputEl').focusin()
$('#inputEl').blur()
$('#inputEl').select()
$('#inputEl').trigger('input')
But none seems to do the trick.
What is the proper way of achieving this?
.focus() would be the correct method here, the problem you are facing could be related to other issues.
At least it is working here
http://jsfiddle.net/KN6rs/
The focus() function doesn't work on console because:
$.focus() not working
I tried
setTimeout(function() { $('.js-search-field').focus() }, 3000); works on SO
$(document).ready(function() {
$('#inputEl').focus();
});
This is your solution. You just need to do it when the DOM is loaded. $(document).ready takes care of that.
Looks like you want to simulate click event. You can do it via jQuery using trigger(), like this:
$("#inputEl").trigger("click");
Here is an example:
$("#inputEl").trigger("click");
function wasClicked() {
console.log('Click event was successfully simulated')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inputEl" type="text" onclick="wasClicked()">
Or if you want just to focus on this input, here it is:
$("#inputEl").focus()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inputEl" type="text">

How can I fire a Javascript event when a text box is changed but not by the user?

I have a custom tag STRUTS in a JSP set as standard used to handle the calendar and I can't set any type of event here.
This tag render this HTML : <A onmouseover="return true" href="javascript:ShowCalendar('data')> (..img..) </A>**
When you select date on link, this change my text box with the date selected, I need fire my event in this moment.
My textbox struts tag is this <html:text property="data" styleClass="testo10" size="12" maxlength="10" tabindex="3"/>
I tried with onchange event, but this work only if user do the changes.
I need fire event whenever the textbox is changed whether the user is or not(changes from Javascript for example or from link, like in my case).
How can I do that?
This can be achieved with 'input' event.
<input type="text" class="txtTest" value="test" onchange="textChange();" oninput="this.onchange();"/>
Here I used jQuery to trigger 'input' event and setTimeout() to just mimic text change dynamically.
function textChange(){
alert('text change');
}
setTimeout(function(){
$('.txtTest').val('new text').trigger("input");
},2000);
JS Bin link here
Basically .trigger() method of jQuery help to trigger the event which you want to fire. In this case I'm firing 'input' event of textbox, which in return calling it's own onchange() method. Or simple you can directly trigger change event also.
Another Solution
For IE7 support
jQuery 1.x + textchange plugin help to achieve this.
I tried with IE7 Emulation.
<input type="text" id="txtTest" value="test"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://zurb.com/playground/uploads/upload/upload/5/jquery.textchange.min.js"></script>
<script type="text/javascript">
$('#txtTest').bind('textchange', function (event, previousText) {
alert(previousText);
});
setTimeout(function(){
$('#txtTest').val('new text').trigger('textchange','some data');
},3000)
</script>
Bind change event in javascript
document.getElementById('txtbox_id').addEventListener('change', function() {
alert("text changed"); //or do whatever u want here
});

Calling .mouseenter( ) is working even though .click( ) won't trigger animation

In HTML, I have a button with the id of "submit1"
<div id="first">
<form>
<input type="radio" name="school" value="pitt">Pitt<br>
<input type="radio" name="school" value="memphis">Memphis<br>
<button id="submit1">Submit</button>
</form>
</div>
Now in Jquery, I try to use a .click() to trigger the div "first" to fadeOut, like so:
$(document).ready(function() {
$('#submit1').click(function(){
$('#first').fadeOut('slow');
});
});
Weirdly enough, nothing happens when I click submit. I thought maybe it wasn't calling my .js file, but alas, when I change it to a .mouseenter( ), it works perfectly to trigger a fadeOut of the div.
$(document).ready(function() {
$('#submit1').mouseenter(function(){
$('#first').fadeOut('slow');
});
});
I saw an old Stack Overflow post where they used alert instead of an animation, so I tried that too during debugging and it still worked. It is literally just animations that seem to break things (tried .slideToggle, .slideDown, etc. just to check). Thanks!
Since the submit button is inside a form element, the default click behavior is to submit the form to the server. Internally, the JS is being called but this also causes the whole page to refresh so you don't see the animation happening. In order to prevent this, change your code to prevent the default submit behavior:
$('#submit1').click(function (e) {
e.preventDefault();
$('#first').fadeOut('slow');
});

Fire an event on input.checked=true/false _without_ jQuery

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

Categories

Resources