GetElementById using variable is giving hard time - javascript

I am trying to use a variable to check what form ID has invoked the onClick event. I tried to go through everything on stack but I am still not sure why getElementById is returning null. Here is what my code looks like -
<form id="mul_f" name="mulf" method="post">
<select id= "mul" name="libraries">
<?php include (__DIR__ ."/include/syshost.php"); ?>
</select>
From Date:<input id="mul_fd" name="mulfd" type="date">
<button id="mulb" type="button" value="submit" onclick="display(this.form.id)"> Submit </button>
<div id="mul_chart_div"></div>
<div id="mul_table_div"></div>
</form>
my function -
function display(s) {
var x = document.getElementById(s); // returns null
var i;
for (i = 0; i < x.length; i++) { // errors out on x.length
document.write(x.elements[i].value + "<br>");
}
document.write(s.id);
document.write(x.length);
}

I tried this -
<form id="mul_f" name="mulf" method="post">
<select id= "mul" name="libraries">
<?php include (__DIR__ ."/include/syshost.php"); ?>
</select>
From Date:<input id="mul_fd" name="mulfd" type="date">
<button id="mulb" type="button" value="submit" onclick="display(this.form)">Submit</button>
<div id="mul_chart_div"></div>
<div id="mul_table_div"></div>
function -
function display(s){
document.write(s.id);
//var x = document.getElementById(s.id);
var x = s;
var i;
for (i = 0; i < x.length; i++) {
document.write(x.elements[i].value + "<br>");
}
document.write(s.id);
document.write(x.length);
}
this works now. Thanks Max, Adeneo Travis.

function onButtonClick() {
var form = getForm(this);
if (form)
alert(form.id);
}
function getForm(el) {
if (el == el.parentNode || !el.parentNode)
return null;
if (el.parentNode.tagName == "FORM")
return el.parentNode;
else
return getForm(el.parentNode);
}
window.addEventListener("load", function () {
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", onButtonClick);
}
})
<form id="form1">
<button type="button">In form 'form1'</button>
</form>
<form id="form2">
<button type="button">In form 'form2'</button>
</form>
<!--Button out of from-->
<button type="button"> Out of from </button>

this refers to the button element.
onclick="display(document.forms[0].id)">

Related

Javascript form clears instantly and flashes one answer

I have an html page that uses a javascript as a statistical calculator, it just needs to print the results into the text boxes i have displayed, but when i hit my submit button, the screen displays the mean value for a split second. no other fields work or stay.
My html file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<script src="script.js"></script>
<title>Script Calculator</title>
</head>
<body class="calculator">
<h2 class="stats">Statistical Calculator</h2>
<p> Enter 5-20 values within 0-100 inside the box below.<br>
Each value should be separated by one space.
</p>
<form>
<textarea id="numbers" name="numberarea" rows="4" cols="40"></textarea> <br>
<br>
<input type="submit" id="subbutton" onclick="performStatistics()"
value="Submit">
<input type="reset">
<br><br>
Max: <input type="text" id ="maxnum" name="max" readonly>
<br>
Min: <input type="text" id="minnum" name="min" readonly>
<br>
Mean: <input type="text" id="meannum" name="mean" readonly>
<br>
Median: <input type="text" id="mednum" name="med" readonly>
<br>
Mode: <input type="text" id="modenum" name="mode" readonly>
<br>
Standard Deviation: <input type="text" id="stddev" name="std" readonly>
<br>
Sum: <input type="text" id="sumnum" name="sum" readonly>
<br>
Variance: <input type="text" id="varinum" name="vari" readonly>
<br>
</form>
<hr>
ePortfolio
</body>
</html>
My javascript is as follows:
function performStatistics() {
var newarray = document.getElementById("numbers").value;
var array = newarray.split(" ");
for (var i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > 100) {
alert("Enter positive values from 0-100")
return false;
}
}
if (array.length < 5 || array.length > 20) {
alert("Enter at least 5 values & no more than 20");
return false;
}
document.getElementById("meannum").value = calcMean(array);
document.getElementById("mednum").value = calcMedian(array);
document.getElementById("modenum").value = calcMode(array);
document.getElementById("stddev").value = calcStdDev(array);
document.getElementById("sumnum").value = calcSum(array);
document.getElementById("varinum").value = calcVariance(array);
document.getElementById("maxnum").value = findMax(array);
document.getElementById("minnum").value = findMin(array);
return false;
}
function calcMean(array) {
return calcSum(array) / array.length;
}
function calcMedian(array) {
var med = 0;
var arraylen = array.length;
arraylen.sort();
if (arraylen % 2 === 0) {
med = (array[arraylen / 2 - 1] + array[arraylen / 2]) / 2;
//takes average of an even array
} else {
med = array[(arraylen - 1) / 2];
//takes middle value of odd array
}
return med;
}
function calcMode(array) {
var mode = [];
var counter = [];
var i;
var holder;
var maxfreq = 0;
for (i = 0; i < array.length; i += 1) {
holder = array[i];
counter[array] = (counter[holder] || 0) + 1
if (counter[holder] > maxfreq) {
maxfreq = counter[holder];
}
}
for (i in counter)
if (counter.hasOwnProperty(i)) {
//returns boolean value^
if (counter[i] === maxfreq) {
mode.push(Number(i));
//pushes value into (end of) array
}
}
return mode;
}
function calcStdDev(array) {
return Math.sqrt(calcVariance(array)).toFixed(2);
}
function calcSum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += Number(array[i]);
}
return sum.toFixed(2);
}
function calcVariance(array) {
var avg = calcMean(array);
var newarray = [];
var vari;
for (i = 0; i < array.length; i++) {
newarray[i] = (array[i] - avg) * (array[i] - avg);
}
vari = calcSum(newarray) / newarray.length;
return vari.toFixed(2);
}
function findMax(array) {
var newarray = array;
var maxnum = Math.max(newarray);
return maxnum;
}
function findMin(array) {
var newarray = array;
var minnum = Math.min(newarray)
return minnum;
}
You need to prevent the submit button from submitting the form.
window.onload=function(){
document.getElementById('subbutton').addEventListener('click', function(ev){
ev.preventDefault(); // prevent the page submit
});
}
You can remove the onclick from the HTML, and add this to your script:
// When the DOM (HTML) is ready
addEventListener('DOMContentLoaded', function() {
// When the form gets submitted (click on submit or enter key)
document.forms[0].addEventListener('submit', function (event) {
performStatistics();
// Prevent the form from refreshing the page
event.preventDefault();
});
});
Note: your script is included in the <head> of your document. Waiting for DOMContentLoaded will ensure the document is ready no matter where your script is called. But you could skip that part if you include your script at the very bottom, before the closing </body> tag.

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>

How to reuse code block in javascript

I am new to learning javascript and apologize if this question is too basic. I have tried to search for a solution but nothing has been clear to me. I have created this code in this link.
https://jsfiddle.net/5p7wzy9x/3/
var btn = document.getElementById("calc");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
var totalTb = document.getElementById("total");
totalTb.value = count ? output : "NaN";
});
var btn = document.getElementById("calcTwo");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = (total / count);
var totalTb = document.getElementById("total");
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
My question is, how would I go about being able to use the same code for the second "grade" button without having to copy and pasting the same code?
I saw that you can use functions to invoke the same code block but am confused how I would go about it. I apologize if this question has already been answered, but I have diligently searched and tried to figure this out on my own. Thank you in advanced.
Instead of passing anonymous functions (functions with no names) to your event handlers as data:
btn.addEventListener("click", function() { ...
set up those functions as "function declarations" so that you can call them by name. Then, instead of passing them into the .addEventListner() method call, you reference them by name (without parenthesis next to the name).
Here's an example:
// Both buttons are configured to call the same event handling function:
document.getElementById("btn1").addEventListener("click", doSomething);
document.getElementById("btn2").addEventListener("click", doSomething);
function doSomething(){
console.log("Hello!");
}
<input type=button id="btn1" value="Click Me">
<input type=button id="btn2" value="Click Me">
Here is how you can combine common code in one function:
var btn = document.getElementById("calc");
var btn2 = document.getElementById("calcTwo");
var totalTb = document.getElementById("total");
btn.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output < Infinity ? output : "NaN";
});
btn2.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
function getTotal() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
return output;
}
<form id="form1">
<input class="value" type="text" value="80" /><br />
<input class="value" type="text" value="50" /><br />
<input class="value" type="text" value="15" /><br />
<input class="value" type="text" value="30" /><br />
<input class="value" type="text" value="90" /><br />
<br />
<input type="text" id="total" />
<button type="button" id="calc">Calculate</button>
<button type="button" id="calcTwo">Grade</button>
</form>

how to validate URL in dynamically added textbox

how to check URL is correct or not when i will enter into dynamically added textbox .
here t3 is given as id of input tag but that is works only for first dynamically added textbox not for others.
how to validate another URL present into next dynamically added textbox ?
<script type="text/javascript">
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" id = "t3" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
</script>
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(document.getElementById('t2').value)||!regex .test(document.getElementById('t3').value))
{
alert("Please enter valid URL.");
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
HTML - index.html
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
var boxes = document.getElementsByTagName('input');
for(i = 0; i < boxes.length; i++) {
if(boxes[i].type == "text" && boxes[i].className==="urls" && !regex.test(boxes[i].value)) {
alert("Please enter valid URL. Error in Text Box "+boxes[i].value);
return false;
}
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' class="urls" id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
JS - script.js
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" class="urls" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
I think you can first try to add an "onchange" handler to the "TextBoxContainer" div and user event.target or event.srcElement to identify whether it is a textbox that triggered the "onchange" event. If the trigger dom is exactly the ones you want, then you can try to validate its value and if it is not, you don't need to do anything. If this is done, then the rest things will be simply add/remove textboxes to the container element. Below are some sample codes that may help:
<script type="text/javascript">
var _container = document.getElementById('TextBoxContainer');
function add(){
var _txt = document.createElement("INPUT");
_txt.type = "text";
_container.appendChild(_txt);
}
_container.onchange = function(event){
var _dom = event.target || event.srcElement;
if(_dom && _dom.tagName === "INPUT" && _dom.type === "text"){
//alert(_dom.value);
//You can validate the dom value here
}
};
document.getElementById('add').onclick=function(){
add();
};
</script>

JavaScript forms and functions

I am trying to write a simple random number generator, where you input 3 integers into forms. The program then returns a certain amount of random numbers between the other two values. When I open the page the forms are displayed but when I click the button to generate the random numbers nothing happens. Why is this happening?
<html>
<head>
<script LANGUAGE="JavaScript">
function randomFromTo(from, to)
{
return Math.floor(Math.random() * ((to - from) + 1) + from);
}
function include(arr, obj)
{
for(var j = 0; j < arr.length; j++)
{
if (arr[j] == obj) return true;
}
}
function RandomGen(form)
{
var enteries = new Array();
var number = form.from.value;
var top = form.top.value;
var size = form.inputBox.value;
var count;
for (count = 0; count < size; count++)
{
var num = randomFromTo(number, top);
if (include(enteries, num) == true)
{
count--;
}
else
{
enteries[count] = num;
}
}
var i;
for(i = 0; i <= enteries.length; i++)
{
document.write(enteries[i]);
document.write("<br>");
}
}
</script>
</head>
<body>
<center><h1>Random Number Generator</h1></center>
<form name="myform" action="" method="GET">Enter the Range of Values
<input type="text" name = "from" value="">to
<input type="text" name = "top" value="">
<p>Enter The Amount of Random Numbers Needed
<input type="text" name = "inputBox" value=""><p>
<input type="button" name="button" value="Generate" onClick=RandomGen(this.form)">
</form>
</body>
You have a syntax error here
<input type="button" name="button" value="Generate" onClick=RandomGen(this.form)">
should be
<input type="button" name="button" value="Generate" onClick="RandomGen(this.form)">
Also this part should be updated, not because it will cause an error but because it is 2011
<script LANGUAGE="JavaScript">
should be
<script type="text/javascript">
Update
Or:
<script>
no need for the type attribute because it is 2018!
You missed a quote:
<input type="button" name="button" value="Generate" onClick="RandomGen(this.form)">
onclick="RandomGen(this.form)"
That part of your code was malformed. onclick is always all lower case and you were missing a "
Your missing a "
<input type="button" name="button" value="Generate" onClick="RandomGen(this.form)">

Categories

Resources