I'm using this bit of jQuery to append a text input field to a div after a checkbox is checked:
$('.sharewithfriends').on("click", ".manual-invite", function () {
if ($('input[name=manual-invite]').is(':checked')) {
$('<li style="margin-top:0;display:none"><input type="text" id="invite_email1" name="invite-email1" value="Add an E-Mail" onfocus="clearText(invite_email1);" onblur="fillText(invite_email1);"/><span><a class="add" href="">Add</a></span></li>').appendTo('#invite-emails').slideToggle();
}
All of that works fine, except for the onfocus and onblur events. They call the following simple functions, which are supposed to clear the field on focus and fill it with the default text on blur:
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
function fillText(thefield){
if (thefield.value=="")
thefield.value=thefield.defaultValue;
}
But when I click the field, I get an error saying "invite_email1 is not defined" even though it clearly is.
Anyone know what I need to do to get this to work?
You're not referring to the right element.
Replace clearText(invite_email1); with clearText(this);.
Even better, bind event listeners instead of adding inline events.
Related
So this is probably an easy one, but I'm just not doing it right. My goal is to send the user input from this textbox:
<input type='text' placeholder='Form Name...' id='formNameInput' required>
Into this Div:
<div id="code_output"></div>
I'm trying to make it appear in real time, and so far I used this to try and do so, but it doesn't work:
document.getElementById("code_output").innerHTML += document.getElementById("formNameInput").value;
Why doesn't it show? Does my code need something to trigger the Javascript?
You're close, but the issue is that you're not using an event handler. The script is executing your code once, as soon as possible (before you have the chance to enter anything into the text input). So, you have to add some sort of event listener so that the copying happens at the appropriate time. Something like below:
document.getElementById('formNameInput').addEventListener('keyup', copyToDiv);
function copyToDiv() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
<input type='text' placeholder='Form Name...' id='formNameInput' required>
<div id="code_output"></div>
You need to do that whenever the value of formNameInput changes. For that you need an event.
Your code should look like:
document.getElementById("formNameInput").addEventListener('input', function () {
document.getElementById("code_output").innerHTML += this.value;
});
function change() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
document.getElementById('formNameInput').onkeyup = change
maybe this is what you are trying?
You need to attach an event listener to your input that executes a function any time an input event occurs on the field:
formNameInput.addEventListener('input', function(e) {
code_output.textContent = e.target.value
})
<input type="text" placeholder="Form Name..." id="formNameInput" required />
<div id="code_output"></div>
Please note that the above code takes advantage of the fact that browsers automatically create a global variable for each element with a unique id attribute value, and this variable has the same name as the value of the id.
If the concept of events is new to you, this might be a good place to get started:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
I have a textbox which is hidden using display = none. I am trying to change it to visible on some condition, however it does not seem to work. I have checked that the control is going to the change event. I have tried various ways to get it to work, the 3 ways that I have tried are within the $('body')
colValue = "<input id ='val' class='value' value ='" + field.Value + "'style = 'display: none'/>";
I have tried these different things to get it to show the control. None of these work.
$('#val').css("display", "block");
$('#val').css('display', 'inline');
$('#val').css({ "display": "inline" });
Am I missing something?
Edit
So your issue appears to be that the box isn't appearing after a change event. Ensure that your HTML IDs are unique, and that your change handler is getting wired up after the DOM is ready. If those are all true the issue likely exists outside of the code fragment you've shown, since the code you've provided should work. One thing to note is that the change event doesn't get fired until the control being changed loses focus. If it's another textbox, you have to click out of the box before the event gets fired. See the example below (note: I'm using show to update the element's visibility since that's more idiomatic, but it should be functionally equivalent to what you attempted.)
$(function() {
$('body').on('change', '.condition', function () {
$('#val').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Text Box 1 <input id ='val' class='value' value='test' style='display: none' type='text'/> <br />
Text Box 2 <input class='condition' type='text'/>
There's no variable named inline in your application. Wrap it in quotes and make it a string. Additionally, you're trying to change the style, so you have to call the appropriate method (See docs for css method):
$("#val").css("display", "inline");
I am attempting to target the previous input field of a form element that is in an accordion. I have tried several ways to target the .image-url field but I am having trouble with targeting just this one field within the accordion. This may be a simple task but I cannot get this thing to work. Any help would be greatly appreciated.
HTML
<form>
<input class="image-url" type="text" />
<input class="button" type="button" />
</form>
JS
$('form .button').click(function() {
// do stuff
uploader.on('select', function() {
$(this).prev().val('text to put');
}
}
This is what I have right now and I cannot get it to work.
this within the uploader.on callback probably isn't the button. Remember the button and then use it in the callback:
$('form .button').click(function() {
var btn = $(this);
// do stuff
uploader.on('select', function() {
btn.prev().val('text to put');
}
});
Side note: Whenever I see an event handler hooked up from within another event handler, it raises a flag for me. If the button is clicked twice, you'll end up with two handlers on uploader for the select event. You might want to check whether that's really what you want...
Side note 2: CSS selectors can do more than just ids and classes, you may not need that class="button" on the button. You can select it via form input[type=button] (in your CSS for styling, and in a jQuery $() call and similar to locate it).
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.
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.