I have a very simple code: I want to cancel a button after it's clicked to display something else. I tried this way
HTML:
<div id="container">
<input type="button" value="New game" onclick="newGame()" />
</div>
js:
function newGame() {
var container = document.getElementById("container");
container.removeChild(container.childNodes[0]);
}
What happens is the button gets cancelled only if I click it two times. Where did I get wrong?
I'm sorry if this is a repost, I tried to check but didn't find a quetion identical to mine
It appears as if your code is going to remove the button once you click on it. Is this correct, or are we not looking at the full markup?
If you remove \n (i.e new line) your code will work
try like this
function newGame() {
var container = document.getElementById("container");
debugger;
container.removeChild(container.childNodes[0]);
}
<div id="container"><input type="button" value="New game" onclick="newGame()" /></div>
The reason why your code is not working is, when you hit enter after div, HTML DOM will automatically creates one dummy text node as it's child. hence your input node became the second child for your container.
Working fiddle
Hope it helps :)
try this:
function newGame() {
var container = document.getElementById("container");
// change 0 to 1
container.removeChild(container.childNodes[1]);
}
container.childNodes[0] is a text Node, in which the text is Newline
I gave id to the button and removed it using id.
In your case it is not removing in first time because container.childNodes[0] in first time is not a button. Try your self using console.log in your function.
function newGame() {
var container = document.getElementById("container");
var d_nested = document.getElementById("button_1");
var throwawayNode = container.removeChild(d_nested);
//container.innerHTML='';
}
<div id="container">
<input id="button_1" type="button" value="New game" onclick="newGame()" />
</div>
Alternatively, you could do this:
<div id="container">
<input type="button" value="New game" onclick="document.getElementById('container').removeChild(this);" />
No separate JS file needed.
Related
It should happen like this when I am pressing 'ADD TODO' if it's empty it should create a p tag after input 'enter your TODO', now although the js is creating the element but it isn't showing up on the webpage
HTML:
<h1 class="head">MY LIST</h1>
<input type="text" id='input'>
<button id='add' type="buttton">ADD TODO</button><br>
remove TODO
remove everything
JS:
function addItem() {
var input =document.getElementById('input');
var textNode = document.createTextNode(input.value)
if(input.value === '') {
var par=document.createElement('p')
par.textContent='enter TODO please';
par.setAttribute('id','new')
// I have only put here the if case
document.querySelector('input').appendChild(par);
}
}
You need to make sure to set the click event for your button. Right now, the button is just calling the default action instead of your function. To do this, the tags for the button need to be
<button id='add' type="button" onclick="addItem()">ADD TODO</button><br>
Right now, your button is trying to add a paragraph as a child to the input and not after. To add the paragraph after you need to change the last line of your JS to
document.querySelector('input').after(par);
Well, as I was searching on the internet for some basic codes to examine - I found this one. A simple code which is supposed to copy the selected text. As i am a complete newbie in JS, I check the meaning of the methods that I didn't understand - and rewrited the code, as i make a few adjustments.
And still the code is not working and If someone can explain - this part ""copyit(this.form.select1)"" - Even though I kind of understand "this" - i am not able to understand what is doind here
function copyit(theField) {
var selectedText = document.getSelection();
if (selectedText.type == 'Text') {
var newRange = selectedText.createRange();
theField.focus();
theField.value = newRange.text;
} else {
alert('select a text in the page and then press this button');
}
}
</script>
<form name="it">
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>
This is the original code - and it is not working either
<SCRIPT LANGUAGE="JavaScript">
function copyit(theField) {
var selectedText = document.selection;
if (selectedText.type == 'Text') {
var newRange = selectedText.createRange();
theField.focus();
theField.value = newRange.text;
} else {
alert('select a text in the page and then press this button');
}
}
</script>
And in the body of your web page, add the following where you want the text to appear:
<form name="it">
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>
onclick="copyit(this.form.select1)"
executes the copyit() function and passes a variable which is later named theField. The variable that is passed is this.form.select1 which is a textarea with ID select1 which is located in the same form as the input you're clicking hence the this.form.
As to why your code isn't working - you should include here the original code before your adjustments. You probably deleted/changed something you shouldn't have.
I'm not sure what you're asking. Are you asking to, when someone clicks on any button/div, it copies a text you want for his clipboard? If no, ignore my comment, if yes, i'll explain:
First place, where should an user click?
<a class="btn" CopydivFunction(#text)">CLICK ME TO Hello.</a>
Now, add the function with JS.
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
Now, place the text you want somebody to copy (hide it):
<h1 id="text" class="hidden">some text. This part won't be seen because of the hidden class, and this is the text that will be copied to your clipboard.</h1>
Place display:none on css:
#text{
display:none;
}
I think you have to add that, so nobody sees it.
And that should be it, click the <a> and you get the text in the h1#text
it changes for about a second and returns to the previous text.The "Loading..." line has to change into "hi, Please click the next text box to see more instructions!".
I have tried it latest chrome and Edge browsers.
function greetMe() {
var yourName = document.getElementById("textbox").value;
info1 = "hi, Please click the next text box to see more instructions!"
document.getElementById("textToChange").innerHTML = info1
}
#myForm {
float: left;
width: 30%
}
#myformInfo {
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>HEllO ThERE!</h1>
<div id="myForm"><form >
<input id="textbox" placeholder="Your name">
<button onclick="greetMe()">click!</button>
<br><br>
<input id="">
</div></form>
<div id="myFormSteps">
<p id="textToChange">
<script>var info1 = "Loading..."
document.write(info1)
</script>
</p>
</div>
</body>
</html>
It's probably because you haven't set the type attribute for your button. A button's default type is submit. Try adding the attribute type="button" to your <button>.
When you click the button your form is submitting and the page is reloading - that's why it returning to its initial state. To stop this happening pass in event as a parameter to the function and then use that argument in the function with preventDefault():
HTML
<button onclick="greetMe(event);">click!</button>
JS
function greetMe(e) {
e.preventDefault();
// ...
}
As an aside it's better is to remove your inline JS and use an event listener instead.
var button = document.querySelector('button');
button.addEventListener('click', greetMe, false);
I'm new to using javascript and have come up against a bit of a wall where I was looking for code to duplicate a DIV. I found the following code:
<html>
<body>
<form name="myform">
<input type="button" value="Click here" onclick="duplicate()">
<div id="original">
duplicate EVERYTHING INSIDE THIS DIV
</div>
<div id="duplicater">
duplicate EVERYTHING INSIDE THIS DIV
<input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
</div>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
</script>
</body>
</html>
This works quite well. I added a Remove Div button so if the user decided they added one Div too many they would have the option to remove it. However, in testing I found if the user Remove Div all the way back to the first Div, any further Duplicate Div does not display. So the user would have to restart the page. To resolve this I tried to include an IF...ELSE.
<html>
<body>
<form name="myform">
<input type="button" value="Click here" onclick="duplicate()">
<div id="original">
duplicate EVERYTHING INSIDE THIS DIV
</div>
<div id="duplicater">
duplicate EVERYTHING INSIDE THIS DIV
<input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
</div>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
if (document.getElementById("duplicater")=="none")
{
document.getElementById("duplicater")="";
}
else
{
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
}
</script>
</body>
</html>
However, this does not work. I fully admit to being no coding guru and wouldn't be surprised if it is a simply syntax issue, but any points with this would be greatfully accepted.
Your problem is here:
this.parentNode.style.display = 'none'
This is setting the parent node (the form) to not display (which isn't the same as removing it). What you want to do is find the lastChild to the of the parent node and remove it.
Matt has your answer, I got distracted so here's a late response. In your code:
> <input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
does not "remove" the node, it just hides it. To remove the node:
<input type="button" value="Remove Div" onclick="this.parentNode.parentNode.removeChild(this.parentNode)">
Also:
> if (document.getElementById("duplicater")=="none")
getElementById returns either a DOM node with a matching ID, or null if there isn't one. Neither will ever be equivalent to the string "none", therefore the above will always return false. Which is a good thing because in the line:
> document.getElementById("duplicater")=""
You will be trying to assign to null or a DOM element, both of which are not permitted. In the case that the left hand side evaluates to null , an error will result. Where it resolves to a DOM element, anything can happen (since host objects can do what they like) but likely an error will result.
I'm pulling a content from PHP array and I have a situation like this:
<div class="weight-display">
<span>04/25/2011</span> <span>100lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
<div class="weight-display">
<span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
etc...
Now when somebody clicks on Edit within, let's say, first div where weight is 100lbs, I just need that "div" to change and to have input field instead of simple text where weight is (while others will remain the same) and to be like this:
<div class="weight-display">
<span>04/25/2011</span> <input type="text" value="100" /> <span>Save</span> <span>Cancel</span>
</div>
<div class="weight-display">
<span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
etc..
So basically div has to "reload itself" and change content. Now I really need some very simple Javascript solution. Preferably I would like a solution with a hidden div beneath original one, so they just swap places when user clicks on EDIT and in a case if CANCEL is pressed to swap places again so original div with text is displayed...
Thanks,
Peter
<style type="text/css">
/* Normal mode */
.weight-display div.edit {display:none}
/* Editor mode */
.weight-edit div.show {display:none}
</style>
<div class="weight-display">
<button onclick="toggle(this)">Edit this!</button>
<div class="edit"><input type="text" value="Test" /></div>
<div class="show">Test</div>
</div>
<script type="text/javascript">
function toggle(button)
{
// Change the button caption
button.innerHTML = button.innerHTML=='Edit this!' ? 'Cancel' : 'Edit this!';
// Change the parent div's CSS class
var div = button.parentNode;
div.className = div.className=='weight-display' ? 'weight-edit' : 'weight-display';
}
</script>
What you suggest is basically correct. I would generate two div's one for display and one edit. The edit div will initially have display: none. When the Edit is clicked, hide the display div and show the edit div.
How about something like:
onClick event calls a function (EDITED to be a little smarter than my original brute force method):
function swapdivs ( id_of_topdiv, id_of_bottomdiv ) {
var topdiv = getRefToDiv( id_of_topdiv );
var bottomdiv = getRefToDiv( id_of_bottomdiv );
var temp = topdiv.style.zIndex;
topdiv = bottomdiv.style.zIndex;
bottomdiv = temp.style.zIndex;
}
Could that or similar work for you? Or am I missing some subtle yet crucial requirement?