In Javascript find if a checkbox is focused - javascript

In Javascript how can I tell if a checkbox has focus or not?
I thought there would be a method or property called isfocused. But apparently not.
By in focus I mean they've tabbed to it using the keyboard and at this point pressing space would check the box.

Create an event handler that is wired to the onfocus event. When it's called, set a global var to remember that it's got the focus. Write another one on the onblur event which clears the variable.

There is a onfocus event that fires when an element receives focus.
<script type="text/javascript">
var isFocused = false;
</script>
<input type="checkbox" name="team" value="team" onfocus="javascript:isFocused = true;">Spurs<br>

You might have to just hook into the onfocus and onblur events for the checkbox to keep track of when it gets and loses focus.

Here's an example of the basics of an implementation that might help you. Note: the output stuff is just for demonstration purposes and not part of the actual solution.
<html>
<head>
<script type="text/javascript">
onload = function()
{
var f = document.forms.test;
f.focusedElem = null;
updateOutput( f );
for ( var i = 0, l = f.elements.length, elem; i < l; i++ )
{
elem = f.elements[i];
elem.onfocus = function( elem )
{
return function()
{
elem.form.focusedElem = elem;
updateOutput( elem.form );
}
}( elem )
elem.onblur = function()
{
f.focusedElem = null;
updateOutput( f )
}
}
}
function updateOutput( f )
{
document.getElementById( 'output' ).innerHTML = ( null == f.focusedElem ) ? 'Nothing!' : f.focusedElem.id;
}
</script>
</head>
<body>
<form name="test">
<input type="checkbox" name="foo" id="foo1">
<input type="checkbox" name="foo" id="foo2">
<input type="checkbox" name="foo" id="foo3">
<input type="checkbox" name="foo" id="foo4">
</form>
What has focus? <span id="output"></span>
</body>
</html>

Related

How to type text to input text using Javascript (without jQuery)

You can set the value of a input like this:
document.getElementById("location-search").value = "Somewhere";
but how do you actually trigger type event using Javascript and without using jQuery?
You can use custom events. Fire an event when ever you add value to input. And add a listener against this event.
var type = new CustomEvent("typing", {});
function typed() {
document.getElementById("d").value = "Somewhere";
document.dispatchEvent(type);
}
document.addEventListener("typing", function(e) {
console.log("Something typed");
});
typed();
<input type="text" id="d" />
Here
Using the approach mentioned : Here
The change would the event type instead of HTMLEvents we use KeyboardEvent.
document.getElementById("d").addEventListener('keydown',function(e){
document.getElementById("log").innerHTML += '</br> keydown Triggered'
});
document.getElementById("triggeringStuff").addEventListener('click',function(){
var str = "Something";
var elem = document.getElementById("d");
str.split('').map(function(item){
var e = document.createEvent('KeyboardEvent');
e.initEvent('keydown');
elem.value += item;
elem.dispatchEvent(e);
});
});
<input type="text" id="d" />
<button id="triggeringStuff">Trigger Stuff</button>
<p id="log">Logs :</p>

Clearing textfield value

I'm trying to clear the textfield in html using javscript if the given condition is met. For ex:- if the user types awesome in textfield then it should reset the textfield (no blank space nothing).
<html>
<input type="text" id="real" onkeypress="blank()" placeholder="tempo"/><br>
<script>
function blank(){
if(document.getElementById('real').value=="awesome"){
real.value='';
}
}
</script>
</html>
Here real is undefined, so instead of
...
real.value = '';
...
do this
...
document.getElementById('real').value = '';
...
Use variable real to store input element and use onkeyup event:
function blank() {
var real = document.getElementById('real');
if (real.value == "awesome") {
real.value = '';
}
}
<input type="text" id="real" onkeyup="blank()" placeholder="tempo" />
<br>
Another good example would be:
document.addEventListener('DOMContentLoaded', function() {
var real = document.getElementById('real');
real.addEventListener('keyup', blank, false);
}, false)
function blank() {
if (this.value === "awesome") {
this.value = '';
}
}
<input type="text" id="real" placeholder="tempo" />
<br>
Change the line
real.value=''
to
document.getElementById('real').value = '';
You can't just say "real.value" because javascript doesn't know what "real" is.
<html>
<input type="text" id="real" onkeypress="blank()" placeholder="tempo"/><br>
<script>
function blank(){
var real = document.getElementById('real');
if(real.value=="awesome"){
real.value='';
}
}
</script>
</html>
You where facing issue with input event "onkeypress" if change the event and use "onkeyup"
issue will be resolved.
<html>
<script>
function blank() {
var real = document.getElementById('real');
if (real.value == "awesome") {
real.value = '';
}
}
</script>
<input type="text" id="real" onkeyup="blank()" placeholder="tempo"/><br>
</html>

Copy text of a field into another automatically

I need to copy the text entered in a field (whether it was typed in, pasted or from browser auto-filler) and paste it in another field either at the same time or as soon as the user changes to another field.
If the user deletes the text in field_1, it should also get automatically deleted in field_2.
I've tried this but it doesn't work:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
var box1 = document.getElementById('field_1');
var box2 = document.getElementById('field_2');
box2.value = box1.value;
}
});
</script>
Any ideas?
You are almost there... The function is correct, you just have to assign it to the change event of the input:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
//Since you have JQuery, why aren't you using it?
var box1 = $('#field_1');
var box2 = $('#field_2');
box2.val(box1.val());
}
$('#field_1').on('change', onchange);
});
$(document).ready(function() {
$('.textBox1').on('change', function() {
$('.textBox2').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="textBox1"/>
<input type="text" class="textBox2"/>
If you are using jQuery, it is very easy - you need just register the right function on the right event :)
Here's the code:
<input id="foo" />
<input id="bar" />
$(function(){
var $foo = $('#foo');
var $bar = $('#bar');
function onChange() {
$bar.val($foo.val());
};
$('#foo')
.change(onChange)
.keyup(onChange);
});
JSFiddle: http://jsfiddle.net/6khr8e2b/
Call onchange() method on the first element onblur
<input type="text" id="field_1" onblur="onchange()"/>
try with keyup event
<input type="text" id="box_1"/>
<input type="text" id="box_2"/>
$('#box_1').keyup(function(){
$('#box_2').val($(this).val());
})
Try something like:
$(document).ready(function () {
$('#field_1').on('change', function (e) {
$('#field_2').val($('#field_1').val());
});
});
Heres a fiddle: http://jsfiddle.net/otwk92gp/
You need to bind the first input to an event. Something like this would work:
$(document).ready(function(){
$("#a").change(function(){
var a = $("#a").val();
$("#b").val(a);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="a" />
<input type="text" id="b" />
If you want that the value of the second field is updated as the same time that the first one, you could handle this with a timeout.
Each time a key is pressed, it will execute the checkValue function on the next stack of the execution. So the value of the field1 in the DOM will already be updated when this function is called.
var $field1 = $("#field_1");
var $field2 = $("#field_2");
$field1.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $field2.val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$field2.val(v1);
v2 = v1;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="field_1" value=""/><br/>
<input id="field_2" value=""/>

Get the value of checked checkbox?

So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.

How could I change the buttonname and the variable value?

How could I write this in javascript or jQuery:
When I push the button the first time the onoff var in the change function gets the value off and the off button changes to a button named on;
now when I press the on button the var onoff gets the value on and the button changes to an off button again.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="jquery-min.js"></script>
<script type="text/javascript">
function change( inputId ) {
/* ... do something with inputId ... */
var onoff = 'off';
console.log( onoff );
}
</script>
</head>
<body>
<form>
<table>
<tr>
<td>one:</td><td><input name="one" id="one" /></td>
<td><input type="button" id="b_one" value="off" onclick="change('one')"></td>
</tr>
<tr>
<td>two:</td><td><input name="two" id="two" /></td>
<td><input type="button" id="b_two" value="off" onclick="change('two')"></td>
</tr>
</table>
<br /><br /><input type="submit" value="ok"/></div><br />
</form>
</body>
</html>
This is in "pure" JavaScript. You will retrieve the button elements for given input and change its value based on the previous value.
function change( inputId ) {
var button = document.getElementById('b_' + inputId);
button.value = button.value === 'off' ? 'on' : 'off';
}
HERE is the code.
Your change() function won't work because 'off' is assigned to onoff variable everytime the function is called. You have to move the variable definition outside the change() function if you want to use it.
I'm not sure that's a valid use of value. However, something like this:
function Change(id) {
if( $("#"+id).val() == "on") {
// code for on
$("#"+id).val("off"); //switch value
}
else {
// code for off
$("#"+id).val("on"); //switch value
}
}
HTML
<input type="button" id="btnOn" value="Off" />
Javascript
var status = "off"
$("#btnOn").click(function () {
if ($(this).val() == "On") {
$(this).val("Off")
status = "Off";
}
else {
$(this).val("On")
status = "On";
}
alert("status : " + status);
});
Here is the sample : http://jsfiddle.net/JCABs
You can set event handlers without adding inline code:
$('input[type="button"]').on('click', function () {
var onoff = this.value;
//this sets the value of the input to its current opposite
this.value = (this.value == 'off') ? 'on' : 'off';
});
Here is a demo: http://jsfiddle.net/df4pu/
This also sets event handlers for every type=button input so you can reduce the repetitious code.
Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().

Categories