In this code, I have two elements; an input box with id 'alpha' and a paragraph with id 'bravo'. What I'm trying to do is make bravo invisible when there is nothing in the input box alpha.
Here is what I have so far:
<html>
<head>
<script>
var a = document.getElementById("alpha");
var b = document.getElementById("bravo");
window.onload = function hidebravo() {
if (a.value == nil) {b.style.visibility = "hidden";}
}
a.onchange = function hidebravo() {
if (a.value == nil) {b.style.visibility = "hidden";}
}
</script>
</head>
<body>
<input id="alpha"/>
<p id="bravo">Hello!</p>
</body>
</html>
For sake of clarity, I have set the variables 'a' and 'b' to correspond to the JS selectors for the input box and the paragraph, respectively.
Now, as soon as the window is loaded I call the function 'hidebravo()' which is the function that makes bravo invisible if input box alpha is empty. I call the same function whenever the user changes the value of alpha, in case alpha contains a value which the user then deletes and it becomes empty once again.
But, for whatever reason, this isn't working as it should and I can't figure out why.
Please help!
You should use null instead of nil in Javascript.
Here's the code that works, without window.onload function:
JS:
function reloadBravo() {
var bravoParagraph = document.getElementById('bravo');
var alphaTextBox = document.getElementById('alpha');
var alphaText = alphaTextBox.value;
if (alphaText.length > 0) {
bravoParagraph.innerHTML = alphaText;
bravoParagraph.style.visibility = 'visible';
} else {
bravoParagraph.innerHTML = '';
bravoParagraph.style.visibility = 'hidden';
}
}
HTML:
<html>
<head>
</head>
<body>
<input id="alpha" onkeyup="reloadBravo()"/>
<p id="bravo"></p>
</body>
</html>
This help you :
<html>
<head>
</head>
<body>
<input id="alpha"/>
<p id="bravo">Hello!</p>
<script>
var a = document.getElementById("alpha");
var b = document.getElementById("bravo");
window.onload = function hidebravo() {
if (a.value == "")
b.style.visibility = "hidden";
else
b.style.visibility = "visible";
}
a.oninput = function hidebravo() {
if (a.value == "")
b.style.visibility = "hidden";
else
b.style.visibility = "visible";
}
</script>
</body>
</html>
JavaScript doesn't have special nil value. There is null. But the .value property of the HTMLInputElement is a DOMString and can't be null. You need to check the .length property of the DOMString. length of 0 indicates that there is no set value.
if (a.value.length === 0) { ... }
Note that as an space and a tab is considered a character, you need to trim the value for checking whether user has typed any visible characters or not:
if (a.value.trim().length === 0) { ... }
But that's not the only problem. load event is fired once and your code doesn't check the current value of the inputs. You should add an event handler for keyup/input/change/paste/... events fired for the input elements.
a.addEventListener('keyup', hidebravo);
b.addEventListener('keyup', hidebravo);
Related
I have a div and it has some elements inside it. What I want to achieve is when a user double clicks an element inside the div, it sets itself as contentEditable. For example: if a user double clicks on a p tag, it becomes editable and as soon as he clicks anywhere outside that tag, it sets contentEditable to false
But what's happening is that when I double click the p tag, it does becomes editable but when I click anywhere outside that element, it doesn't set itself to false and it only sets itself to false when I click on the same p tag again. Which is very strange. What am I doing wrong here?
Here's my code:
<html>
<body>
<div id="zzz">
<h1>Welcome</h1>
<p>this is the text</p>
<button>click me</button>
<u>yo</u>
</div>
</body>
<script>
let arr = [];
let myiframe = document.getElementById("zzz");
myiframe.addEventListener("click", function (e) {
obj = e.target;
arr.push(obj);
console.log(arr);
if (arr.length > 2) {
arr.shift();
}
if (arr[0] == arr[1]) {
console.log("same");
} else {
console.log("different");
obj.contentEditable = "false";
}
if (event.detail === 2) {
obj.contentEditable = "true";
obj.focus();
}
});
</script>
</html>
I think you only need to store a single element in memory, which is the last editable element. I used .setAttribute and got it working
let arr = [];
let myiframe = document.getElementById("zzz");
let activeElement = null
myiframe.addEventListener("click", function(e) {
obj = e.target;
//console.log(activeElement)
if (activeElement && activeElement !== obj) {
activeElement.setAttribute('contenteditable', 'false');
}
if (event.detail === 2) {
obj.setAttribute('contenteditable', 'true');
activeElement = obj
obj.focus();
}
});
<div id="zzz">
<h1>Welcome</h1>
<p>this is the text</p>
<button>click me</button>
<u>yo</u>
</div>
If you change obj.contentEditable = "false"; to arr[0].contentEditable = "false" then upon a click it would check if the elements match and if they don't it would disable the elements property.
e.target is the element you clicked on, so when you click on an element and modify obj.contentEditable you’re only ever modifying that element’s contentEditable property.
I have this section of javascript in my html that grabs a form input, puts it through a function and returns a json. I then want to either hide or show certain form elements based on the values in this json.
At the moment, i can do all of this fine except for changing the style.display properties of the elements im trying to hide/show, i can find them okay with getElementbyId (have tested this with other stuff) but the changes i make to the style don't seem to do anything.
As you can see below, i have put in a few alerts to make sure everything is working, and they all seem to align with what i need from the function. The alert showing style.display even matches up with what i'm trying to change it to, however even if it says "none", the form element still shows up.
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
)
}
</script>
Edit: i added the console.log lines in but nothing seems to show in the console.
console log image
The issue was that the page was reloading to it's original state after the script had been executed, so i stopped this by adding "; return false" after the function like so:
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
); return false
}
</script>
I am trying to make a checkbox list form with only images and
I have this code from add an image to a html type input check box or radio :
<html>
<script type="text/javascript">
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '52 0 ROff.png';
var imgTrue = '52 0 ROn.png';
//replace the checkbox with an image and setup events to handle it
function replaceChecks() {
//get all the input fields on the page
inputs = document.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i<inputs.length; i++) {
//check if the input is a checkbox
if(inputs[i].getAttribute('type') == 'checkbox') {
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].checked) {
img.src = imgTrue;
} else {
img.src = imgFalse;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set image
img.onclick = new Function('checkClick('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
}
}
}
//change the checkbox status and the replacement image
function checkClick(i) {
if(inputs[i].checked) {
inputs[i].checked = '';
document.getElementById('checkImage'+i).src=getImageUnchecked(i);
} else {
inputs[i].checked = 'checked';
document.getElementById('checkImage'+i).src=getImageChecked(i);
}
}
function getImageChecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
}
function getImageUnchecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
}
function startImages() {
}
</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>
But the images only start displaying after the first click.
Is there any work around I can do to start from the page load ?
I tried with the existing functions but achieved nothing.
you have attached the checkClick() to click event of images but you never actually load the images initially, so for that you will have to call checkClick(i) from for loop.
<html>
<script type="text/javascript">
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '52 0 ROff.png';
var imgTrue = '52 0 ROn.png';
//replace the checkbox with an image and setup events to handle it
function replaceChecks() {
//get all the input fields on the page
inputs = document.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i<inputs.length; i++) {
//check if the input is a checkbox
if(inputs[i].getAttribute('type') == 'checkbox') {
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].checked) {
img.src = imgTrue;
} else {
img.src = imgFalse;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set image
img.onclick = new Function('checkClick('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
checkClick(i);
}
}
}
//change the checkbox status and the replacement image
function checkClick(i) {
if(inputs[i].checked) {
inputs[i].checked = '';
document.getElementById('checkImage'+i).src=getImageUnchecked(i);
} else {
inputs[i].checked = 'checked';
document.getElementById('checkImage'+i).src=getImageChecked(i);
}
}
function getImageChecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
}
function getImageUnchecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
}
function startImages() {
}
</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>
You have a tremendous amount of unnecessary code and were setting initial image values to images that don't exist.
Also, your HTML was not valid (the <html> closing tag must be the last thing in the document).
Additionally, you should not use inline HTML event attributes (onclick, etc.) and instead completely separate your JavaScript from your HTML and follow modern, standards-based coding practices.
Also, unless you expect your HTML to have to be parsed as XML at some point (highly unlikely), you can omit the last slashes in your elements (<input ... /> can just be <input ... >). Along the same lines, you no longer need to specify type="text/javascript" in your script tags.
Below is a cleaned up and modernized working version of your code. Note how much less code there actually is (without the comments, it's really very little code) and how much simpler that code is. Please review the comments in the code for details on what is being done and why.
.hidden { display:none; }
<html>
<head>
<title>Checkbox and Images</title>
</head>
<body>
<input type="checkbox" id="option1" checked> Test<br>
<input type="checkbox" id="option2" checked> two<br>
<button id="btnOutput">Check</button>
<script>
// You should never make global variables as they can collide with other variables
// Instead, create a "scope" of your own to work in with an Immediately Invoked
// function expression (an unnamed function that invokes itself right after being
// declared)
(function(){
// Anything declared inside this function is not accessible outside of it
// Since we know these are the only two image paths needed, we can set them up as
// variables and completely do away with the extra functions that set them.
var imgFalse = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
var imgTrue = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
// Get references to all the DOM elements you will need and then you don't
// have to scan for them again over and over.
var btnOutput = document.getElementById("btnOutput");
// .getElementsByTagName() returns a "live node" list that causes the DOM
// to be re-scanned for the elements everytime you reference the list.
// Use .querySelectorAll() for better efficiency and turn the node list that
// returns into a proper JavaScript array so that .forEach() can be used to
// iterate the elements later.
var checkboxes =
Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]'));
// Set up the click event handling function for the button
btnOutput.addEventListener("click", function(){
alert('option 1 is checked? ' + checkboxes[0].checked +
'option 2 is checked? ' + checkboxes[1].checked);
});
// Loop through the checkboxes array
checkboxes.forEach(function(checkbox, index){
// No need to test the input type because this array only contains checkboxes
// create a new image
var img = document.createElement('img');
// Show the right image based on the checked status of the clicked checkbox
if(checkbox.checked) {
img.src = imgTrue;
} else {
img.src = imgFalse;
}
img.id = 'checkImage' + index; // set image ID
img.checked = false;
// Set up image click event handler
img.addEventListener("click", function(){
// Toggle the checked state of the image.
// In JavaScript, the "checked" property is boolean. It has values of true and false,
// not "checked" and "" (those are the values to use in HTML attributes).
this.checked = !this.checked;
if(this.checked) {
img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
} else {
img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
}
});
// place image just prior to the checkbox in the DOM
checkbox.parentNode.insertBefore(img, checkbox);
// Hide the checkbox. Use CSS classes instead of inline styles
checkbox.classList.add("hidden");
});
})();
</script>
</body>
</html>
I have this script that is supposed to change the text of the button when the button is clicked.
<body>
<button onclick="toggleText(this);" id="id">Edit</button>
</body>
function toggleText(element){
var text = document.getElementById(element.id).textContent;
if (text == 'Edit') {
text = 'Done';
} else {
text = 'Edit';
}
}
But it doesn't work. It only works when you put document.getElementById(element.id).textContent directly into the if statements.
How do I get the variable to store properly?
Since you already get the element, you don't need to get it again. You can just use element.
But the reason why you can't change it is that you're only changing the variable that contains the text. It does not point to the element's properties. You need to use this:
function toggleText(element){
var text = element.textContent;
if (text == 'Edit') {
element.textContent = 'Done';
} else {
element.textContent = 'Edit';
}
}
When you access document.getElementById(element.id).textContent you get the value of it, not the reference. So changes to it won't affect the element.
But when you assign element to variable, it gets reference to it.
var element = document.getElementById(element.id);
if (element.textContent == 'Edit') {
element.textContent = 'Done';
} else {
element.textContent = 'Edit';
}
Just use:
index.js
var mainText = document.getElementById("mainText").value;
document.write(mainText);
index.html
<textarea id="mainText"></textarea>
As tymeJV commented, you can store by reference the element you get by id. Its property is stored by value. Instead store the element in a variable and access its property from the variable.
var text = document.getElementById(element.id);
if (text.textContent == 'Edit') {
text.textContent = 'Done';
} else {
text.textContent = 'Edit';
}
Is jquery an option ?
I used to do something like :
var a = $('#theid');
A.something
I need to have a number that's displayed on a web page that will increase or decrease when the up or down arrow keys are pressed. I found/massaged together javascript file to do this but I can't seem to get it to work with my HTML. I was trying to link it to a html textbox but it would not work.
if someone could help me with the HTML to get this working that would be great.
var setTimeoutId;
var keyIs = "up";
function myIncrementFunction()
{
var num = parseFloat(myText.value)+1;
myText.value = num;
}
myText.onkeydown = function(e)
{
keyIs = "down";
if(keyIs == "down")
{
var e = e || event ;
if (e.keyCode == 38)
{
for(var s=0; s<1; s++)
setTimeoutId = setTimeout('myIncrementFunction()',100);
}
}
}
myText.onkeyup = function(e)
{
keyIs = "up";
}
Tried this and it still is not working.. > ?
number.html
<html>
<head>
<script type="text/javascript" src="number.js"></script>
</head>
<body>
<input type="text" id="myText" />
</body>
</html>
number.js
var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
// "38" is the up arrow key
if (e.keyCode == 38) {
// increment the value in the text input
myText.value++;
// "40" is the down arrow key
} else if (e.keyCode == 40) {
// decrement the value in the text input
myText.value--;
}
}
I don't understand why it works in the example posted and when I save my files and open it in the browser it will not work!
I'm on OSX Lion using Chrome/Safari
It looks like there are a couple of things going on. First, as jayp points out in his comment, you aren't defining what myText is.
Secondly, I think you're over-complicating this a bit. How about trying something like this:
Give your text input an ID, something like <input type="text" id="myText" />
Then use something like this:
// Assign our text input to a variable
var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
// "38" is the up arrow key
if (e.keyCode == 38) {
// increment the value in the text input
myText.value++;
// "40" is the down arrow key
} else if (e.keyCode == 40) {
// decrement the value in the text input
myText.value--;
}
}
This is a pretty simplified example, but should get you pointed in the right direction. Hope it helps.
See a working example at JSFiddle
Edit:
It's not working in your case because the script is trying to find the input element before the page is fully loaded. You can move your script to the bottom of the page like this:
<html>
<head></head>
<body>
<input type="text" id="myText" />
<script type="text/javascript" src="number.js"></script>
</body>
</html>
In your number.js, you are increasing the value of the text field, but you have no value originally set, therefore there is nothing to increase.
Try editing your HTML so that you have:
<input type="text" id="myText" value="" />
There's a small jQuery plugin for doing this: https://github.com/nakupanda/number-updown
Usages:
$('#textInput').updown();
View live demo here: http://jsfiddle.net/XCtaH/embedded/result/
Keyboard and mousewheel events supported