Clilcking on a button is giving a Bad Path error - javascript

I'm trying to make a pen which incorporates the javascript exercises I'm learning. Here is the Pen: https://codepen.io/ychalfari/pen/JVYoNW
In this specific case I'm trying to accept an array from an input and run a function which sums the array when you click the button, and the result should show underneath.
When I click the button I either get an Error: "Bad Path /boomboom/index.html"
or nothing happens the page just kind of reloads and it takes me to the top of the page.
The HTML
<form id="sum-arr-form">
<div class="form-wrap" >
<label for="arr-to-sum"> Enter an Array to sum: <input id="arr-to-sum" class ="med-input" type="text" value = "">
<button class="btn1" onclick ="sumOfArray()">submit</div> </form>
<p>Result: <span id="demo"></span></p>
The Javascript
let inputArr = document.getElementById('arr-to-sum').value;
const add = (a,b) => a+b;
const sumOfArray = function() {
let sum = inputArr.reduce(add);
document.getElementById("demo").innerHTML = sum;};

You have some mistakes in your code.(button tag without type will trigger submit)
<button class="btn1" onclick ="sumOfArray()">submit
change this line to
<input type="button "class="btn1" onclick ="sumOfArray()" value="submit">
then get the value of input inside your sumOfArray function. (add the below 2 lines in your sumOfArray function) (waynelpu's answer above)
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);

The value get from input is string, if you want to process it as array you need to convert to correct type in js, try
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);

Related

How to read input box line by line in Javascript and return various values depending on input?

I am trying to create a function in Javascript which can read an input box line by line and return different values depending on the input.
For example, if someone enters several protein mutations on separate lines with the format Arg86Lys, I want the function to read the first three and last three letters to get Arg Lys. Then, if I have a value stored for Arg Lys (let's say 100), I want the output to be a textbox which prints out the value 100 (and prints out the rest of the values on separate lines).
I am stuck on how to read the input box value line by line, and only extract the first three and last three letters from each line. I also do not understand how I can store values (like Arg Lys = 100) and return said values when a certain input is found.
So far I have created a multiline textbox (in HTML) and tried to make a function that reads line by line:
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea rows = "5" cols = "60" name = "description">
</textarea><br>
<input type = "submit" value = "submit" />
</form>
<script>
var lines = document.getElementById('textareaId').innerHTML.split('\n');
for(var i = 0;i < lines.length;i++){
\\
}
</script>
</body>
textarea is an input, so its value is going to be stored in its value property, and passed along with the form submission. Here is an answer I found that goes over how to intercept the submit event for the form:
Intercept a form submit in JavaScript and prevent normal submission
Once you've intercepted the form submission event, pull the value from the description input, and do with it what you want from there
let form = document.getElementById("form");
let data = {"Arg Lys":100}; // store data like this
form.addEventListener("submit",function(e){
e.preventDefault();
var lines = document.getElementById('textareaId').value.split('\n');
document.getElementById('textareaId').value = '';
for(var i = 0;i < lines.length;i++){
let val = lines[i].substring(0,3);
let lastval = lines[i].substring(lines[i].length - 3)
document.getElementById('textareaId').value += val+' '+lastval + ' - ' +data[val+' '+lastval]+'\n';
}
})
<body>
<form id="form" action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea id="textareaId" rows = "5" cols = "60" name = "description"></textarea><br>
<input type = "submit" value = "submit" />
</form>
</body>
Are you looking for something like that?

Making live forms on html+js

I'm making site to make table game calculations easier. So, if simplify, I have a form like this:
<input id="x"/>
<input id="y"/>
And I want to collect data of this form in live time and process them like this immediately:
<span id="x-plus-y"/> in html and document.getElementById('x-plus-y').innerHTML = x*y in js
It's very simplified but I think you got the thought.
My question is how to process x+y immediately as the user enters the values into the input fields.
This is the simple approach you can go through. I have attached a keyup event listener on every input and then invoking the updateResult function which calculates the product and displays it within the result div.
HTML
Number 1 : <input type="number">
<br><br>
Number 2 : <input type="number">
<br><br>
<div id="result">
</div>
JS
const inputs = Array.from(document.querySelectorAll("input"));
const resultDiv = document.querySelector("div");
const numbers = [];
for(const input of inputs) {
input.addEventListener('keyup', updateResult);
}
function updateResult() {
let product = 1;
for(const input of inputs) {
product*= parseInt(input.value,10);
}
if(!isNaN(product)) {
resultDiv.innerHTML = "Product: " + product;
}
}

How do I wait for input to be filled in an html page and then print it's value to the console in javascript?

I have a HTML page with an input field
Someone enters some text into it
They click a button
I want to grab the value of the input field AFTER they click the button with some JS code(client-side) and then print it to the console/save it to a file.
How would I go about doing this?
I've tried looking but I can't find anything like this at all :/
Thanks! :)
This example should help you to achieve your goals.
const inputNode = document.getElementById('input');
const buttonNode = document.getElementById('button');
buttonNode.addEventListener('click', () => {
const inputValue = inputNode.value;
// do what ever you wan't
});
<input id="input" type="text" />
<button id="button">Click</button>
Try this:
// This function is called by the HTML code onclick on the button
var get_content_of_input = function(){
var user_input = document.getElementById("text_field").value;
// Now you can use the variable user_input containing the text
}
<input id="text_field">Please enter Text</input>
<button id="button" onclick="get_content_of_input()">Click here to sumbit</button>
The content of the text field will now be saved in the variable "user_input".

Delete button next to each array's value

I have a HTML-JavaScript script in which the user can insert data to a new array [] by using a form's text field and an insert button.
By pressing insert button, the user inserts the data typed into the array.
I have a function which prints all the values of the array into <p id="demo"></p> and runs itself every 100 milliseconds in order to be updated with the arrays values.
I also have a reset button to delete every array's value when clicked.
What I want to do is add a delete button next to each array's value in order to be easier for the user to delete the wrong value he inserted.
I am using this code to insert values and print them:
HTML:
<div align="center">
<form id="form1">
<input type="text" name="fname" id="fname" placeholder="Type here!">
</form>
<br>
<input type="button" id="Button Insert" onclick="myFunction()" value="Insert">
<input type="button" onclick="myFunction3()" value="Reset">
</div>
<p id="demo" align="center"></p>
JavaScript/JQuery:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
all_values.push(temp_val);
document.getElementById("form1").reset();
}
setInterval(function () {
$("#demo").html(all_values.join("<br>"));
}, 100);
function myFunction3() {
all_values.length = 0;
}
To be more specific I want something like these things: iOS example JSFiddle Example 1 JSFiddle Example 2.
Could you please help me? Thanks in advance.
I'd do it the other way around.
Remove setInterval as it's really bad way to do such things.
Remove white spaces from the id attribute (id="Button-Insert", not id="Button Insert")
Don't use onclick attributes. Instead, register click event handlers with jQuery
// caching is a good practice when you reffer to the same elements multiple times:
var all_values =[], demo = $("#demo"), form = $("#form1")[0], fname = $("#fname");
$('#Button-insert').click(function(){
var temp_val = fname.val();
all_values.push(temp_val);
// create delete button along with the value
demo.append('<p>'+temp_val+' <button value="'+temp_val+'" type="button" class="del-btn">Delete</button></p>');
form.reset();
});
$('#Button-reset').click(function(){
all_values = [];
demo.html('');
});
// event delegation for dynamic elements:
demo.on('click', '.del-btn', function(){
all_values.splice(all_values.indexOf($(this).val()), 1);
$(this).parent().remove();
});
JSFiddle
Simply create the delete buttons at the same time you create the table.
function loadvalues(){
var i, button;
$('#demo').empty();
for(i in all_values){
$('#demo').append(all_values[i]);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
}
Also you don't need to poll, you could simply add each one on demand with a function like this:
function addVal(){
var val = $("#fname").val(), i = all_values.length;
all_values.push(val);
$('#demo').append(val);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
I had some typos, the code works,
Check here:
http://codepen.io/anon/pen/QbvgpW

Add form input to array with javascript using unshift()

I am trying to add elements to an array via a form. I am using the unshift() method. The code below doesn't work and I would like to know why.
<form>
<input id="input"> </input>
<input type = "button" id="button"> Click me </input>
</form>
<script>
var input = document.getElementById("input").value;
var button = document.getElementById("button");
var myArray = [];
myArray.unshift(input);
button.onclick = function alerted (){
alert(myArray);
};
</script>
Your quoted code runs immediately when the page is loaded. The form field won't have anything in it then, so its value will be ''. When you alert that, the default toString operation on the array will result in '' and the alert will be blank.
You want to run your unshift code in response to a user event, such as the button being clicked, rather than right away. You can do that by setting input to be the element (remove .value from that line) and then moving your line with unshift into the function you're assigning to onclick, adding the .value there:
button.onclick = function alerted (){
myArray.unshift(input.value);
alert(myArray);
};
Other notes:
You never write </input>. Normally you don't close input tags at all. If you're writing XHTML (you probably aren't), you'd put the / within the main input tag like this: <input id="input" />. But again, you're probably not writing XHTML, just HTML.
The value (caption) of an input button goes in its value attribute, not content within opening and closing tags. (You would use opening and closing tags with the button element, not input.)
Taking all of that together, here's a minimalist update: Live copy | source
<form>
<input id="input"><!-- No ending tag -->
<input type = "button" id="button" value="Click me"><!-- No ending tag, move value where it should be -->
</form>
<script>
var input = document.getElementById("input"); // No .value here
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // Moved this line, added the .value
alert(myArray);
};
</script>
DEMO
You need to a) get the value in the click and b) return false if you want the button to not submit. I changed to button. Alternative is <input type="button" value="click me" id="button" />
You may even want to empty and focus the field on click...
<form>
<input id="input" type="text"/>
<button id="button"> Click me </button>
</form>
<script>
var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // get the value
alert(myArray);
return false;
};
</script>​
You're not getting the new value in the onclick function.
Try this: http://jsfiddle.net/SeqWN/4/
var button = document.getElementById("button");
var i = document.getElementById("input");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(i.value);
alert(myArray);
};​

Categories