I'm trying to create a site settings page with some checkboxes. If the checkbox is 'ON' a HTML element has a certain value, else it would be something else. But for some reason every checkbox keeps returning the value "on" in JavaScript. Please help.
My HTML:
<p>Click this checkbox</p>
<input type='checkbox' id='theBOX' checked='checked'>
<button onclick='theFunction'>Apply Changes</button>
<!-- Div that has to be toggled -->
<p id='TXT'></p>
My JavaScript:
function theFunction() {
var valueOfCheckBox = document.getElementById('theBOX').value;
if (valueOfCheckBox == 'on') {
document.getElementById('TXT').innerHTML = 'ON';
} else {
document.getElementById('TXT').innerHTML += 'OFF';
}
}
your check boxes are checked by default. remove checked=checked from check box input
<input type='checkbox' id='theBOX'>
and yes you have to change the Javascript function to check whether check box has been checked or not
you can get the valueOfCheckBox to be true if the check box is checked otherwise it will be false
var valueOfCheckBox = document.getElementById('theBOX').checked;
function theFunction() {
var valueOfCheckBox = document.getElementById('theBOX').checked;
if (valueOfCheckBox) {
document.getElementById('TXT').innerHTML = 'ON';
} else {
document.getElementById('TXT').innerHTML += 'OFF';
}
}
You should remove the 'checked' attribute from your input tag
<input type='checkbox' id='theBOX' >
function theFunction() {
var valueOfCheckBox = document.getElementById('theBOX').value;
if (valueOfCheckBox == 'on') {
document.getElementById('TXT').innerHTML = 'ON';
} else {
document.getElementById('TXT').innerHTML += 'OFF';
}
}
<p>Click this checkbox</p>
<input type='checkbox' id='theBOX'>
<button onclick='theFunction'>Apply Changes</button>
<!-- Div that has to be toggled -->
<p id='TXT'></p>
You have multiple issues :
1 - You forgot the parentheses on the js function call :
<button onclick='theFunction()'>Apply Changes</button>
2 - When you set your js var with the value, or we dont need it. Just put this :
var valueOfCheckBox = document.getElementById('theBOX');
3 - Then to know wether it is check or not, use the js .checked property as following :
if (valueOfCheckBox.checked == true) {
document.getElementById('TXT').innerHTML = 'ON';
} else {
document.getElementById('TXT').innerHTML += 'OFF';
}
Finally, your code should look like this :
<p>Click this checkbox</p>
<input type='checkbox' id='theBOX' checked='checked'>
<button onclick='theFunction()'>Apply Changes</button>
<!-- Div that has to be toggled -->
<p id='TXT'></p>
<script type="text/javascript">
function theFunction() {
var valueOfCheckBox = document.getElementById('theBOX');
if (valueOfCheckBox.checked == true) {
document.getElementById('TXT').innerHTML = 'ON';
} else {
document.getElementById('TXT').innerHTML += 'OFF';
}
}
</script>
You can use .checked property. This property returns true if the checkbox is checked by default, otherwise it returns false.
If you want by default checked on input box, just add checked attribute in input tag.
<input type="checkbox" id="theBOX" checked>
Hope this may help you.
<head>
<script>
function theFunction() {
var valueOfCheckBox = document.getElementById('theBOX').checked;
if (valueOfCheckBox) {
document.getElementById('TXT').innerHTML = 'ON';
} else {
document.getElementById('TXT').innerHTML = 'OFF';
}
}
</script>
</head>
<body>
<p>Click this checkbox</p>
<input type='checkbox' id='theBOX'>
<button onclick='theFunction()'>Apply Changes</button>
<!-- Div that has to be toggled -->
<p id='TXT'></p>
</body>
</html>
This will work.
function theFunction() {
var valueOfCheckBox = document.getElementById('theBOX');
if (valueOfCheckBox.checked) {
document.getElementById('TXT').innerHTML = 'ON';
} else {
document.getElementById('TXT').innerHTML = 'OFF';
}
}
<p>Click this checkbox</p>
<input type='checkbox' id='theBOX' checked />
<button onclick='theFunction()'>Apply Changes</button>
<!-- Div that has to be toggled -->
<p id='TXT'></p>
I would recommend you to use<label for="checkbox">Click this checkbox</label> instead of <p>Click this checkbox</p>.
Related
I am trying to disable/enable an input line by clicking a button
I can manually enter the word "closed" in an input line and it works fine, but I can not get the "closed" to get entered with a button
var obj = document.getElementById("state");
obj.onchange = function(status){
if(this.value=="closed"){
document.getElementById("test").disabled = 'disabled';
}else{
document.getElementById("test").disabled = '';
}
}
<button id="state" name="state" type="submit" value="open">open</button>
<button id="state" name="state" type="submit" value="closed">closed</button>
<input id="test"/>
The input id=state line works fine, but nothing happens when I click the buttons
There is a few things to consider :
You can’t use multiple times the same ID (state)
A button won’t react to a onChange, but a onClick
You can directly use the onClick HTML attribute
function disableInput(disabled){
document.getElementById("test").disabled = disabled
}
<button onClick="disableInput(false)">open</button>
<button onClick="disableInput(true)">closed</button>
<input id="test" />
Perhaps you want a toggle?
window.addEventListener("load", function() {
document.getElementById("state").addEventListener("click", function(e) {
e.preventDefault(); // not really needed on type="button"
var closed = this.value == "closed";
this.value = this.innerText = closed ? "open" : "closed";
document.getElementById("test").disabled = closed;
})
})
<button id="state" name="state" type="button" value="open">open</button>
<input id="test" />
Try something like this,
var buttonClick = function(status) {
if (status == "closed") {
document.getElementById("test").disabled = true;
} else {
document.getElementById("test").disabled = false;
}
}
<button id="openState" name="OpenState" type="submit" value="open" onclick="buttonClick(value)">open</button>
<button id="closedState" name="ClosedState" type="submit" value="closed" onclick="buttonClick(value)">closed</button>
<input id="test" />
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a it displays for a split second and goes away. Please help
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>game</title>
<style>
</style>
</head>
<body>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
/*var input;
var room;
function submitFunction() {
alert("hello")
}
*/
</script>
<script type="text/javascript">
var input;
var room;
room = "Main Enterence"
$(document).ready(function () {
$("#mainForm").submit(function() {
input = document.getElementById("textInput").value;
if (input == "east") {
if (room == "Main Enterence") {
room = "Bedroom"
enterBedroom();
}
}
if (input == "west") {
}
if (input == "north") {
}
if (input == "south") {
}
})
})
function enterBedroom() {
$( "#consoleOutput" ).append( "<p>Test</p>" );
}
</script>
<div id="consoleOutput">
<p id="welcomeText"></p>
</div>
<form onsubmit="submitFunction()" id="mainForm">
<input type="text" id="textInput">
<input type="submit" name="sumbit">
</form>
</body>
</html>
Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a it displays for a split second and goes away. Please help
This happens, because the page is refreshed - you submit form. You have to add first parametr to submit event and use preventDefault() function on it
$("#mainForm").submit(function(event) {
event.preventDefault();
});
Error:
There are two functions invoked during submit of the form...
When you need page not to refresh then don't use submit without preventing the default event...
Solution:
var input;
var room;
room = "Main Enterence";
$("#mainForm").click(function() {
input = document.getElementById("textInput").value;
if (input == "east") {
if (room == "Main Enterence") {
room = "Bedroom"
$("#consoleOutput").append( "<p>Test</p>" );
}
}
if (input == "west") {
}
if (input == "north") {
}
if (input == "south") {
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="consoleOutput">
<p id="welcomeText"></p>
</div>
<form id="mainForm">
<input type="text" id="textInput">
<input type="button" value="submit" name="submit">
</form>
It clears because you are using submit which will cause the page to reload/refresh. Change that to click
your html button:
<input type="button" name="sumbit" id="submit" value="submit">
your js:
$(document).ready(function () {
$("#submit").click(function() {
.
.
.
I am new to programming. Every time I run this code, nothing happens. Can you please tell me why this is?
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<script type="text/javascript">
var x = 0
document.write(x)
function button1() {
document.write(x++)
}
function button2(){
document.write(x--)
}
</script>
</body>
The problem is that you put ++ and -- after the variable, meaning that it will increment/decrement the variable after printing it. Try putting it before the variable, like below.
Also, as mentioned, you have some trouble with document.write(). Consider the following documentation from the W3Schools page:
The write() method writes HTML expressions or JavaScript code to a
document.
The write() method is mostly used for testing. If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Thus, document.write() will remove all your existing content as soon as you click on a button. If you want to write to the document, use an element's .innerHTML like this:
var x = 0;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
document.getElementById('output-area').innerHTML = --x;
}
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>
Why don't you change your code a bit? Instead of document.write(x++) and document.write(x--) use document.write(++x) and document.write(--x).
The document.write is the problem. It only works before the browser is done loading the page completely. After that, document.write doesn't work. It just deletes all of the existing page contents.
Your first document.write is executed before you the page has loaded completely. This is why you should see the 0 next to the two buttons.
Then however, the page has loaded. Clicking on a button causes the event handler to be executed, so document.write will be called, which doesn't work at that point, because the page already has loaded completely.
document.write shouldn't be used anymore. There are many modern ways of updating the DOM. In this case, it would create a <span> element and update it's content using textContent.
Moreover, use addEventListener instead of inline event listeners:
var x = 0;
var span = document.querySelector('span'); // find the <span> element in the DOM
var increment = document.getElementById('increment'); // find the element with the ID 'increment'
var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'
increment.addEventListener('click', function () {
// this function is executed whenever the user clicks the increment button
span.textContent = x++;
});
decrement.addEventListener('click', function () {
// this function is executed whenever the user clicks the decrement button
span.textContent = x--;
});
<button id="increment">increment</button>
<button id="decrement">decrement</button>
<span>0</span>
As others have mentioned, the first x++ won't have a visible effect, because the value of x is incremented after the content of the <span> is updated. But that wasn't not your original problem.
document write will delete full html:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
As in w3schools
try this instead
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<div id="value"></div>
<script type="text/javascript">
var x=0
var element = document.getElementById("value");
element.innerHTML = x;
function button1(){
element.innerHTML = ++x;
}
function button2(){
element.innerHTML = --x;
}
</script>
I changed the x-- and x++ to ++x and --x so the changes are immediatly. With this change your code would have worked aswell. showing 1 or -1.
HTML code for UI
<div class="card">
<div class="card-body">
<h5 class="card-title">How many guests can stay?</h5>
<div class="row">
<ul class="guestCounter">
<li data-btn-type="increment"><span class="romoveBtn"><i class="fa fa-plus"></i></span> </li>
<li class="counterText"><input type="text" name="guestCount" id="btnGuestCount" value="1" disabled /> </li>
<li data-btn-type="decrement"><span class="romoveBtn"><i class="fa fa-minus"></i></span></li>
</ul>
</div>
Java Script:
// set event for guest counter
$(".guestCounter li").on("click", function (element) {
var operationType = $(this).attr("data-btn-type");
//console.log(operationType);
var oldValue = $(this).parent().find("input").val();
//console.log(oldValue);
let newVal;
if (operationType == "increment") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$(this).parent().find("input").val(newVal);
});
var x = 1;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
if(x <= 0 ){
alert(' minimum value 0 // By Khaydarov Marufjon marvell_it academy uzb ')
return false ;
}
document.getElementById('output-area').innerHTML = --x;
}
input{
width: 70px;
background-color: transparent;
padding: 20px;
text-align: center;
}
button{
padding: 20px;
}
<input type='button' value="plus" onclick="button1()" />
<span id="output-area"></span>
<input type='button' value="minus" onclick="button2()" />
This question is very common. I have developed a solution with Bootstrap and pure JavaScript in another very similar thread here.
There is autoincrement input on keeping button pressed down.
Use ontouchstart and ontouchend instead than onmousedown and onmouseup method for mobile. To make it work for both mobile and desktop browser without headache use onpointerdown, onpointerup, onpointerleave
https://stackoverflow.com/a/70957862/13795525
function imposeMinMax(el) {
if (el.value != '') {
if (parseInt(el.value) < parseInt(el.min)) {
el.value = el.min;
}
if (parseInt(el.value) > parseInt(el.max)) {
el.value = el.max;
}
}
}
var index = 0;
var interval;
var timeout;
var stopFlag=false;
function clearAll(){
clearTimeout(timeout);
clearInterval(interval);
}
function modIn(el) {
var inId = el.id;
if (inId.charAt(0) == 'p') {
var targetId = inId.charAt(2);
var maxValue = Number(document.getElementById(targetId).max);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue < maxValue){
stopFlag=false;
document.getElementById(targetId).value++;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index+1 >= maxValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value++;
}
index++;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
if (inId.charAt(0) == 'm') {
var targetId = inId.charAt(2);
var minValue = Number(document.getElementById(targetId).min);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue > minValue){
stopFlag=false;
document.getElementById(targetId).value--;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index-1 <= minValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value--;
}
index--;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Button example</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<button type='button' class='btn btn-danger btn-sm ' id='mbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='A' onchange='imposeMinMax(this)' value='200' max='350' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='B' onchange='imposeMinMax(this)' value='250' max='450' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='C' onchange='imposeMinMax(this)' value='3' max='10' min='1' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
</body>
</html>
When the value in the "tds" field range between 1 to 10 below then the input "TAN" has appeared else it should in should not appear(hidden state)
<input id="tds" type="text" onchange="myFunction()"/>
<input id="myP" name="TAN" style="visibility:hidden;" value="test"/>
<script>
function myFunction() {
tdsvalue = document.getElementById('tds').value;
if (tdsvalue <= 10){
document.getElementById("myP").style.visibility = "";
else
}
}
</script>
Set visibility to visible, not ""
And your code should look like this
<input id="tds" type="text" onchange="myFunction()"/>
<input id="myP" name="TAN" style="visibility:hidden;" value="test"/>
<script>
function myFunction() {
tdsvalue = document.getElementById('tds').value;
if (tdsvalue <= 10) {
document.getElementById("myP").style.visibility = "visible";
}
else {
document.getElementById("myP").style.visibility = "hidden";
}
}
</script>
Note : You can also use display:block to show and display:none to hide.
display:none will not be available in the page and does not occupy any space. visibility:hidden hides an element, but it will still take up the same space as before. The element will be hidden, but still affect the layout.
Try the following code i.e. improved version of yours:
<input id="tds" type="text" onkeyup="myFunction(this)"/>
<input id="myP" name="TAN" style="display:none;" value="test"/>
<script>
function myFunction(el) {
var tdsvalue = el.value;
if (tdsvalue >= 1 && tdsvalue <=10){
document.getElementById("myP").style.display= "block";
} else {
document.getElementById("myP").style.display= "none";
}
}
</script>
It appears you have a syntax error caused by else.
I would also recommend you parse the value as an integer using parseInt()
function myFunction() {
var tdsvalue = parseInt(document.getElementById('tds').value);
if (tdsvalue <= 10) {
document.getElementById("myP").style.visibility = "visible";
} else {
document.getElementById("myP").style.visibility = "hidden";
}
}
<input id="tds" type="text" onchange="myFunction()" />
<input id="myP" name="TAN" style="visibility:hidden;" value="test" />
If you have any questions about the source code above please leave a comment below and I will reply as soon as possible.
I hope this helps. Happy coding!
this is a sample code of what I am doing. unfortunately the alert(nextElem.value) returns "undefined" when I click the second checkbox to get the href of the link after it. do you have any idea how to fix it?
<HTML>
<HEAD>
<TITLE>Checkbox Inspector</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function validate()
{
for (i = 0; i <(document.f1.checkThis.length) ; i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem.href);
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="f1">
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate()">Check here<BR>
click here
</FORM>
</BODY>
</HTML>
Get the link's href with jQuery
http://jsfiddle.net/mplungjan/H9Raz/ :
$('form input:checkbox').click(function () {
alert($(this).nextAll('a').attr("href"));
});
Because of the BRs we need the nextAll, surprisingly since I was using the next selector with an "a"
See here why it did not work: Cleanest way to get the next sibling in jQuery
Get the link's href with forms access and usage of ID - no jQuery
http://jsfiddle.net/mplungjan/fKE3v/
window.onload=function() {
var chks = document.getElementsByName('checkThis');
for (var i=0;i<chks.length;i++) {
chks[i].onclick=function() {
var id = this.id;
var linkId="link_"+id.split("_")[1]
alert(document.getElementById(linkId).href)
}
}
}
<form>
<div>
<input type="checkbox" name="checkThis" id="chk_1" value="http://www.google.com" />Check here<br/>
click here<br>
<input type="checkbox" name="checkThis" id="chk_2" value="http://www.bing.com" />Check here<br/>
click here
</div>
</form>
Forms access to get the next checkbox
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate(this.form)">Check here<BR>
<INPUT TYPE="checkbox" NAME="checkThis" onClick="validate(this.form)">Check here2<BR>
function validate(theForm) {
var chk = theForm.checkThis
for (i = 0; i <chk.length) ; i++) {
if (chk[i].checked) {
var nextElem = chk[i+1];
if (nextElem) alert(nextElem.value);
}
}
}
Your problem is that nextElem is the text node immediately after your checkbox, not the next checkbox; text nodes don't have value attributes. For example, try this:
function validate() {
for (i = 0; i < (document.f1.checkThis.length); i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem);
alert(nextElem.value);
}
}
}
Or, for your convenience:
http://jsfiddle.net/ambiguous/sUzBL/1/