How to call Javascript function and pass elements with HTML button? - javascript

I am trying to implement a Javascript function within an HTML button. Below is the Javascript and HTML that I am using. I want the submit button to call the function with the file_name and file_data being passed into the function, but I am not exactly sure how to do this. I know there is an onClick I can use, but I don't know how to pass the information from the file input into the function.
<form method="POST">
<div align="center">
<input type="file" id="myfile" name="myfile">
</div>
<br />
<div align="center">
<button type="submit" class="btn btn-primary">Add File</button>
</div>
</form>
function uploadFile(file_name, file_data) {
fetch("/upload-file", {
method: "POST",
body: JSON.stringify({ file_name: file_name, file_data: file_data }),
}).then((_res) => {
window.location.href = "/";
});
}

Creating a handleSubmit function which gets called from the forms onSubmit='handleSubmit()'.
The form information is acquired via: Object.fromEntries((new FormData(event.target)).entries());. which is of the type object.
function handleSubmit() {
let formValues = Object.fromEntries((new FormData(event.target)).entries());
/* call any function you want! */
}
<form action="/action_page.php" onsubmit="handleSubmit()">
Enter name: <input type="text" name="fname"/>
<input type="submit" value="Submit"/>
</form>
-------- EDITED I. Following the recommendation by: isherwood, your result should look something like this:
function logSubmit(event) {
let fieldValue = form.fname.value; //gets field value
event.preventDefault();
}
const form = document.getElementById('form');
form.addEventListener('submit', logSubmit);
<form id="form">
<label>Test field: <input type="text" name="fname"></label>
<br/><br/>
<button type="submit">Submit form</button>
</form>

In HTML there is actually an Event-Listener called "onclick".
Try using it on your submit button like this:
<button onclick="uploadFile(file_name, file_data)">Add File</button>

Related

PHP 2 actions from a single Button

I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:
I have the following code:
For the Submit button
<form method='POST'>
<div class="form-group">
<input type="text" name="s_amount" style='width:20%;' required>
<input type="submit" class="btn btn-primary" name="submit" value="Submit" />
</div>
</form>
<?php
$s_amount = $_POST['s_amount'];
echo $s_amount;
?>
AND for the Submit Code button
<button id="submitcode"type="button" class="btn btn-default">Submit Code</button>
<pre><code id="output">.../...</code></pre>
When the Submit code is pressed, this executes the following script
<script>
$(document).ready(function(){
$("#submitcode").on("click", function(){
ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R")
//arguments
var mysnippet = new ocpu.Snippet("V_CT="+$('[name="CT"]:radio:checked').val()+"\r V_TP="+$('[name="LENGTH"]:radio:checked').val()+$('#input2').val());
//perform the request
var req = ocpu.call("identity", {
"x" : mysnippet
}, function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
});
});
})
});
</script>
What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.
Many thanks !
try giving id to form tag and on click on submitcode button call the form using its id.
for ex.
<form method='POST'>
function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
// using form id call the form
$("#formdata").submit(); // it will simply submit the form.
});
});
<form method="post" id="formdata"> <!--assign id to form tag-->
</form>
Could finally do it very easily using js.
<input type="text" id="VTP" value="0">
and get the value in the javascript form
document.getElementById("VTP").value
# nikhil borikar: Thanks but it did not work

call javascript a function in html submit button

I have a form which I want to hide or show dependent on the users decision. I got following functions in an external javascript file:
function hide_element() {
$("form").hide();
};
function show_element() {
$("form").show();
};
and this is how I call those functions:
<button type="submit" onclick="show_element;">show</button>
<button type="submit" onclick="hide_element;">hide</button>
<form>
...
</form>
Unfortunately this does not work. Do you have any clues why this is the case?
Since we are using jQuery I would like to propose this approach:
HTML:
<button id='toggleMyForm'>hide</button>
<form id='myForm'>First name:
<br>
<input type=" text " name="firstname " />
<br>Last name:
<br>
<input type="text " name="lastname " />
<br>
<input type="submit" value="Submit"/>
</form>
jQuery:
var myForm = $('#myForm');
var toggleMyForm = $('#toggleMyForm');
toggleMyForm.on('click', function(){
myForm.toggle();
myForm.is(":visible") ? $(this).html('hide') : $(this).html('show');
});
Test here: http://jsfiddle.net/urahara/obm39uus/
NOTE: don't put yourself in the position where you have multiple submit buttons in a <form>, you can distinguish between them by using value attribute, but still in my opinion it's better to keep clean design with one submit per form.
don't repeat jQuery fetching calls. make a handle of a element:
var myForm = $('myForm'); then use it like this e.g: myForm.show()
replace show_element with show_element() & hide_element with hide_element() like below:
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
Now you try to call variables named show_element and hide_element. These doesn't exist.
Function has to be called with brackets. If you have no params, use ().
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
I recommend you to use <button type="button" class="hide">Hide</button>
And, in the js file :
$('button.hide').click(function() {
$('form').hide();
}
Same thing for the show button.
You've to replace "show_element;" with "show_element();".
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
But why?
The () Operator Invokes the Function.
Using the example above, show_element refers to the function object, and show_element() refers to the function result.
Example:
Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
http://www.w3schools.com/js/js_functions.asp
With "show_element" you are able to store the function itself (in a variable for example), but you don't execute it.
is this pseudo-code?
If not I would rewrite it like:
$form = $('#form_id');
function hide_element() {
$form.hide();
$form.submit();
}
function show_element() {
$form.show();
$form.submit();
}
And then:
<button onclick="show_element();">show</button>
<button onclick="hide_element();">hide</button>
<form>
...
</form>
I removed the type submit because it is not good to have more than one submit. Actually both are outside the form. In case you want to submit it I would put it like this:
<button onclick="show_element();">show</button>
<button onclick="hide_element();">hide</button>
<form>
...
</form>

Passing java-script variable to same form action php file argument

Having a html form with buttons, I wanted to pass the clicked button value (which is obtained as javascript variable 'tree') to the same form action as an argument to php script. My javascript for getting the button value is like,
<script>
function getVal(value)
{
var tree =value;
}
</script>
On form,
<button type="" name="btn" value="a" onclick="getVal(this.value)">a</button>
<button type="" name="btn" value="b" onclick="getVal(this.value)">b</button>
<button type="" name="btn" value="c" onclick="getVal(this.value)">c</button>
<input type="submit" value="Submit">
Basically, I would like to do something like,
<form action="backend.php" **js variable as argument** method="POST">
You have two options. The first would be to add a hidden field to the form to send as POST data, and the second would be to add it to the action, which will make it a GET variable.
Option 1:
<script>
function getVal(value)
{
document.getElementById('buttonValue').value = value;
}
</script>
<input type="hidden" name="btnValue" id="buttonValue" value=""/>
Option 2:
<script>
function getVal(value)
{
document.getElementById('myForm').action = "backend.php?btnValue="+value;
}
</script>
<form action="backend.php" id="myForm" method="POST">
With the first option you can get the value in PHP using $_POST['btnValue'] and in the second case you can use $_GET['btnValue']

Javascript innerHTML Not Posting

I am trying to get a function to print out whatever the user inputs into the text-box. I am using onClick as an attribute on my submit button. I know I set it up properly because it flickers the answer, but only for a split second. How can I get the input to stay on the page? Here's the code: HTML: Type what you want to post to the website!
HTML:
<div id="main_div">
<section id="leftbox">
<form name="mybox">
Type what you want to post to the website!:
<br />
<input type="textbox" size="15" maxlength="15" name="text" id="text">
<br />
<input type="submit" value="Submit!" onClick="doFirst()">
</form>
</section>
</div>
<div id="insert"></div>
Javascript:
function doFirst(){
text = document.getElementById('text');
insert = document.getElementById('insert');
if(text.value == "")
{
insert.innerHTML = "Please input something!";
return false;
}
else
{
insert.innerHTML = text.value;
}
}
try this:
Using type=button
<input type="button" value="Submit!" onClick="doFirst()">
OR using type=submit
<form name="mybox" onsubmit="doFirst(); return false;">
<input type="submit" value="Submit!">
</form>
Explain:
The action for onclick in submit button DO executed. You keep see the page does not have any changes, because of there are a FORM. And the key point: the form handle the submit action after the JS function doFirst() immediately. Adding the onsubmit in the form with return false to stop default action, means:
<form name="mybox" onsubmit="return false;">
<input type="button" value="Submit!" onClick="doFirst()">
</form>
To simplify the changes, use button instead of submit type, or using onsubmit instead of onclick in form trigger.
onClick="doFirst()"
gets converted into an anonymous function:
function(){ doFirst() }
and whatever that function returns determines if the submit should be completed or aborted, so you should use:
onClick="return doFirst();"
In other words, it's not enough that doFirst return something, whatever doFirst returns should be returned again inside the onClick.

Hide submit type input value from url

I have a form with GET method with some inputs like this:
<input type="text" name="something">
<input type="submit" name="submit" value="Click here to submit form">
I don't want the url to become
mypage.php?something=value&submit=Click+here+to+submit+form
I want to suppress the submit parameter in the url (should be like this: mypage.php?something=value).
I need only GET method please don't mention POST method.
Also you may mention to remove name="submit" but i need it also to identify this submit.
Also if there is a input from which is empty i don't want to show
<input type="text" name="input1">
<input type="text" name="input2">
<input type="submit" name="submit" value="Click here to submit form">
input1 gets value but if input2 doesn't have value the i want url like
mypage.php?input1=value
Thanks
If you don't want the submit parameter to show up in your GET request URL, don't give it a name, and instead use id or class to identify it uniquely:
<input type="submit" id="submit" value="Click here to submit form">
I would remove form submit the and just turn it into a button. Then I would use jquery to submit the form and do any logic processing.
<input type="test" id="favoriteCheese" value="nacho" />
<button id="submit" value="Click here to submit form">Click here to submit form</button>
$("#submit").on('click', function () {
var data = {};
var favCheese = $("#favCheese").val();
if(favCheese.length > 0) {
data.favCheese = favCheese
}
$.ajax({
url : ".../mypage.php",
data : data,
type : 'GET',
...
})
})

Categories

Resources