Using a form to run javascript method - javascript

I'm trying to run a JS method with a custom text variable as a parameter. I need to be able to write some text in a form, and then send that value to the method to execute it. I'm not sure why it's not working - it seems to be receiving the value of the VALUE as "" or blank. How would I go about doing this?
<FORM NAME="myform" ACTION="" METHOD="GET">
Choose a Place: <INPUT TYPE="text" NAME="inputbox" VALUE="" id = "place"><P>
</FORM>
<button type="button" onclick="buttonGenerator()">Generate Postcard</button>
<script>
var x = document.getElementById('place').value;
function buttonGenerator(){
generate(x);
}
</script>

Your x variable is being set when the script first runs (when the page is loading). You want to avoid setting it until the button is clicked. Simply move it into the function and you should be set:
function buttonGenerator(){
var x = document.getElementById('place').value;
generate(x);
}

Related

Comparing values with javaScript then redirect to another url if true

edit- the problem was in the redirection and Solved by Ahmed with the immediately invoked Function Expression aka IIFE
problem redirecting to another page, values are a string and the integer "CharFields" .. else statement works fine but the if statement when I type it correct the page just refreshes and nothing happens.
I made java function to get variables from a user input trcode
and made Django print the model in an input value those two works fine I tested them with printing,, the problem is in comparing the values and redirecting to the another URL
function readText () {
var value1 = document.getElementById("trcode").value;
var value2 = document.getElementById("trfcode").value;
if (value1 === value2) {
location.href="http://127.0.0.1:8000/myposts";}
else {
alert("You typed: " + "Wrong Password");}
}
<form onsubmit="return readText();">
<tr><td height="18" class="subheaderboldtext"> Enter Code:
<input id="trcode" maxlength="8" class="box">
<input class="submit" type="submit" value="SUBMIT">
<button id="trfcode" value="{{ user.profile.trf_code }}">z</button>
I have made some changes to your code. The button with id trfcode is being assigned a value already called user.profile.trf_code. If you replace it with the value you are trying to match it will work fine. For testing purposes I have changed your code a bit and have assigned it a value of z. Upon typing z in input and clicking submit gives me a +ve result.
I am guessing your main concern is reading the value of user-profile user.profile.trf_code. So you may wanna debug this and find out if you are getting a proper value back which you are expecting.
Few tips for debugging. When you are in such a situation, please first look at the values of each element and find out even if you are getting the values back. Then next step to find out if you are getting the same values or not and so on.
Putting value="z" makes this working. Please note that I have added extra logs and an alert. Please feel free to remove it.
EDIT:
If you see in the form, I have added a function wrapping your function. This is called immediately invoked Function Expression aka IIFE which basically is a function and can be called right there. Form creates an event, that event has a method called preventDefaults() which prevents the page from reloading or refreshing upon everytime you submit. I have wrapped your method under an IIFE to prevent the page from refreshing and then called your function. I would highly recommend you adding this as a part of your question though.
Your form,
<form onsubmit="return (function(event) { event.preventDefault(); readText()}) (event)">
<tr>
<td height="18" class="subheaderboldtext"> Enter Code:
<input id="trcode" maxlength="8" class="box">
<input class="submit" type="submit" value="SUBMIT">
<!-- <img src="/static/guest/images/querybutton.png" alt="Query Button" /> -->
</td>
</tr>
</form>
<button id="trfcode" value="z">z</button>
Javascript given below,
function readText() {
var value1 = document.getElementById("trcode").value;
var value2 = document.getElementById("trfcode").value;
console.log(`value1 = ${value1}`);
console.log(`value2 = ${value2}`);
if (value1 === value2) {
// location.href = "http://127.0.0.1:8000/myposts";
console.log(`I am good`);
alert(`You typed: ${value1}`);
} else {
console.log(`I am in else`);
alert("You typed: " + "Wrong Password");
}
}

Console.log data from HTML form input

https://codepen.io/anon/pen/NYaeXV
I am trying to log the value of a HTML form input. I put multiple options inside the CodePen. Here is my initial thought process.
<form action="">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value());
}
sConsole();
You need to use value instead of value() since value is not a function , also consider using e.preventDefault() to avoid the page reload one more thing , by adding sConsole() into your js file you're asking the function to be executed when the page load, you need to move your function to the submit event instead.
Here is a working example and Happy coding :)
function sConsole(event) {
event.preventDefault();
var data = document.getElementById("data");
console.log(data.value);
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="" id="form" onsubmit="sConsole(event)">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
</div>
You missed onclick or onSubmit , you should also use .value
function sConsole() {
var data = document.getElementById("data");
console.log(data.value);
//!!Option 1a
//console.log(data.submit());
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="">
<input type="text" name="data" id="data">
<button type="submit" onClick="sConsole()">Submit</button>
</form>
</div>
You were close, just a few things to consider.
Getting the value of an input field
The value attribute of an input element stores the text in the textbox. To retrieve, this in javascript, use ExampleElement.value, for example:
var dataValue = document.getElementById("data").value;
or
var data = document.getElementById("data");
var dataValue = data.value;
You can also specify the value attribute in the input tag with value="". This is useful if you want to prefill the input text box, for instance, if you send the user input to a php script for action and wanted to return the textbox with information already included.
Calling a Javascript Function
There are multiple ways to call a javascript function, including doing so when certain events occur. In your situation, you probably want the input value logged every time the user clicks submit. You could add an event listener, but for simplicity sake of understanding, let's just use inline code. Every time they submit, let's log it, so onsubmit="sConsole();". Now the submit action will run your logging function.
If you wanted to log every change while the user was typing, you would use an event listener with more complex evaluation of the input value.
Prevent Default
It's likely that you don't want the form to actually be submitted to the server and page reloaded every time the user clicks submit. By using event.preventDefault();, javascript prevents the usual action of submitting the form to the server and instead leaves the user input and the page as is.
If you want the textbox to be "erases" after each submit, it's probably best to reset the value in your function rather than submitting the form. To reset the value, you would simply do data.value = "".
Code Example
Putting it all together, here's an example code segment with comments about your original sample.
<form action="" onsubmit="event.preventDefault(); sConsole();"> <!-- use inline JS to print input to console on submit -->
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
<script>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value); // data is the element, and we want its value
}
//sConsole(); This would call it only on script load, which isn't what you want
</script>

Javascript fail to execute function - onsubmit and action

I am creating a page that is only javascript and html. I have 2 problems.
When it calls the function inputs() in this form, it fails at the first time and success on the next submissions.
<div id="container">
<form onsubmit="inputs()" action="#">
Variables: <input type="number" id="vars" size="1" required/>
Constraints: <input type="number" id="cons" size="1" required/>
<input type="submit" value="Submit">
</form>
</div>
I wasnt able to solve this but I skipped it because it still proceeds to the inputs() the next submissions.
But in my inputs(), i created a form dynamically. The form is created as this:
var form = document.createElement("form");
form.setAttribute("action","#");
form.setAttribute("onsubmit","solve()");
Now, when I submit the dynamically created form, the problem is it goes back to the first set of form. solve() was not called.
Why is it? What should be edited?
Thanks for the help in advance.
solve() has these lines of codes. It's just a test if it will successfully go into it but it fails. This just deletes all the elements.
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
This line
form.setAttribute("onsubmit","solve()");
isn't doing what you think it does. If it was in the actual html it would work but not now. What it does is just make the attribute appear in the console. The event handler isn't actually being set.
Instead do it via onsubmit property or addEventListener
form.onsubmit = solve; // now it must work
Try return false at the end of the function solve. this should work to show but would not perform action. Also add "return solve()" instead of "solve()".

Javascript function will not activate onClick

In my page head:
<script>
function formula()
{
document.forms["inquire"]["search"].value.scrollIntoView();
}
</script>
In my page body:
<div id="nav">
<form id="inquire" name="inquire" onSubmit="return false;">
Search or inquire here: <input type="text" id="search" name="search" value="<?php search($_GET['search']) ?>" autocomplete="off"/>
<input type="button" name="btnSearch" id="btnSearch" onClick="formula();"/>
</form>
</div>
What I want to happen here is that, when btnSearch is clicked, it activates formula(), taking the value from search in form inquire, and then scrolling to the value in a separate div I have called formula. This works if I put document.getElementById(this.form.search.value).scrollIntoView(); directly into the onClick for btnSearch, however it refuses to work no matter how I set it up as a function. Does anyone here know why it might be doing this, or how I can fix it?
It's not working because your function is erroneous:
function formula() {
document.getElementById(document.forms.inquire.search.value).scrollIntoView();
}
That code gets the value of the search field and uses it for an "id" lookup. It'd probably be a good idea to check that there actually is an "id" with the value typed in:
function formula() {
var element = document.getElementById(document.forms.inquire.search.value);
if (element) element.scrollIntoView();
}

document.write to current HTML page

I am a noob to programming, so I'd appreciate any advice from you more knowledgeable folks out there. I am working on a bit of javascript for a web page and I need the javascript to print to that current HTML page, preferably in the div tag I have set up for that purpose. Here's what I have so far:
<html>
<head>
<title>Tardy Reporting</title>
<script src="students.js" type="text/javascript">
</script>
</head>
<body>
<h1>Scan in Student ID</h1>
<form method="POST" name="idForm" onSubmit="getId(parseInt(document.idForm.studentId.value));">
<input type="text" name="studentId" id="studentId"/>
<input type="Submit" name="Submit" />
</form>
<div id="div1"></div>
<p>
</body>
</html>
and my JS file:
var studentNumberArray = [50011234, 50012345, 50013456];
var studentNameArray = ["Mike Simpson", "Greg Pollard", "Jason Vigil"];
var studentLastPeriodArray = ["George Washington", "Darth Vadar", "Obi Wan Kenobi"];
var tardyArray = [0, 0, 0];
function getId(studentId) {
for (i = 0; i < studentNumberArray.length; i++){
if(studentId === studentNumberArray[i]){
tardyArray[i] += tardyArray[i] + 1;
document.getElementById('div1').innerHTML='test';
}
}
}
Mind you, this is just the basic framework, so it's not nearly done yet, but the thing that is bugging me is that it'll go through the code correctly and print it out, but the result only lasts a fraction of a second on my browsers (chromium and firefox). Any help would be appreciated.
Here is an easier/better way to accomplish what you are trying to do
var students = {};
// Add students to object
students[50011234] = { 'id': '50011234', 'name':"Mike Simpson", 'lastPeriod':"George Washington", 'tardy':0 };
students[50012345] = { 'id': '50012345', 'name':"Greg Pollard", 'lastPeriod':"Darth Vadar", 'tardy':0 };
students[50013456] = { 'id': '50013456', 'name':"Jason Vigil", 'lastPeriod':"Obi Wan Kenobi", 'tardy':0 };
function getId(studentId) {
students[ studentId ].tardy += 1;
document.getElementById('div1').innerHTML='test';
}
Also, as pointed out below, you should change your button to not submit if that is not what you are intending to happen:
<form method="POST" name="idForm">
<input type="text" name="studentId" id="studentId"/>
<input type="button" onclick="getId(parseInt(document.idForm.studentId.value));" name="Mark Tardy" />
</form>
The reason why you see it only for a fraction of a second is that you are actually causing a submit. A submit is a full call back to the server which returns the page to its initial status.
To fix this simply make the function call on the onclick event of the button:
<html>
<head><title>Tardy Reporting</title>
<script src="students.js" type="text/javascript"> </script>
</head>
<body>
<h1>Scan in Student ID</h1>
<form method="POST" name="idForm" >
<input type="text" name="studentId" id="studentId" />
<input type="button" onclick="getId(parseInt(document.idForm.studentId.value));" value="submit" />
</form>
<div id="div1"></div>
<p>
</body>
</html>
What do you mean by "result"? It appears that you are setting the innerHTML of div1 to "test" over and over again.
Perhaps you mean to write
document.getElementById('div1').innerHTML += 'test';
Doing this is not efficient and it is preferable you concatenate on a string, or even better, join an array, before assigning the innerHTML.
but the result only lasts a fraction of a second on my browsers (chromium and firefox).
That is because you are submitting the page, so the page gets refreshed. You need to change the button type to button from submit. Also add a onclick to the button and call the js function getId
Forms are a special construct that allows communication with a server:
When a form is submitted, the form data is "POSTED" to a server via an HTTP request.
Typically, the browser displays the server's response as a new web page.
Forms use the action attribute to specify which server page should process the request
In your case, no action is specified, so the form POSTS to the current page, which is equivalent to refreshing the page. This means that all client-side (JavaScript) changes are wiped out, which is why you only see them for a split-second.
To achieve your desired result, change the input type from submit to button:
<input type="button" onclick=".." value="submit" />
Ideally, the student data exists in a database that is manipulated by code on a server. Your form would POST a request that returns an HTML page containing the desired data.
References
HTTP
Forms

Categories

Resources