This is the current code I have
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body>
Active
Inactive
Banned
<input type="text">
</body>
</html>
What I want to do is when I click on active, the textbox will have the word active and so on. Is there a way to do this?
You can do this using jquery:
$(document).ready(function() {
$('a').click(function(e) {
e.preventDefault();
var text = $(this).text();
$('input[type=text]').val(text);
});
});
In pure javascript you could do this:
html - I would suggest adding an id to the input
<body>
Active
Inactive
Banned
<input id="foo" type="text">
</body>
javascript
var links = document.querySelectorAll( 'a' );
var input = document.getElementById('foo');
function setInput(event) {
event.preventDefault();
input.value = event.target.innerHTML;
};
for( var i=links.length; i--; ) {
links[i].addEventListener( 'click', setInput, false );
};
And without JQuery just in case someone wants it :
http://jsfiddle.net/s0ds5rdy/
I recommend putting "#" in the href attribute. It'll scroll to the top of the page if you don't preventDefault, while browsers might reload the page if you click on a blank link.
window.addEventListener("load", function () {
var allLinks = document.getElementsByTagName("a");
for (var i = 0; i < allLinks.length; ++i) {
allLinks[i].addEventListener("click", function (e) {
e.preventDefault();
document.querySelector('input[type=text]').value = e.target.innerHTML;
});
}
});
Related
I need to change text each time I click on button.
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("data-text") == button.innerHTML) {
button.innerHTML = button.getAttribute("data-text1");
} else {
button.setAttribute("data-text1", button.innerHTML);
button.innerHTML = button.getAttribute("data-text");
}
},
false
);
<div>
<button id="changeText" data-text="Show" data-text1="Hide">Hide</button>
</div>
I don't understand why this code doesn't work when I try to load page using google chrome. However when I loaded it to codepen it worked
It expects from you certain structure like this one:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText" text="Show" >Hide</button>
</div>
<script>
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("text") == button.innerHTML) {
button.innerHTML = button.getAttribute("text1");
} else {
button.setAttribute("text1", button.innerHTML);
button.innerHTML = button.getAttribute("text");
}
},
false
);
</script>
</body>
</html>
Copy paste it to your file and you'll see that it works.
Please mark it as an answer if it fixes your problem :)
Your code is working, but your approach is not so nice. See the 2 options down below.
let text = {
'Hide': 'Show',
'Show': 'Hide'
}
const click = (event) => {
// option 1, it needs the object above.
// It's good for multiple alternatiosn like color, icon etc
// or multiple states like hide to show, show to sure, sure to really, really to hide.
event.target.innerText = text[event.target.innerText];
// option 2, it's good for one or two alternations.
// event.target.innerText = event.target.innerText == 'Hide' ? 'Show' : 'Hide'
}
document.querySelector('button').addEventListener('click', click);
<button>Show</button>
you can make it more simple by removing the custom attribute and use the button innerHTML only along with enum by using Object.freeze(),it will make the code more readable
const titleEnum = Object.freeze({show: "SHOW", hide: "HIDE"});
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.innerHTML === titleEnum.hide) {
button.innerHTML = titleEnum.show;
} else {
button.innerHTML = titleEnum.hide;
}
},
false
);
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText">HIDE</button>
</div>
</body>
</html>
Use innerText to get the value of an element
const changeBtn = document.getElementById("changeText");
changeBtn.addEventListener("click", ()=>{
if(changeBtn.innerText === "2"){
changeBtn.innerText = "1";
}
else{
changeBtn.innerText= "2";
}
});
<div>
<button id="changeText">1</button>
</div>
I am making a to-do list application. You enter an item. It gets appended to the list. On clicking the item on the list, it gets crossed. Can't make the text clickable and thus can't add the classList.toggle() function to cross the item from the list.
I've tried to create an empty "li" element to which an "a" element is created inside it. (Note: all this happens when we add the item to the list). I thought, using the "a" element, I could hover over the text and thus make it clickable and connect it to the classList.toggle() function.
<html>
<head>
<style>
.done
{
text-decoration:line-through;
}
</style>
</head>
<body>
<input type="text" id="user_input">
<ul></ul>
<script>
var input = document.getElemenyById("user_input");
function addingNewList()
{
var li = document.createElement("li");
var tag = document.createElement("a");
tag.appendChild(document.createTextNode(input.value));
li.appendChild(tag);
ul.appendChild(li);
tag.onclick=tag.classList.toggle("done");
}
function input_length()
{
return input.value.length;
}
input.addEventListener("keypress",function(event)
{
if(input_length() >0 && event.which == 13)
{
addingNewList();
}
})
</script>
</body>
</html>
The expected output should be that, if the user add: "Do Laundry" to the list, It gets added to the list. On clicking "Do Laundry", there should be line through it, i.e it should be crossed. Currently, the items are getting added, but are not getting crossed. No error message is showing up either.
I have made it work very similar to the answer from Saurabh with the following:
<html>
<head>
<style>
.done
{
text-decoration:line-through;
}
</style>
</head>
<body>
<input type="text" id="user_input">
<ul id="list"></ul>
<script>
var input = document.getElementById("user_input");
function addingNewList()
{
var li = document.createElement("li");
var tag = document.createElement("a");
tag.appendChild(document.createTextNode(input.value));
var ul = document.getElementById("list");
li.appendChild(tag);
ul.appendChild(li);
tag.addEventListener("click",function()
{
toggleClass(this);
})
}
function toggleClass(e) {
e.classList.toggle("done");
}
function input_length()
{
return input.value.length;
}
input.addEventListener("keypress",function(event)
{
if(input_length() >0 && event.which == 13)
{
addingNewList();
}
})
</script>
</body>
</html>
In the above example in your question you had spelt getElementById wrong in one place and you did not define ul. I also added the toggle function to add to the click event you need to create.
While adding new li inside ul you need to bind addEventListener in new element, then on element click you need to add done class in to that element.
Try this:
<html>
<head>
<style>
.done {
text-decoration:line-through;
}
</style>
</head>
<body>
<input type="text" id="user_input">
<ul id="list"></ul>
<script>
var input = document.getElementById("user_input");
function addingNewList() {
var li = document.createElement("li");
var tag = document.createElement("a");
tag.appendChild(document.createTextNode(input.value));
li.appendChild(tag);
li.addEventListener("click", function (event) {
event.target.classList.add('done');
})
var ul = document.getElementById("list");
ul.appendChild(li);
// tag.onclick=tag.classList.toggle("done");
}
function input_length() {
return input.value.length;
}
input.addEventListener("keypress", function (event) {
if (input_length() > 0 && event.which == 13) {
addingNewList();
}
})
</script>
</body>
</html>
As I am learning javascript I was testing different things. I made a small function:
foo("div", "button");
function foo(divId, buttonId)
{
var flag = 1;
var button2;
document.getElementById(buttonId).onclick = function() {
if (flag) {
button2 = createButton("Ceaning Service");
var span = createSpan("I will be removed");
var div = document.getElementById(divId);
div.appendChild(span);
document.body.insertBefore(button1, div);
flag = 0;
}
if (!flag) {
button2.onclick = function() {
div.removeChild(span);
document.body.removeChild(button1);
flag = 1;
return;
}
}
}
}
function createButton(text)
{
var button = document.createElement("BUTTON");
button.innerHTML = text;
return button;
}
function createSpan(text)
{
var span = document.createElement("SPAN");
span.innerHTML = text;
return span;
}
I can click the second button without errors only when I click the first button Click Me once. When I click Click Me button more than once and try to click the second button, it shows div is undefined. (span is undefined too, but it won't show because browser reaches div first).
Html:
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
</head>
<body>
<button id="button">Click Me</button><br>
<div id="div"></div>
<script src="test3.js"></script>
</body>
</html>
I played around with this function and when I declare span and div before ...(buttonId).onclick =... it works.
So why this code only works when I click Click Me once? I think with the second click it cannot reference to the created elements, but not sure why.
And although it removes those elements, will they be removed by the garbage collection as well or is there some kind of a memory leak happening?
And please try not to reference jQuery or some other libraries/frameworks. It would only complicate things for me for now.
I have a div <div id="Country">India</div> . I want to execute some code (say JavaScript function) whenever the div value changes. How can I listen to changes on the div value? Do i need to use Jquery for this?
an easy jquery solution is to use a custom event and trigger it yourself when you change the DOM:
$("#country").html('Germany').trigger('CountryChanged');
$('#country').on('CountryChanged', function(event, data) {
//contentchanged
});
I have prepared a small demo for you. Its a little crude but I am sure You can improve it ;).
Happy Coding :)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#ChangeText").click(function(){
var value = $("#DivText").val();
$("#Country").text(value);
});
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
alert('Content added! Current content:' + '\n\n' + this.innerHTML);
} else {
alert('Content removed! Current content:' + '\n\n' + this.innerHTML);
}
});
});
</script>
</head>
<body >
<input type="text" id="DivText" />
<button id="ChangeText"> Change Div Text </button> <br /> <br />
<div id="Country">India</div>
</body>
</html>
You can listen to events triggered by the MutationObserver DOM API :
https://developer.mozilla.org/en/docs/Web/API/MutationObserver
Try this Demo, It's in Cracker0dks's link http://jsbin.com/ayiku and this is the code http://jsbin.com/ayiku/1/edit
Try this within script tag:
$(document).ready(function(){
var new_country1 = "";
var new_country2 = "";
var func_flag = 0;
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
new_country1 = this.innerHTML;
if(new_country1 != new_country2 && func_flag == 1) {
country_changed_function();
}
} else {
new_country2 = this.innerHTML;
}
func_flag = 1;
});
});
function country_changed_function(){
alert('country changed.');
}
Here "country_changed_function" is function trigger on country div innerHTML got changed.
Im writing a test code to do a counter that stores the value in a hidden form field. Whenever this counter is incremented with a button click, the counter value is stored in the hidden field. I have no problem with this portion.
However, im having problem to display an alert whenever the hidden field is being changed. Pls see my code below and tell me where i have gone wrong. Thank You.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
storage=document.getElementById('store').value;
alert(storage)
}
$(document).ready(function() {
var content = $('#store').val();
$('#store').change(function() {
if ($('#store').val() != content) {
alert('Content has been changed')
}
});
});
</script>
</head>
<body>
<input type="button" id="trigger" value="Start" onclick="startRolling()"/>
<input type="text" id="cnt" readonly="readonly"/>
<input type="hidden" id="store" value="0"/>
</body>
What if you just fire the event without trying to detect the change?
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
if(storage != tonum) {
alertChange();
}
//storage=document.getElementById('store').value;
//alert(storage)
}
function alertChange() {
alert('Content has been changed');
}
You could also look at the trigger event in jquery: http://api.jquery.com/trigger/.
Try this
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
//storage=document.getElementById('store').value;
//alert(storage)
}
$(document).ready(function() {
//var content = $('#store').val();
$('#store').change(function() {
//if ($('#store').val() != content) {
alert('Content has been changed')
}
});
Why don't you change the first function to jquery?
From the description of the change-event:
The change event occurs when a control loses the input focus and its value has been modified since gaining focus.
Hidden inputs cannot lose focus(because they never have focus), so change will not fire there anyway.
See Any even to detect when the "Class" attribute is changed for a control for a solution.
Rather than using a change event, I've used a loop event that checks every second.
var content="";
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
storage=document.getElementById('store').value;
content=storage;
alert(storage)
}
function checkifchanged(){
if ($('#store').val() != content) {
alert('Content has been changed');
}
else{
content = $('#store').val();
}
setTimeout('checkifchanged()',1000);
}
$(document).ready(function() {
content = $('#store').val();
checkifchanged();
});
var content = $('#store').val();
You are storing the changed value and comparing with the same value,
this if statement doesn't execute
if ($('#store').val() != content)
don't store the value just call change event directly.
$(document).ready(function() {
$('#store').change(function() {
alert('Content has been changed')
});