Please look at the following code:
**page.html**:
<!DOCTYPE html>
<html>
<head>
<title> Playing with JavaScript </title>
<script src="myjs.js"> </script>
</head>
<body id="body">
<ul id="mylist">
<li> David </li>
<li> Aharon </li>
</ul>
<form>
<input type="text" name="user_input"> <br>
<button onclick="add_item(user_input.value)"> add_item </button>
</form>
</body>
</html>
**myjs.js**
function add_item(user_input) {
var new_li = document.createElement("li");
var new_text = document.createTextNode(user_input);
new_li.appendChild(new_text);
document.getElementById("mylist").appendChild(new_li);
}
This code creates a list of two names and displays a button and an input line. Once the user enters a new name in the input line and clicks the button, the new name is supposed to be added to the list.
It happens for a very short period of time and then the new element in the list disappears. Do you know what can I change in the code so the new element in the list will stay permanently?
I think it's because your form is submited and page is reload
add a type="button" at your button
Working Example
function add_item(user_input) {
var new_li = document.createElement("li");
var new_text = document.createTextNode(user_input);
new_li.appendChild(new_text);
document.getElementById("mylist").appendChild(new_li);
}
<form>
<input type="text" name="user_input"> <br>
<button type="button" onclick="add_item(user_input.value)"> add_item </button>
</form>
<ul id="mylist"></ul>
<button> element have 3 type :
submit : default type if no type are specified who submit a form
reset : who reset/clear input in a form
button : no specific action
I imagine the page is reloading because your button element is a submit button inside a form - when no type attribute is specified for a button it becomes a submit button by default. Your form doesn't have an action specified so submitting reloads the current page.
Add type="button" to the button.
That will mean that the button has no default behaviour and does only what the JS does explicitly.
Related
I'm trying to build a Trivia game, right now I've one question and 3 answers (radio buttons), the user will choose one answer and then click submit. If it's the wrong answer the button will show "Retry" instead of "Submit.
First I only started to learn Javascript and I'm pretty sure there's a simple/better way to use one button to submit and then "retry" if the answer is wrong. I just created two functions, first function() that will check the answer, if it's the wrong answer it'll jump to wrongAnswer() This function suppose to change the text of the button, changing the button onclick (so I can increase the number of "clicks") and will check if there's more than 1 click (if true: location.reload) I couldn't think on a better way to let the user try again answering the question (I made the other radio buttons gray after "wrong" answer).
Also why when I put
var clicks = 0; outside the function it's NaN... Why?
My main problem, the second click will give me this error instead of increasing the "clicks" (it's not defined on HTML but this's why I change the attribute as you can see in the code
Uncaught ReferenceError: wrongAnswer is not defined
at HTMLInputElement.onclick (index.html:1)
Though I can see on the button inspect that the onclick is now = wrongAnswer();
My HTML:
<input class="submit" id="mybtn" onclick="userChoose()" type="submit" value="Submit!">
<p>Clicks: <a id="clicks">0</a></p>
My javaScript:
function wrongAnswer() {
var clicks = 0; // for how many button clicks
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
var btn = document.getElementById("mybtn");
btn.value = 'Try again'; // Will just add a hidden value
btn.innerHTML = 'Try again'; // Even without inner it works ??? (not sure why)
btn.style.fontSize = "x-large"; // Made the text a little bit smaller
document.getElementById( "mybtn" ).setAttribute( "onclick", "wrongAnswer();" );
}
}
In the end I'll be happy if someone can explain what I did wrong and if there's a better way instead of doing this to reload the page by clicking the button again after "wrong answer".
if (clicks = 2){
location.reload;
}
If i understood your question here there is an example:
In this example i have a question and 3 radio buttons (answer1, answer2 and answer3).. if the user click on radio button1(answer1) he gets an alert with good job else an alert with retry and the button value is retry!. The user when click on the reTry the page is reload...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> test</title>
<style>
</style>
<script type="text/javascript">
function userChoose(){
//control the value button if it is submit or retry
let btn=document.getElementById('mybtn');
if(btn.value=="Submit!"){
//user have to answer
let answer= document.getElementById('answer1');
if(answer.checked){
alert('good job!');
}
else{
//wrong answer
alert("Retry!");
document.getElementById('mybtn').value="Tryagain!"
}
}
else{
//call function wrongAnswer()
wrongAnswer();
}
}
function wrongAnswer(){
location.reload();
}
</script>
</head>
<body>
<p>QUESTION....</p><br>
<div>
<input type="radio" name="answer" id="answer1" value="a1">answer1<br>
<input type="radio" name="answer" id="answer2" value="a2">answer2<br>
<input type="radio" name="answer" id="answer3" value="a3">answer3<br>
</div>
<br>
<input class="submit" id="mybtn" onclick="userChoose()" type="submit" value="Submit!">
</body>
</html>
Hope this helps
Here is my code --
<div id="div1">
this is div 1
<form class="thisformtobeaddeverytime">
<!-- this form to be add on click #btn1 -->
</form>
</div>
<div id="div2">
this is div 2
<form class="thisformtobeaddeverytime">
<!-- this form to be add on click #btn2 -->
</form>
</div>
<div id="showtheaddedform">
//here my form will be push on click to button
</div>
<button type="button" id="btn1">Add the form1</button>
<button type="button" id="btn2">Add the form2</button>
// the click function in my js file are as -
$(document).on("click","#btn1",function(){
$("#showtheaddedform").append($("#div1").html());
});
$(document).on("click","#btn2",function(){
$("#showtheaddedform").append($("#div2").html());
});
now the problem is --
On click #bun1 it's adding the content of #div1 into #showtheaddedform (i.e. the form attribute and all element inside form), like
<div id="showtheaddedform">
<form class="thisformtobeaddeverytime">
<!-- this form to be add on click #btn1 -->
</form>
</div>
but when I'm clicking #btn2 it's adding only the element inside the form , like
<div id="showtheaddedform">
<!-- this form to be add on click #btn2 -->
</div>
[ NOTE : I've not written any kind of remove query ]
..any idea , how it's removing !!!
Both your buttons have the same id. Also there is a syntax mistake in
$(document).on("click","#btn1",function(){
$("#showtheaddedform").append($("#div1").html());
}
add
); to it
DEMO
Actually Form tag is getting append to the div on second button's click. But in the UI it will not be shown as it doesnt have any tags or text in it. Try giving some text or tag in it. It will work
EDIT
Updated Fiddle
Your second button appears to have the wrong ID.
<button type="button" id="btn1">Add the form2</button>
Change to
<button type="button" id="btn2">Add the form2</button>
Try Below code in java script tag and also change your button id to btn1 and btn2
$(document).ready(function(){
//alert("hi");
$("#btn1").click( function()
{
$("#showtheaddedform").empty();
$("#showtheaddedform").append($("#div1").html());
});
$("#btn2").click( function()
{
$("#showtheaddedform").empty();
$("#showtheaddedform").append($("#div2").html());
});
});
How do you replace a button with whatever words were on the button before? I was looking at an answer to another similar question, which said to use something like:
var myBtn = document.getElementById("buttonId"),
mySpan = document.createElement("span");
mySpan.innerHTML = myBtn.innerHTML ;
myBtn .parentNode.replaceChild(mySpan, myBtn);
but that had made what other buttons do change. Does anyone know another way to change a button to regular text?
I know that that code works just by itself, but it doesn't work with my code for some reason, so I don't really care what's wrong with that code. I'm just wondering if anyone knows another way to do it.
Thanks
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<div id="myDiv">
<input type="button" value="Change into Text" id="submit" onClick="change()"> <!--button input that will trigger an event named change-->
</div>
</body>
</html>
<script type="text/javascript">
function change(){ //function to run when you click on the button...
var buttonValue = document.getElementById("submit").value; //stores the button value
document.getElementById("myDiv").innerHTML = buttonValue; // displays the value as a plain text inside "myDiv" - removing the button input entirely
}
</script>
EDIT:
I've just noticed you had multiple buttons in your page, which will make my previous example wrong. heres something that will make you work easier i think in case you will add extra buttons:
first heres the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<li id="id_1"><input type="button" value="Change into Text" onClick="change(1)" id="button_1"></li>
<li id="id_2"><input type="button" value="Change into Text" onClick="change(2)" id="button_2"></li>
<li id="id_3"><input type="button" value="Change into Text" onClick="change(3)" id="button_3"></li>
</ul>
</body>
</html>
<script type="text/javascript">
var id;
function change(id){
var buttonValue = document.getElementById("button_"+id).value;
document.getElementById("id_"+id).innerHTML = buttonValue;
}
</script>
In the HTML part, you can create a list (li) of buttons if that's your layout...
each list will have its own id, in this case id_x that will be used later when you replace its content. each button calls a function change(id) while id is just a unique number for each button.
In the JS part, the change(id) gets the id of the button that was clicked, takes its value, and replaces the innerHTML (content) of the relative list items with a plain text.
Let me know if you still need any other help.
Seems that you are looking for another way to replace the buttons with plain text, well I'll show you the jQuery way.
HTML
<div>
<button id="btn1" class="change-button">A button with some text 1</button>
<button id="btn2" class="change-button">A button with some text 2</button>
<button id="btn3" class="change-button">A button with some text 3</button>
</div>
jQuery
// When we click a button with a "change-button" class
$(".change-button").on("click", function(event){
// First we get the ID value of the clicked button
// example: "btn2"
var buttonId = $(this).attr('id');
// Then we get the html value of the clicked button
// example: "A button with some text 2"
var buttonText = $(this).html();
// We use the function replaceWith, to replace the button to a <span>
// with the buttonText variable we have
$('#' + buttonId).replaceWith("<span>" + buttonText + "</span>");
});
As you can see, it's a lot more cleaner with jQuery. You should try it!
Here is the fiddle so you can test it.
<html>
<script>
function fun()
{
var a = document.getElementById("hello").value;
document.getElementById("ad").innerHTML = a;
}
</script>
<body>
<div id="ad">
<input type="button" value="hello" id="hello" onClick="fun()">
</div>
</body>
</html>
sorry, edited the wrong post
Ok Guys I need help in this case and please help if you can :(
I have following div created with text-type input
<div class="footer">
<div id="footerInner">
<form>
<input type="text" name="enter" value="" id="input"/>
</form>
</div>
</div>
I have also created above .footer .mainBody
<div class="mainBody">
<script src="Scripts/main.js">
var h = document.getElementById('input').value;
document.write(h);
</script>
</div>
And I have included Javascript in it
I want to work it this way: when I input text in input tag to appear in .mainBody div.
And also do I need button to submit input or it can be done with key press for Ex. "Enter"?
Guys onkeyup="writeThis()" isn't working it just reloads page :(
To execute some events on keyevents, you need to write the onkeyup or onkeydown or any other key function in the element. And in that attribute you can add the function's name which would respond to the event. I will write my function's name as writethis() which will write the value to the div.
You then need to use this:
<input type="text" id="input" onkeyup="writethis()" />
And the function would be:
function writethis() { // the function
var h = document.getElementById('input').value; // the value
document.getElementsByClassName('mainBody').innerHTML = h; // the input
}
This way, you will get the input written on a keypress!
You can also try and use some keyevents such as:
if(event.keyCode == 13) { // enter key event
/* key code for enter is 13
* do what so ever you want */
}
Ok, try this as your JS script content in html head section:
function writeOnBody() {
var inputText = document.getElementById('input').value;
var mainBodyEl = document.getElementById('mainBody');
mainBodyEl.innerHTML = inputText;
}
your HTML code:
<div class="footer">
<div id="footerInner">
<form>
<input type="text" name="enter" value="" id="input" onkeyup="writeOnBody()" />
</form>
</div>
</div>
<div id='mainBody' class="mainBody"></div>
I hope it helps. JSFiddle sample: http://jsfiddle.net/amontellano/JAF89/
var h = document.getElementById('input').value; // the value
document.getElementsByClassName('mainBody').innerHTML = h;
avoid using getElementsByClassName instead give you div a id and use getElementById..
rest is in my opinion the best solution..
and yes you can also you a button also all you have to do is call you function on onclick event like this
<button onclick="functionZ()">click me</button>
and define that functionZ in your java script
What we are doing here is..
Adding a button and a click event upon it..such that when that button will be clicked it will call a function for us..
Make sure to add your scripts in lasts part of your page as page loads from top to bottom so its good practice to add scripts just near to end of body
I have some html that looks as so:
<h3 class="basic left-top-border-radius">Basic<br /> 500<span>$25</span></h3>
<a class="signup colorbox" href="#text-signup-form">More Info</a>
When More Info is clicked a lightbox pops up with a simple info request form. Here is my problem. I would like when the link is clicked to have the text of the h3 header passed to a form input field that is hidden so I know which plan they clicked on for more info.
The input looks like so:
<input type="text" class="cat_textbox" id="CAT_Custom_440761" name="CAT_Custom_440761" maxlength="1024" />
How would I do this using jQuery? (I thought of using jQuery .text() method but I read that does not work with forms and I do not know how to pass the h3 text anyway.
NOTE There are multiple h3 elements on the page.
You can do the following with this code.
$('.signup').click(function(){
var planTitle = $('h3').text();
$('#CAT_Custom_440761').val(planTitle);
});
As you click on the button it will search for the h3 tag (would be better to attach an ID to the h3 tags) grab the text of that element and insert it into the value of the input field.
If you aren't able to attach an ID to the h3 tag you can search for the prev instance of h3 and take the text from that.
$('.signup').click(function(){
var planTitle = $(this).prev('h3').text();
$('#CAT_Custom_440761').val(planTitle);
});
You can try this:
$('a').click( function() {
var text = $(this).parent().find('h3').text();
$(this).parent().find('.cat_textbox').val(text);
})
perhaps you can use this code
<form action="test1.asp" id="testform">
<input type="hidden" id="test3" value="">
<input type="BUTTON" id="submit" onclick="modify_value()"/>
</form>
<script type="text/javascript">
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'testvalue';
document.getElementById("testform").submit();
}
</script>