Adding a Select Box Dynamically - javascript

I am creating an application using JSP.
In one of the Pages , the user needs to enter some Symptoms . Now i want to give a button. when the user clicks this button , a new select box is created .
I have searched a lot and can only find how to dynamically add options to select but i want new select box
Someone please help .

Here's a sample code:
<html>
<head>
<script type="text/javascript">
function addSelectBox ()
{
var parentDiv = document.getElementById ("main");
var selectElement = document.createElement ("select");
for (var i=0;i < 5;i++)
{
var option = new Option ("Text " + i, "Value" + i);
selectElement.options[selectElement.options.length] = option;
}
parentDiv.appendChild (selectElement);
}
</script>
</head>
<body>
<div id="main">
<input type="button" onclick="addSelectBox ()" name="clickme" value="Add Select Box" />
</div>
</body>
</html>
EDIT:
For JSP (if you have the options in an ArrayList):
<html>
<head>
<%
int totalElements = 5;
ArrayList r = new ArrayList (totalElements);
for (int i=1;i <= totalElements;i++)
{
r.add (String.valueOf (i));
}
%>
<script type="text/javascript">
function addSelectBox ()
{
var parentDiv = document.getElementById ("main");
var selectElement = document.createElement ("select");
var option;
<%
for (int i=0;i <= r.size();i++)
{
%>
option = new Option ('<%=r.get (i)%>', '<%=r.get (i)%>');
selectElement.options[selectElement.options.length] = option;
<%
}
%>
parentDiv.appendChild (selectElement);
}
</script>
</head>
<body>
<div id="main">
<input type="button" onclick="addSelectBox ()" name="clickme" value="Add Select Box" />
</div>
</body>
</html>

$(".your-button").click(function() {
var selectBoxHtml = ["<select>"];
var sourceItems = [4,5,6];
for (var sourceIndex = 0; sourceIndex < sourceItems.length; sourceIndex++) {
selectBoxHtml.push('<option value="' + sourceIndex + '">' + sourceItems[sourceIndex] + '</option');
}
$(this).after(selectBoxHtml.join("") + "</select>");
});
Once sourceItems is dynamic, be sure to escape it.

Related

Added text strings do not show in unordered list

I'm trying to code a small application that lets you dynamically add text strings in an unordered list, but the problem is the strings I pass as input do not show up after clicking the "Invia/Send" button. I have tried with a few solutions from other questions, but none of them worked. Any ideas?
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button id="add" onclick="addParagraph(paragraphArray)">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(paragraphArray){
var text = document.getElementById("insertParagraph").value;
var radio = document.getElementById("insertType");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.getElementById("beforeParagraph");
var selectedBeforeParagraph = sel.options[sel.selectedIndex].value;
for(i = 0; i < radio.length; i++){
if(radio[i].checked){
selectedInsertType = radio[i].value;
}
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>
There were a few issues:
A common problem people run into with the button tag is by default, it has a type of 'submit' which will submit the form. There are a few ways to disable this, my preferred method is to set the type as button.
Another issue is you don't have any content in the select box, which was causing an error trying to get the value of a select box with no options that can be selected.
I updated your radios, to use querySelectorAll and look for :checked that way you don't need to create an if statement.
I also removed the paragraphArray from addParagraph() since it is a global variable.
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button type="button" id="add" onclick="addParagraph()">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(){
var text = document.getElementById("insertParagraph").value;
var radio = document.querySelectorAll("#insertType:checked");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.querySelector("#beforeParagraph");
var selectedBeforeParagraph = (sel.selectedIndex > -1) ? sel.options[sel.selectedIndex].value : "";
for(i = 0; i < radio.length; i++){
selectedInsertType = radio[i].value;
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

How to accept the input from a text box and display in array format in jQuery?

I have written the code of taking input value from a text box and adding it to an array using the add button and also displaying the values of the array when the display button is clicked.
The thing is I did all this using JavaScript and now I want to do it using jQuery. I tried a code snippet from this website but it's not working. Please help.
<body>
<script src="jquery-3.3.1.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();"></input>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
<script>
var x = 0;
var sample = []; // <-- Define sample variable here
function add_element_to_array(){
$(document).on('click', '#btnSubmit', function () {
var test = $("input[name*='i_name']");
$(test).each(function (i, item) {
sample.push($(item).val());
});
console.log(sample.join(", "));
});
}
function display_array() {
var e = "<hr/>";
for (var y = 0; y < sample.length; y++) {
e += "Element " + y + " = " + sample[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</body>
You can use this code to get idea of how it should work. You can also check for non-empty value before pushing the value into the array as an empty value in array will not make any sense.
$(document).ready(function(){
var valueArray = [];
//add value in array
$('#button1').click(function(){
var textValue = $('#text1').val();
//push non empty value only
if(textValue.trim() !== ''){
valueArray.push(textValue);
//reset the text value
$('#text1').val('');
}
});
//display value
$('#button2').click(function(){
$('#Result').html(valueArray.toString());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
I have added the jquery script considering the following as your suggested html.
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
The inptArr must be a global array.
<script>
var inptArr = [];
$('#button1').on('click',function(){
if($('#text1').val() != '')
inptArr.push($('#text1').val());
});
$('#button2').on('click',function(){
var string = '';
var lastIndex = parseInt(inptArr.length - 1);
for(var i = 0; i <= lastIndex ; i++)
{
if(i == lastIndex)
string += inptArr[i];
else
string += inptArr[i] + ',';
}
$('#Result').append(string);
});
</script>
This is another way to achieve what you want with minor changes.
You have only one text input element so don't need any each loop.
document.ready() is needed if you define script from starting of the code because at starting there is no defined element that have an id as btnSubmit so this block must wait to dom elements to be ready.
Also you don't need pure javascript code getElementById on display_array() function when you use jquery. You can change it as $("#Result").html(e);
var x = 0;
var array = [];
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
array.push($("#text1").val());
});
});
function display_array() {
var e = "<hr/>";
for (var y = 0; y < array.length; y++) {
e += "Element " + y + " = " + array[y] + "<br/>";
}
$("#Result").html(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"/>
<input type="button" id="btnSubmit" value="Add"/>
<input type="button" id="button2" value="Display" onclick="display_array();"/>
<div id="Result"></div>
In your code functions passed to onclick attributes are binding the click event to a DOM - don't do that.
var array = Array();
var input = $("#text1");
var result = $("#result");
function add_element_to_array(){
var value = input.val();
array.push(value);
console.log("Add:", value);
// input.val(""); // bonus: clears input after adding text to an array
}
function display_array() {
result.text(array.toString());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1">
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
<input type="button" id="button2" value="Display" onclick="display_array();">
<div id="result"></div>

Dynamically array input with Javascript

I want to input the amount of array and the output will follow as it's amount.
Ex: If I put "7" in the input text. the result will show as much as 7.
Here's my code:
<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount");
for (i = 0; i < j.length; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You have something wrong on your JavaScript
See code:
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount")[0];
for (i = 0; i < j.value; i++) {
text += "The number is " + j.value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
.getElementsByName returns an array of elements, so you need to specify the index of your element so that you can access its properties.
Fiddle here

an unordered list from Array items using innerHTML in Javascript

I am trying to add a bulleted list to the page after the user enters 'exit' into a prompt; the list should not include the term 'exit'. I was able to get the list in full using document.write but this included the 'exit' and got rid of my page formatting. I am pretty sure I need to use innerHTML, but when I do this all I get is the page without any of the array items. Any help is greatly appreciated.
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script>
function askMe() {
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit'){
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
var MyList = getElementById('results');
MyList.innerHTML = "<li>"+list+"</li>";
}
}
</script>
</head>
<body onload="askMe()">
<ul>
<div id="results">
</div>
</ul>
<br/>
<br/>
</body>
you have to use document.getElementById() and also generate a string inside the loop and use inner html after the loop so that the previous li's dont get over written.
update the code portions like
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
and in html , remove the div inside ul and giv id to ul
<ul id="results">
</ul>
and here is the full code becomes:
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script type="text/javascript">
function askMe()
{
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit')
{
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++)
{
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
}
</script>
</head>
<body onload="askMe()">
<ul id="results">
</ul>
<br/>
<br/>
</body>
</html>
You should use MyList.innerHTML += "<li>"+list+"</li>"; (notice the use of += instead of =)
Also, change your <ul> HTML to be:
...
<ul id="results">
</ul>
...

Categories

Resources