Javascript Html Event handling - javascript

When I use this code, I am unable to get it to display the data upon clicking the display button. The code is supposed to save the input upon clicking the next button and display the array upon clicking display and clear the array when clicking clear. How do I go about resolving this?
Whenever I click the buttons nothing happens. I want to display the array inside the text area.
<html>
<head>
<script language = "javascript">
var full_name;
var dob;
var gender;
var memberList= new Array();
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
// Replace the contents of the textarea with the value in str
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
}
</script>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
</head>
<body>
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
</button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
</form>
</body>
</html>

your code is working..remove </button> in your html
I thing you expecting like this: declare the array like var memberList= [];.If you click the clear button Array was empty and textarea also empty.If you need only empty with array.remove document.getElementById("textBox").value=""; in clearlist()
var full_name;
var dob;
var gender;
var full_name;
var memberList= [];
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
document.getElementById("textBox").value="";
}
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()">
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
<input type = "button" value = "CLEAR" onclick ="clearList()">
</form>

you have written "</button>" as closing tag, which is incorrect syntax for input tag.
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"></button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
replace this with the following and your code will work fine.
<input type = "button" value = "NEXT" onclick ="saveMember()"/>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"/>
<input type = "button" value = "CLEAR" onclick ="clearList()"/>
also change these functions for proper functioning
function saveMember() {
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
memberList.push(full_name, dob, gender);
document.getElementById('full_name').value = "";
document.getElementById('dob').value = "";
document.getElementById('gender').value = "";
}
function clearList() {
memberList = [];
document.getElementById("textBox").value = str;
}

Related

Why can't I see the query parameters in the form present in the url?

I'm having a problem getting the form values by passing the two query parameters, id and type, from the url.
Let's assume the URL is:
... page.html?id=14&type=Title
I want the values of these to be shown in the form to then make the change later.
function getQueryVariable () {
var query = window.location.search.substring (1);
var vars = query.split ("&");
for (var i = 0; i <vars.length; i ++) {
var pair = vars [i] .split ("=");
}
}
function onLoad () {
var value = getQueryVariable ();
var id = document.getElementById ('id');
var type = document.getElementById ('type');
id.value = value;
type.value = value;
}
<div class = "container">
<form method ="post" id="save" action="javascript: myFunction()" onload="onLoad()">
<div class = "field">
<label for = "id"> ID: </label>
<input type = "number" id = "id" name = "id" />
</div>
<div class = "field">
<label for = "type"> Fragment Type: </label>
<input type = "text" id = "type" name = "type" />
</div>
<div class = "field">
<button type = "submit" class = "full"> Save changes </button>
</div>
</form>
</div>
As you can see from the code, I call the onLoad() function to load the data into the form.
I don't get any errors; the values of the getQueryVariable() function variables are correct, but I notice that it is not called.
myFunction() is not shown, but this is the function that will serve me later to modify the fields of the form.
Could you kindly help me?
First of all, you need to execute onLoad function,
then you need to create an object to store the values and pass it to another function.
And your loop is really out of the world, I corrected it, please try to understand my code and if you have questions feel free to comment.
Here you go, for query, I changed it to a string that you provided as an exemple, so it would work in snippet.
function getQueryVariable () {
var object = {}
var query = "id=14&type=Hello%20Title";
var vars = query.split ("&");
for (var i = 0; i <vars.length; i ++) {
let splitted = vars[i].split('=')
object[splitted[0]] = decodeURI(splitted[1])
}
return object;
}
function onLoad () {
var pairs = getQueryVariable ();
var id = document.getElementById ('id');
var type = document.getElementById ('type');
id.value = pairs.id;
type.value = pairs.type;
}
onLoad();
<div class = "container">
<form method ="post" id="save" action="javascript: myFunction()" onload="onLoad()">
<div class = "field">
<label for = "id"> ID: </label>
<input type = "number" id = "id" name = "id" />
</div>
<div class = "field">
<label for = "type"> Fragment Type: </label>
<input type = "text" id = "type" name = "type" />
</div>
<div class = "field">
<button type = "submit" class = "full"> Save changes </button>
</div>
</form>
</div>
Your getQueryVariable () function is not returning anything. You can try something like this:
function getQueryVariable () {
var query = window.location.search.substring (1);
var vars = query.split ("&");
var params = {}
for (var i = 0; i <vars.length; i ++) {
var pair = vars [i] .split ("=");
params[pair[0]] = pair[1]
}
return params
}
function onLoad () {
var params = getQueryVariable ();
var id = document.getElementById ('id');
var type = document.getElementById ('type');
id.value = params.id ;
type.value = params.type ;
}

how to add n number of input fields in html using js

I have to get 'n' - total number of names from the user and then create n number of fields for getting all the names. I've currently written this as:
HTML code:
<form action="/flight_ticket/book" name="myform" method="post">
.
.
.
Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>
</body>
JS code:
function addFields(){
var number = parseInt(document.getElementById("nooftickets").value);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Name " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
But when I run it on browser, after clicking the "Enter names", I don't see any changes in the browser!
What have I got wrong?
What you are doing is trying to fetch the value of the noofticktes which is defined as a name in the HTML but in your code, you are using document.getElementById('noofticktes').value which is throwing an undefined error as there is no id defined as noofticktes.
So, just change your code on from:
var number = document.getElementById("nooftickets").value;
To this:
var number = document.getElementsByName("nooftickets")[0].value;
you will be able to make your code work.
One small update in your code would be if you are trying to clear/remove all the contents of the element container just use the container.innerHTML='' instead of looping and removing each element.
Here is the updated Snippet of your code.
function addFields() {
debugger;
var number = document.getElementsByName("nooftickets")[0].value;
var container = document.getElementById("container");
container.innerHTML = '';
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Name " + (i + 1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
<form action="/flight_ticket/book" name="myform" method="post">
. . . Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container' />
</div>
<br/><br/>
</form>
function addFields() {
// body...
var input = '';
var number = document.getElementById('number').value;
for(var i=0;i<number;i++)
{
input +="<input id='number"+i+"' name='number"+i+"'><br>";
}
document.getElementById('container').innerHTML = input;
}
<form action="/flight_ticket/book" name="myform" method="post">
Enter the number of tickets to be booked:
<input name="nooftickets" id="number" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>

How to add info while copying from multiple fields using javascript?

How can I add JavaScript to a single button as to copy text to the clipboard from multiple HTML inputareas including fixed text, while inserting a line break between each field?
To give you a better idea, it's simply a webpage that will allow us at work to take very repetitive notes that we always write (same points) made of 10 points, and with a click it'll copy the fields and the text that refers to the input in a form that is ready to be pasted anywhere.
<!DOCTYPE html>
<head>
<title>Repeater</title>
</head>
<body>
<button id = "button" onclick = "myFunction()">CLICK ME!</button>
<input class = "text" name = "text" type = "text" id = "textone">
<input class = "text" name = "textone" type = "text" id = "texttwo">
<input class = "text" name = "texttwo" type = "text" id = "textthree">
<input class = "text" name = "textthree" type = "text" id = "textfour">
<input class = "text" name = "textfour" type = "text" id = "textfive">
<script>
var total;
function myFunction(){
var inputarray = document.getElementByClass("text);
for(var i = 0;i < inputarray.length; i++){\
var now = inputarray[i].value;
total = total + now;
total = tatal + "____________________________________________________________________________"
}
total.select();
document.execCommand("Copy");
}
</script>
</body>
</html>
Try this

Trying to add an option to select with append, and nothing happens

My code has two sections: a section to input new items, and a section to interact with them. I'm trying to update the dropdown list every time a new item is added with jQuery, but my current method does nothing. By nothing, I mean that the dropdown list would remain empty. I've tried previous answers to this question, but none worked. (I'm pretty new to Javascript, so me just being a noob is completely possible).
Here's the html:
<!DOCTYPE html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "deletion.css"></link>
<script src = 'chemical.js'></script>
</head>
<body>
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button id = "newChemicalButton" onclick = "addChemical()" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
</body>
And the Javascript:
chemicals = [];
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append('<option value = "' + chemical.name + '"> ' + chemical.name + '</option> \n');
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}
There are a couple of things going on. First of all, When you press the submit button it tries to submit the first form. Second: It seems like the onclick event is not binding to the method which should add the item to the dropdownlist.
I've updated a couple of things:
Added $(document).ready(...); as it is best practice.
I've removed the inline onclick and bind the click event via jQuery.
JSFiddle here...
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button type="button" id = "newChemicalButton" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
and the JS:
$(document).ready(function(){
var chemicals = [];
$("#newChemicalButton").on("click",function(){
addChemical();
});
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append("<option value=" + chemical.name + ">" + chemical.name + "</option>");
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}
});
Possible the "\n" behind the append code make this not working. Try to remove it.

How to process onchange events for select elements which is dynamically created using javascript?

I have to create a few "select" elements in a html file dynamically.
And I also intend to create the same amount "select" elements according to the value of
the former created "select" elements.
Thus I will have a set of "select" elements pair.
When the first "select" element's selected value is changed,
the second "select" elements will refresh its options using the according records in a database.
My problem is I can't receive the correct value of the first "select" element.
Everytime when the onchange event is called, the value passed on to onchange function( in my case, it's called "fillSource()" is the value before the change happened instead of the changed selected value.
Do anyone know how to solve this problem?
The following is my javascript code:
<script>
var selectCount = 1;
var cats = #{dropCatsJson};
var subcats = #{dropSourceJson};
function addNewSource() {
var inputchange = document.createElement('select');
inputchange.options[0] = new Option("pls Select", "0");
inputchange.id="schange";
var input1 = document.createElement('select');
for( var i=0;i< cats.length;i++ ) {
var s = cats[i];
input1.options.add( new Option(s.Name, s.Id) );
}
input1.id = 's' + selectCount;
//input1.onchange = new Function("alert(\"input1 changed\")");
input1.onchange = new Function("fillSource(" + input1.value + ")");
document.getElementById('newSource').appendChild(input1);
document.getElementById('newSource').appendChild(inputchange);
selectCount = selectCount + 1;
}
function fillSource(input1)
{
var dropsub = document.getElementById("schange");
dropsub.options.length = 0;//clear all the options.
for( var i=0;i< subcats.length;i++ ) {
var s = subcats[i];
if( s.ParentId == input1.value )
{
dropsub.options.add( new Option(s.Name, s.Id) );
}
}
}
</script>
===============================================================================
final code that works.
Please notice that you should add onchange event for newly created
select elements like this:
input1.onchange = function(){fillsource(input1.value)};
here is my test.html code:
<html>
<script type="text/javascript">
var selectCount = 1;
function addNewSearch()
{
//alert("add");
var input1 = document.createElement('select');
input1.options[0] = new Option("s1","1");
input1.options[1] = new Option("s2","2");
input1.name = 's' + selectCount;
input1.id = 's' + selectCount;
input1.onchange = function(){fillsource(input1.value)};
document.body.appendChild(input1);
selectCount = selectCount +1;
//alert(selectCount);
var selcount = document.getElementById('selCount');
selcount.textContent = selectCount;
}
function fillsource(ivalue)
{
alert(ivalue);
}
</script>
<form name= "Search" id= "SearchForm" method= "post">
<select name= "SearchWhat" onchange = "setSearchField()">
<option value = "both"> Both Event and Task </option>
<option value = "event"> Event </option>
<option value = "task" > Task </option>
</select>
<label id="selCount"></label>
<input type="submit" value= "submit" name = "btn_submit"/>
<input type="button" name= "newsearch" value= "New Search" onClick= "addNewSearch()">
</html>
You're capturing the value at the time you create the select element, and hard-coding it into the onchange function. You need to use a closure:
input1.onchange = (function(input1) {fillsource(input1.value)})(input1);

Categories