HTML inside of a JavaScript loop - javascript

I'm trying to create 10 radio buttons, labeled 1-10 with a for loop inside of my html and I can't get it to work.
<html>
<body>
<h2 style="text-align:center">
On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?
</h2>
<form id="NPSform"; style= "text-align:center">
<script>
for (var i = 1; i <=10; i++) {
<input type="radio" name="scores" id="i" value="i"> i
}
</script>
<input type="submit" name="mysubmit" value="Submit"/>
</form>
</body>
</html>
Thanks. I'm new to JS so I'm still learning a lot.

Use document.write to output the HTML like so.
document.write('<input type="radio" name="scores" id="i" value="i"> i');
<html>
<body>
<h2 style="text-align:center">
On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?
</h2>
<form id="NPSform"; style= "text-align:center">
<script>
for (var i = 1; i <=10; i++) {
document.write('<input type="radio" name="scores" id="i" value="i">'+ i);
}
</script>
<input type="submit" name="mysubmit" value="Submit"/>
</form>
</body>
</html>

You can add all inputs to one string inside loop and then append it to HTML, also you should separate your js and html code
var inputs = '';
for (var i = 1; i <= 10; i++) {
inputs += '<input name="scores" type="radio" value="' + i + '" id="' + i + '">'+i+'';
}
document.getElementById('NPSform').insertAdjacentHTML('afterbegin', inputs);
<h2 style="text-align:center">On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?</h2>
<form id="NPSform" style="text-align:center">
<input type="submit" name="mysubmit" value="Submit" />
</form>
You can also create one div, set innerHTML and use insertBefore to add it to html
var inputs = '';
for (var i = 1; i <= 10; i++) {
inputs += '<input name="scores" type="radio" value="' + i + '" id="' + i + '">' + i + '';
}
var div = document.createElement('div');
div.innerHTML = inputs;
var submit = document.querySelector('#NPSform input');
submit.parentNode.insertBefore(div, submit);
<h2 style="text-align:center">On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?</h2>
<form id="NPSform" style="text-align:center">
<input type="submit" name="mysubmit" value="Submit" />
</form>

<html>
<head>
<script>
function addbuttons() {
var buttons = document.getElementById("dynamicButtons");
for (var i = 1; i <=10; i++) {
buttons.innerHTML += '<input type="radio" name="scores" id="' +i +' " value="' +i +'">'
}
}
</script>
</head>
<body onload="addbuttons()">
<h2 style="text-align:center">
On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?
</h2>
<form id="NPSform"; style= "text-align:center">
<div id="dynamicButtons"></div>
<input type="submit" name="mysubmit" value="Submit"/>
</form>
</body>
</html>

<html>
<body>
<h2 style="text-align:center">
On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?
</h2>
<form id="NPSform"; style= "text-align:center">
<input type="submit" name="mysubmit" value="Submit"/>
</form>
</body>
<script>
for (var i = 1; i <=10; i++) {
document.write("<input type='radio' name='scores' id='"+i+"' value='"+i+"'> "+i+"");
}
</script>
</html>

<html>
<body>
<h2 style="text-align:center">
On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?
</h2>
<form id="NPSform"; style= "text-align:center">
<div id="radioscontainer">
</div>
<input type="submit" name="mysubmit" value="Submit"/>
</form>
<script>
var radioButtons = '';
for (var i = 1; i <=10; i++) {
radioButtons += '<input type="radio" name="scores" id="i" value="i"> i';
}//for
$("#radioscontainer").append( radioButtons );
</script>
</body>
</html>

Related

HTML, how to get always +1 sum

I'm doing a point counter in general and I have no idea how to do it anymore, so I would like to add +1 to the sum on the "=" button and add it only once if someone could help me, I would be grateful
Code: https://pastebin.com/C26VFyev
var result = 0;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + 1);
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>
Use a variable for what you add to the sum. Initialize it to 1 for the first time, than change it to 0 for future uses.
var result = 0;
var addition = 1;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + addition);
if (addition == 1) {
addition = 0;
}
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>

How to get values of multiple textboxes generated dynamically?

I have a button called 'AddTextArea', on clicking, I get new text area, but how can I get the values that I have entered in the new text areas?
I tried like this-
var x= document.getElementById("div_quotes").value;
but it's not working.
Please help, as I am new to JS, thanks in advance.
<html>
<head>
<script type="text/javascript">
function addTextArea(){
var div = document.getElementById('div_quotes');
div.innerHTML += "<textarea name='new_quote[]' />";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>
var x= document.getElementById("div_quotes").value;
Above code will not work as div_quotes is a div and div do not have value property.
You will have to search for textareas in this div.
Sample
function addTextArea() {
var div = document.getElementById('div_quotes');
div.innerHTML += "<textarea name='new_quote[]' />";
div.innerHTML += "\n<br />";
}
function validate(){
var tas = document.querySelectorAll('#div_quotes textarea[name="new_quote[]"]')
for(var i = 0; i< tas.length; i++){
console.log(tas[i].value)
}
}
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="button" name="submitted" onclick="validate()" value="Validate">
</form>
Version 2
Now if you notice in above sample, if you type and then add another textarea, it will flush value of previous ones. This is because, you are setting .innerHTML += .... This will destroy and recreate all elements again. You should use document.createElement
function addTextArea() {
var div = document.getElementById('div_quotes');
var wrapper = document.createElement('div')
var ta = document.createElement('textarea');
ta.name = "new_quote[]"
wrapper.append(ta);
div.append(wrapper)
}
function validate(){
var tas = document.querySelectorAll('#div_quotes textarea[name="new_quote[]"]')
for(var i = 0; i< tas.length; i++){
console.log(tas[i].value)
}
}
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="button" name="submitted" onclick="validate()" value="Validate">
</form>
You can add a CSS Class to the new text area that is generated and get the data using
var x = document.getElementsByClassName("dynamicTxtArea")
I have added the class to the Text area that is being dynamically generated. Please check the code below.
<html>
<head>
<script type="text/javascript">
function addTextArea(){
div.innerHTML += "<textarea name='new_quote[]' class='dynamicTxtArea'/>";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>

How do I add/remove text boxes with JQuery changing the variable name to keep the name attributes different?

I want to make a book catalog with JQuery to add books to a author. In the code That I have I am trying to add a author and have his books be in a array with his number only. Separated by other authors and their own arrays of books.
For example, when I press the button to add a author a input box appears so that I can add the authors name also a button to add a book that when I press that button I get an input box to add a books name.
When I press the add author again I want to be able to add another author with the same input boxes as before (adding more books to that author).
Also to add multiple books assigned to that author.
I have already done this in the pics but I get an array of everything. I want it to be separated by author.
author1 has an array of {book1, book2, book3...}
author2 has an array of {book13, book14, book15}
(i'm a beginner at JQuery)
This is the code that I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form role="form" method="post">
<p class="all_fields">
<button class="add_author">Add Author</button>
<div id="commonPart" class="commonPart">
<label for="author1">Author <span class="author-number">1</span></label>
<br/>
<input type="text" name="author" value="" id="author1" />
<br/>
<button class="add_book">Add book</button>
<div>
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function($){
var wrapper = $(".all_fields"); //Fields wrapper
var commonPart = $("#commonPart");
var add_author = $(".add_author"); //Add button ID
var add_subButton = $(".add_book"); //Add sub button ID
$('.my-form .add-box').click(function(){
var n = $('.all_fields').length + 1;
if( 15 < n ) {
alert('Stop it!');
return false;
}
$(add_author).click(function(e){
e.preventDefault();
var htmlToAdd = $('<label for="author' + n + '">Author <span class="author-number">' + n + '</span></label><br/><input type="text" name="author' + n + '" value="" id="author' + n + '" /><br/><button class="add_book">Add book</button><a class="add-book" href="#">Add Book</a><div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
htmlToAdd.hide();
$('.my-form p.all_fields:last').after(htmlToAdd);
box_html.fadeIn('slow');
return false;
});
$(add_book).click(function(e){
e.preventDefault();
var htmlToAdd = $('<div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
htmlToAdd.hide();
$('.my-form p.all_fields:last').after(htmlToAdd);
box_html.fadeIn('slow');
return false;
});
$('.my-form').on('click', '.remove-box', function(){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
</body>
</html>
updated code(fixed some bugs..), try this....
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<button onclick="addAuthor()" >Add Author</button><br><br>
<div id="addAuth"></div>
<br><br>
<button onclick="submit()" >Submit</button>
</div>
<div id="result" ></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor(){
authors++;
var str = '<div id="auth'+authors+'"><input type="text" name="author" id="author'+authors+'" />'
+'<button onclick="addMore(\'auth'+authors+'\')" >Add Book</button>'
+'</div>';
$("#addAuth").append(str);
}
var count=0;
function addMore(id){
count++;
var str = '<div id="bookDiv'+count+'">'
+'<input class="'+id+'" type="text" name="book'+id+'" />'
+'<span onclick="addMore(\''+id+'\')" style="font-size: 20px; background-color: green; cursor:pointer;">+</span>'
+'<span onclick="removeDiv(\'bookDiv'+count+'\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">-</span>'
+'</div>';
$("#"+id).append(str);
}
function removeDiv(id){
var val = confirm("Are you sure ..?");
if(val){
$("#"+id).slideUp(function(){$("#"+id).remove();});
}
}
function submit(){
var arr = [];
for(i=1; i<=authors; i++){
var obj = {};
obj.name = $("#author"+i).val();
obj.books = [];
$(".auth"+i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
</script>
</body>
</html>
Please try this code and include jquery min js :
<div class="my-form">
<form role="form" method="post">
<p class="all_fields">
<div id="commonPart" class="commonPart">
<label for="author1">Author <span class="author-number"></span></label>
<input type="text" name="author" value="" id="author1" />
<br/>
<div>
<label for="author1">book <span class="author-number"></span></label>
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
<button type="button" class="add_author" onclick="AddCustomMOre();">Add More</button>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
<script> function AddCustomMOre(){
$(".all_fields ").append('<div id="commonPart" class="commonPart"><label for="author1">Author <span class="author-number"></span></label> <input type="text" name="author" value="" id="author1" /> <br/> <div><label for="author1">book <span class="author-number"></span></label> <input type="text" class="bookName" name="authBook[]"/></div> Remove</div>');
} </script>
You can try this....
<p class="all_fields">
<button class="add_author">Add Author</button>
<div class="commonPart">
<label for="author1">Author <span class="author-number">1</span></label>
<br/>
<input type="text" name="author1" value="" id="author1" />
<br/>
<button div-id="1" class="add_book">Add book</button>
<div id="books1">
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
</p>
<script>
var c=1;
$(".add_author").on("click",function(){
c++;
$(".all_fields").append('<div class="commonPart"><label for="author'+c+'">Author <span class="author-number">'+c+'</span></label><br/><input type="text" name="author'+c+'" value="" id="author'+c+'" /><br/><button class="add_book" div-id="'+c+'">Add book</button><div id="books'+c+'"><input type="text" class="bookName" name="authBook[]"/></div></div>');
});
$(".add_book").on("click",function(){
var id=$(this).attr("div-id");
$("#books"+id).append('<input type="text" class="bookName" name="authBook[]"/>');
});
</script>

Get Radio Value to Carry over pages with Javascript

I am trying to build a very simple dot chasing game as a homework assignment, and I cannot figure out how to carry over the difficulty selection from the index page to the actual game page.
Index Page
<form id="difficulty" name="difficulty" action="game.html">
<input type="radio" name="diff" id="easyDiff" value="easy">
<label for="easyDiff">Easy</label>
<input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
<label for="medDiff">Medium</label>
<input type="radio" name="diff" id="hardDiff" value="hard">
<label for="hardDiff">Hard</label>
<input type="submit" value="Start Game!" onClick="setDifficulty()"/>
</form>
Game Page
<html>
<head>
<title>DotSmasher</title>
<link rel="stylesheet" href="dotSmasher.css" type="text/css">
<script src="dotSmasher.js" type="text/javascript"></script>
</head>
<body onLoad="setGameAreaBounds(); startGameTimer()" onResize="setGameAreaBounds()">
<div id="scoreLabel">Score: 0</div>
<div id="pageTitle">DotSmasher</div>
<div id="start">
<button id="startButton" onClick="start()">Start</button>
</div>
<div id="stop">
<button id="stopButton" onClick="pause()">Stop</button>
</div>
<div id="gameArea">
<button id="dot" onClick="detectHit()"></button>
</div>
</body>
</html>
JavaScript Code
Variables count, timer, and difficulty are instantiated at the beginning of the page
var score = 0;
var aWidth;
var aHeight;
var timer;
var count = 30;
var counter = setInterval(startGameTimer, 1000);
var difficulty;
function startGameTimer(){
count -= 1;
if (count <= 0){
clearInterval(counter);
clearTimeout(timer);
alert("Game has ended, Thank you for playing on " + difficulty + "!");
return;
}
}
function setDifficulty(){
var radioButtons = document.getElementsByName("diff");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
difficulty = radioButtons[i].value;
}
}
}
For some reason i am getting an undefined error and cannot figure out what it could be.
You need to put your script at the top in your page and in head tag, try this:
<script>
function setDifficulty(){
var radioButtons = document.getElementsByName("diff");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
difficulty = radioButtons[i].value;
alert(difficulty);
}
}
}
</script>
<input type="radio" name="diff" id="easyDiff" value="easy">
<label for="easyDiff">Easy</label>
<input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
<label for="medDiff">Medium</label>
<input type="radio" name="diff" id="hardDiff" value="hard">
<label for="hardDiff">Hard</label>
<input type="submit" value="Start Game!" onclick="setDifficulty();"/>
Here is DEMO

Append and remove last appended, Javascript

Can anyone provide insight on removing a text field element that was just appended? I haven't been able to get other posted solutions to work with the code I'm using. Thanks in advance.
<html>
<head>
<script>
function append(num) {
var txt = document.getElementById("result").value;
txt = txt + num + " ";
document.getElementById("result").value = txt;
}
</script>
</head>
<body>
<form>
<input type="button" value="A" onclick="append(this.value)">
<input type="button" value="B" onclick="append(this.value)">
<input type="button" value="C" onclick="append(this.value)">
<br>
<br>
<input type="text" id="result" size="100">
<br>
<br>
<input type="button" value="Clear Last" onclick="?">
<input type="reset" value="Clear All">
</form>
</body>
</html>
Try this:
function append(num) {
if (append.prev) {
//do something
console.log(append.prev);
}
var txt = document.getElementById("result").value;
txt = txt + num + " ";
document.getElementById("result").value = txt;
append.prev = num;
}
Working Fiddle (check in console)

Categories

Resources