I am new with JavaScript, I have a value in an input field, like 0 or 1 and then when this value changes a word is changed to 'Off' or 'On' respectively.
I know this is pretty simple but I'm new with JavaScript as I said.
How does your code look like currently?
What have you tried so far?
EDIT
I'm working in the code right now so nothing great so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function change(value) {
if (value == 1)
return "ON";
else
return "OFF";
}
</script>
</head>
<body>
<input type="text" value="1" />
<p>ON OR OFF RIGHT HERE</p>
</body>
</html>
What difficulties are you encountering?
I need this values keep been updating all the time, if the value of the input field change the word must change either.
If you are new to javascript what tutorials/articles/books did you read so far in order to get started?
Not a specific tutorial right now, I'm googling.
EDIT 2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function change(){
toggler = document.getElementById('toggler');
onoff = document.getElementById('onoff');
toggler.onChange = function(e){
onoff.innerHTML = (toggler.value==1)? 'on' : 'off';
}
}
</script>
</head>
<body>
<input type="text" id="toggler" value="1" onkeyup="change()" />
<div id="onoff"></div>
</body>
</html>
I'm trying to following the suggestions but still not working, what am I doing wrong here guys ?
You don't posted any code but here it goes some general code:
Your input:
<input type='text' id='myinput' onkeyup='contentChanged(this)' />
Look for other key events: http://unixpapa.com/js/key.html
Then, your function:
function contentChanged(myinput)
{
var myvalue = myinput.value;
if (myvalue == "1")
{
// Do something with value = 1
}
else if (myvalue == "0")
{
// Do something with value = 0
}
// And so on...
}
EDIT:
Now that you've posted your code, you can do like as I said:
<input type="text" value="1" onkeyup="change(this.value)" />
EDIT 2:
You're setting two events to your object and onChange just works to select object. Because of this I suggested you to use onkeyup or another key event. Just remove your onChange event out of your function.
Change to this and try:
function change(){
toggler = document.getElementById('toggler');
onoff = document.getElementById('onoff');
onoff.value = (Number(toggler.value)==1)? 'on' : 'off';
}
Number function is important to cast your input data and be sure that is a number.
Plus add an maxlength attribute on your textfield to limit user input data:
<input type="text" id="toggler" value="1" onkeyup="change()" maxlength="1" />
You need to add an onChange handler to your input field, this can be done in many ways. for example, let's say your input has an id of #toggler, and the element where either on or off needs to be shown has an id of #onoff
toggler = document.getElementById('toggler');
onoff = document.getElementById('onoff');
toggler.onChange = function(e){
onoff.innerHTML = (toggler.value==1)? 'on' : 'off';
}
Related
var data = document.getElementById('myFieldId');
console.log(data.value);
<!DOCTYPE html>
<html>
<head> </head>
<body>
<input type="text" id="myFieldId"/>
<script src="main.js"></script>
</body>
</html>
I expect when I write any text in the input, it would print the corresponding text. But I don't get anything in the console. What should I do?
You need to add an event listener that executes as soon as someone inputs text.
There is no such thing as binding a variable to a text input; this needs to be implemented by yourself.
See this example:
const data = document.getElementById('myFieldId');
data.addEventListener(
'input', // first argument is the name of the event you want to react to
// second argument is the function that should execute when the event occurs
function(inputEvent) {
console.log(data.value);
}
);
<input type="text" id="myFieldId"/>
You code start at load page so is empty, i add an onchange event so when you finish to write console.log will output the value.
var data = document.getElementById('myFieldId');
data.onchange = function()
{
console.log(this.value);
};
<!DOCTYPE html>
<html>
<head> </head>
<body>
<input type="text" id="myFieldId"/>
<script src="main.js"></script>
</body>
</html>
I am a fan of the timepicker from this SO answer but can't get it to work in a project where input elements are created dynamically. Problem seems that this timepicker needs to store the object returned by the constructor. Ideally, timepicker should work like the datepicker from jQuery-UI. So I tried to be clever and before creating a jQuery plugin I tried to make a javascript class like this:
function MyTimePicker(inputelement) {
// store the timepicker object
this.mytimepicker = new TimePicker(inputelement);
// show picked time in the element
this.mytimepicker.on('change', function (evt) {
var value = (evt.hour || '00') + ':' + (evt.minute || '00');
evt.element.value = value;
});
}
and use it like this on three input elements:
var dummy1;
var dummy2;
var dummy3;
window.onload = function () {
dummy1 = new MyTimePicker(jQuery('#time2').get(0));
dummy2 = new MyTimePicker(jQuery('#time3').get(0));
dummy3 = new MyTimePicker(jQuery('#time4').get(0));
};
It doesn't work. The timepicker popup appears when clicking in each of the input elements, but the on(change) event is never called so that the picked time does not show in the input element.
Either because of not having enough experience with Javascript objects, or with using this timepicker.
Update: I improved my code with a proper prototype, here is the complete code, completely standalone to play with:
<!DOCTYPE html>
<html>
<head>
<title>Timepicker class, standalone, by Jonatas Walker</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<!-- source: https://github.com/jonataswalker/timepicker.js SO: https://stackoverflow.com/a/36758501/1845672 -->
<link href="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet">
<script src="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>
</head>
<body>
<div id="arrayoftimes">
<input id="time2" type="time" placeholder="Time HH:MM"><br />
<input id="time3" type="time" placeholder="Time HH:MM"><br />
<input id="time4" type="time" placeholder="Time HH:MM"><br />
</div>
<script>
// Javascript Class. this disturbs the above reference application of TimePicker. It probably is not re-entrant.
//constructor
function MyTimePicker(selector) {
this.mytimepicker;
this.init(selector);
}
//prototype
MyTimePicker.prototype = {
init: function (selector) {
var inputelement = jQuery(selector).get(0);
this.mytimepicker = new TimePicker(inputelement);
// show picked time in the element
this.mytimepicker.on('change', function (evt) {
var value = (evt.hour || '00') + ':' + (evt.minute || '00');
evt.element.value = value;
});
}
};
</script>
<script>
var dummy1;
var dummy2;
var dummy3;
window.onload = function () {
dummy1 = new MyTimePicker('#time2');
dummy2 = new MyTimePicker('#time3');
dummy3 = new MyTimePicker('#time4');
};
</script>
</body>
</html>
Now the first input element works OK, but the picked time value goes into all three input elements. The other two inputs do show the timepicker dialog, but the picked value does not appear.
In the Firebug console, after picking the first time, I see two errors in the timepicker.js: TypeError: active is undefined.
Could that indicate that, somehow, the timepicker internal code is not re-entrant?
Or am I doing something wrong with object oriented javascript?
Update:
I am pretty sure that there is a bug in timepicker.js. I will report here as soon as I find it.
With gforce301 helping me to read the docs, I came to this solution to turn the timepicker into a jQuery plugin. This code has test code and is stand-alone, and contains checkboxes to select or deselect inputs for the timepicker.
The plugin is at the end of this code.
Working: you can add more inputs with the timepicker. Test this with selecting more checkboxes.
Not working: you cannot remove a timepicker from an input. If you deselect a checkbox, the related input will not be listed in the new target list passed to the setTarget() method, but the timepicker keeps working on the deselected input.
<!DOCTYPE html>
<html>
<head>
<title>Test of Timepicker class, standalone, by Jonatas Walker</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<!-- source: https://github.com/jonataswalker/timepicker.js SO: https://stackoverflow.com/a/36758501/1845672 -->
<link href="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet">
<script src="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>
<style>
.timepicker {background-color: yellow;}
</style>
</head>
<body>
<div id="arrayoftimes">
Time 1
<input type="checkbox" onclick="settimeclass(this, '#time1')" />
<input id="time1" type="text" placeholder="Time HH:MM"/>
<br />
Time 2
<input type="checkbox" onclick="settimeclass(this, '#time2')" />
<input id="time2" type="text" placeholder="Time HH:MM"/>
<br />
Time 3
<input type="checkbox" onclick="settimeclass(this, '#time3')" />
<input id="time3" type="text" placeholder="Time HH:MM"/>
<br />
<br />
ID's with timepicker: <span id='msg'></span>
</div>
<script> //this code is specific for this particular page
// at page load, uncheck all checkboxes
$('input:checkbox').prop('checked', false);
$('input:text').val('');
// when (un)checking a checkbox, adjust the timepicker class on each time input
function settimeclass(self, id){
if ($(self).prop('checked')){
$(id).addClass('timepicker');
}else{
$(id).removeClass('timepicker');
}
// apply the new jquery plugin for the timepicker
$('.timepicker').timepicker();
}
</script>
<script> // this code could be moved to a library
// jquery plugin for Jonatas's timepicker
(function ( $ ) {
// create time picker object
var _timepickerobj = new TimePicker([]);//([...], {lang:'en', theme:'dark'});
// attach event for formatting the time
_timepickerobj.on('change', function(evt) {
var value = (evt.hour || '00') + ':' + (evt.minute || '00');
evt.element.value = value;
});
// set timepicker target to jquery selector
$.fn.timepicker = function() {
var sel_array = this.toArray();
//_timepickerobj.target = [];// no effect
_timepickerobj.setTarget(sel_array);
// debugging: list time input id's with timepicker
var sel_ids = $.map(sel_array ,function(sel) {return sel.id;});
$('#msg').text(sel_ids);
return this;
}
}( jQuery ));
</script>
</body>
</html>
This plugin is good enough for my project, but it would be nice if someone could improve, e.g. on removing a timepicker from an input.
Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;
I'm doing some very rudimentary javascript work and seem to hit a bump. For the life of me, I can't seem to find what should be a very basic answer on Google.
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function lowerCase(){
var input = document.send.inputText;
input.toLowerCase();
document.write(input);
alert(input);
}
</script>
</head>
<body>
<h1>Test Page</h1>
<form name="send">
<input type='text' name="inputText" onkeypress="lowerCase()"/>
</form>
</body>
</html>
My intent is that the function lowerCase is executed on entering information into the textbox and pressing enter. However, I can never seem to get the function to execute.
How about...
HTML:
<input type='text' name="inputText" onkeypress="lowerCase(this)">
JavaScript:
function lowerCase ( input ) {
setTimeout( function () {
input.value = input.value.toLowerCase();
}, 0 );
}
Live demo: http://jsfiddle.net/vXpj8/3/
function lowerCase ( e ) {
if ( e.keyCode === 13 ) {
this.value = this.value.toLowerCase();
e.preventDefault();
}
}
document.send.inputText.onkeypress = lowerCase;
Live demo: http://jsfiddle.net/vXpj8/1/
Notice, how I bind the event handler with JavaScript. I do this because I want to have the event object available in the function.
There's a space between the onkeypress attribute and equals sign. Remove that; it should work.
Fiddle: http://jsfiddle.net/iambriansreed/jEnxH/
<form name="send">
<input type='text' name="inputText">
</form>
<script>
document.send.inputText.onkeypress = function(event){
if(event.keyCode != 13) return;
this.value = this.value.toLowerCase();
alert(this.value.toLowerCase());
event.preventDefault();
};
</script>
If you want it to work when the enter key is pressed, then you'll need to deal with the form being submitted, since pressing enter in a text input element that is a form control submits the form.
More likely you want to change the value to lower case on some other event, such as keup, e.g.
<input onkeyup="this.value = this.value.toLowerCase();" ... >
Doing this sort of thing is a bit annoying for users though, since upper case letters are magically changed to lower case. If there is a back-end requirement for lower case letters, better to deal with it there than confuse users entering text.
a few issues with your code
first var input is a input box not the string, toLowerCase() is a string method, you need input value
var input = document.send.inputText;
alert(input.value);
second, onkeypress is excuted before text is entered, maybe you should consider change onkeypress to onkeyup
try if this helps
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function lowerCase(){
var input = document.send.inputText;
input.value = input.value.toLowerCase();
}
</script>
</head>
<body>
<h1>Test Page</h1>
<form name="send">
<input type='text' name="inputText" onkeyup="lowerCase()">
</form>
</body>
</html>
I'm trying to subscribe to change events on an input tag for an ajax auto complete form. These change events are not firing when the user clicks an autocomplete suggestion from FireFox.
I've seen fixes for IE, but not FireFox. You can view this behavior here
Steps to recreate:
type any input in one of the boxes and click submit.
Start typing the value again in the same box.
You should see the autocomplete suggestion box appear below the input box. Notice that clicking the suggestion does not fire the change event (it also doesn't fire the click event)
Currently my only option is to disable autocomplete on this field, but I do not want to do that.
Firefox 4+ fire 'oninput' event when autocomplete is used.
Here's some jQuery to make this more actionable:
$('#password').bind('input', function(){ /* your code */});
I've had the same problem.
Apparently, there is password manager debugging available
https://wiki.mozilla.org/Firefox:Password_Manager_Debugging
So I've found that for me DOMAutoComplete event got triggered and
I've managed to attach it sucessfuly to a field via jQuery's bind like
$('#email').bind('DOMAutoComplete',function() { ...
If it makes you feel better, it is a known bug
Proposed workaround: (Not mine, from here
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Mozilla Firefox Problem</title>
<script type="text/javascript">
function fOnChange()
{
alert('OnChange Fired');
}
var val_textBox;
function fOnFocus()
{
val_textBox = document.getElementById('textBox').value;
}
function fOnBlur()
{
if (val_textBox != document.getElementById('textBox').value) {
fOnChange();
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr>
<td><input type="text" id="textBox" name="textBox" onFocus="fOnFocus()" onBlur="fOnBlur()"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
</body>
</html>
Another Suggested work around. This time using polling, you can work it in exactly
the same way, checking for "changes" to your field. Tweak the poll value (default to
375ms for your own taste).
I've used jQuery and a jquery plugin someone wrote:
https://github.com/cowboy/jquery-dotimeout/
Git Hub Src: https://raw.github.com/cowboy/jquery-dotimeout/master/jquery.ba-dotimeout.js
<html>
<head>
<meta charset="utf-8">
<title>onChange() for Firefox / IE autofil get-around</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/~dsloan/js/ba-dotimeout.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var val;
var count=0; // used to illustrate the "poll count"
// when focusing on the element and typing
// (vs not focused)
// set a focus function to poll the input
$("#myname").focus(function() {
// start polling
$.doTimeout('checkname', 375, function() {
++count;
// no changes, just exit this poll
if($("#myname").val() == val) {
return true;
// store the value
} else {
val = $("#myname").val();
}
var str;
// do stuff here with your field....
if($(document.activeElement) &&
($(document.activeElement).attr('id') ==
$("#myname").attr('id'))) {
var len = $("#myname").val().length;
if(len == 0) {
str = 'Timer called, length 0...';
} else if(len < 2) {
str = 'Timer called, length < 2...';
} else {
str = 'Timer called, valid!';
}
}
// show some debugging...
$("#foo span").html(str+' (count: '+count+'): '+
$(document.activeElement).attr('id')+
', val: '+$("#myname").val());
return true;
});
});
// set a blur function to remove the poll
$("#myname").blur(function() {
$.doTimeout('checkname');
});
});
</script>
</head>
<body>
<form action="#" method=post>
Name: <input type="text" name="name" value="" id="myname" />
Scooby: <input name="scooby" value="" id="scooby" />
<input type="submit" value="Press Me!" />
</form>
<div id="foo"><span></span></div>
</body>
</html>
A possibly alternative: could you simply use a timer to tell when the value of the text box changes?
You're going to have to blur the input field and reset the focus to it. That's going to require a little trickeration though.