Set Input Value with Javascript - Wont POST on Submit - javascript

I'm trying to get data from an API and post it to a database, the form I have worked when you manually input data. but when you set the data from the API request - it updates on the page. Although shows blank when it posts.
I'm using
document.getElementById('Title').value = item.volumeInfo.title;
to get the "Value" in an Input.
and
<div class="form-group">
<label for="name">Authors</label>
<input class="form-control" type="text" value="" id="Author" ng-model="book.Author" required="required"/>
</div>
to attach to form.
<button class="btn btn-primary" ng-disabled="AddNewForm.$invalid ||
isUnchanged(book)" id="add-new-btn"
ng-click="New_Book(book)">Add</button>
Why is it submitting as blank?

Your form elements submit their value via their “name” attribute... does you input element generate a name attribute? If not, this is why it won’t work.
Eg
<input name=“foo” value=“bar”/>
Submits as:
?foo=bar

Your question isn't clear enough for me. But I've tried to make a quick example and make it as general as possible to let you work with your form inputs!
Here is a Live Preview
HTML
<form action="post" id="myForm">
<input type="text" id="title">
<input type="submit" value="Click To Update">
</form>
<h2 id="result"></h2>
JavaScript
// Select our main elements (form, text input, result heading)
const form = document.getElementById("myForm");
const titleInput = document.getElementById("title");
const result = document.getElementById("result");
form.onsubmit = function(e) {
// Don't refresh the page
e.preventDefault();
// Set the input value into the result heading
result.innerHTML = titleInput.value;
}
This solution allows you to write anything in your input, and after submitting your form. You can use that data elsewhere.

Related

Page is refreshing on JSON request

I am trying to build a page that would allow a user to input text into a text field and hit enter on their keyboard and it would return the top 10 Wikipedia entries with that text.
Currently, my concern is that the page refreshes every time it fetches the JSON. I attempted the e.preventDefault() method, as I read about on other questions, but it isn't working. Can someone help me understand why this auto-refresh is happening, and how to fix it? Thank you.
Here is my HTML:
<div class="container-fluid">
<form action="#">
<input id="search" name="query" onkeyup="" type="text"></input>
</form>
</div>
<div class="main"></div>
</div>
And here is my Javascript:
$(document).ready(function() {
$("#search").on("keyup", function(e) {
// attempt to prevent page refresh
e.preventDefault();
// if key pressed is "enter"
if (e.keyCode == 13) {
// retrieve user input
var search = document.getElementById("search").value;
// build Wikipedia API url
var request = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + search + "&format=json&callback=?";
$.getJSON(request, function(json) {
var x = json.query.search[0]["snippet"];
$(".main").html(x);
});
};
});
});
Here's a link: https://codepen.io/lieberscott/pen/RLVaGE
Because you submit the form (pressing enter does that). The form submits to the current page which looks like a reload.
<form id="searchform>
<input id="search" name="query" onkeyup="" type="text"></input>
</form>
$('#searchform').on('submit', function(e){
e.preventDefault();
// your magic here.
});
The preventDefault stops the key UP, but by that time, you've already started submitting. The poreventDefault stops the enter getting input as text (you can check this with a textarea). If you'd change it to a letter, say A, you'd type the A, but not see it.
You can also remove the form itself, keeping just the input, if that doesnt create other issues, resulting in less HTML, which is nice.
Remove <form> tag from your HTML.
You are using a form and on enter/return it will try to submit the form.
Unless there is a button type="submit" or input type='submit' remove the form and use only input
<div class="container-fluid">
<input id="search" name="query" onkeyup="" type="text"></input>
</div>
<div class="main"></div>
</div>

How do I keep track of all inputs that have been submitted

I'm trying to keep track every time someone submits a name using data-name only. How do I alert the user to let them know that the contents were posted to the website or not and what other names have been submitted.
<div id="container">
<form method="POST" action="#">
<label class="large">Please enter your name
<input id="textbox" class="name" data-name="" pattern="[a-zA-Z0-9]{1-45}">
</label>
</form>
</div>
This is the JQuery I'm using:
//When the form is submitted
$("#form").submit(function(){
//get the value of the input
var input = $('#textbox').val();
//insert it into the data-name attribute
var name = $("#textbox").attr("data-name", input);
//Aler the user
$("input[data-name]").val(function(){
alert($(this).data('name'));
});
});
I think that your jquery selector is incorrect.
$("#form") means that it is targeting an element with the id of "form". In order to make that work, you would need to give your form element an id of form. E.g.
<form id="form" method="POST" action="#">
In order to alert the value of the textbox however, you do not need to put the value into a data-name attribute but instead get the value out of the form when submitting.
$('#myForm').submit(function(e){
alert(e.target.foo.value);
})
See the following fiddle, for an example:
https://jsfiddle.net/dgw3bw63/

How can I submit multiple dynamically generated forms with a single submit button using Javascript? [partial progress]

I am having a bit of trouble with some code. I am attempting to submit multiple forms. The first form is immediately visible, and the second can be added to the page when the user clicks an "Add Another Form" button (think of this like a referral system a user can add multiple referrals to).
So far I am able to submit one form and make more than one form appear on the page, however submitting any more than the first visible form is a challenge. Here is my code so far:
The form (all forms are clones):
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input id="name" type="text">
<input id="phone_number" type="text">
<input id="addanother" type="button" class="formBtn lrgBtn addanother" value="Add Another Form" >
<input type="hidden" name="retURL" value="https://www.example.com/thank-you/">
<input type="button" value="Submit Now" class="loopStarter multiRefHide formBtn" onclick="submitFormLoop()">
</form>
JavaScript for Form Submissions (SubmitFormLoop function):
var formCounter = 0;
var ellipsesCount = 0;
function submitFormLoop(){
if(typeof document.forms[formCounter]!= 'undefined'){
if($('.error:visible').length>0){
return false;
}
document.forms[formCounter].mySubmit.click()
if($('.error:visible').length>0) return false;
$('#submitting').show();
$('#supportCase').hide();
document.getElementById('submittingText').innerHTML = "Submitting your form(s)."
setInterval(function(){
ellipsesCount++;
var dots = new Array(ellipsesCount % 8).join('.');
document.getElementById('submittingText').innerHTML = "Submitting your form(s)" + dots;
}, 300);
setTimeout(function(){submitFormLoop()},1500)
formCounter++
}else{
window.location = "https://example.com/thank-you";
$('input[type="submit"],.addanother').hide()
formCounter = 0;
}
}
Again I can get the first one to submit, but I can't seem to get the function to loop. Any advice on this matter is very welcome, whether it is a small tweak or a recommendation to scrap my code completely.
Thank you all very much.
You cannot submit multiple form elements from the same page.
But you can get the behavior you desire two ways:
Submit the forms using AJAX (using XMLHttpRequest or a helper library like jQuery).
Reformat your inputs to use a single form element.
To do the latter, PHP programmers1 typically use the syntax:
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input name="contacts[0][name]" type="text">
<input name="contacts[0][phone_number]" type="text">
<input name="contacts[1][name]" type="text">
<input name="contacts[1][phone_number]" type="text">
<input name="contacts[2][name]" type="text">
<input name="contacts[2][phone_number]" type="text">
</form>
Notice the [<integer>] in the syntax. In PHP, the $_POST variable will contain data like these as an indexed array.
Your button can then add additional input elements in the same format:
<input name="contacts[3][name]" type="text">
<input name="contacts[3][phone_number]" type="text">
On form submission, you can then retrieve these fields like so:
foreach($_POST['contacts'] as $person){
echo $person['name'];
echo $person['phone_number'];
}
1 I assume you're using PHP since your form's endpoint is submission.php.

append div value into url, along with user input from text field using Get submitting method javascript

i'm trying to add value of a div into the URL, then submit the form using GET so i can retrieve the data from the URL to display on my result page. But i'm not sure how to do that.
For example:
Code:
<form action="Receipt.html" method="GET">
<input type= "text" id="Name" name="txtName"/>
<div id="total">30</div>
<input type="submit" value="Purchase" class="submit"/>
</form>
I need to pass the value of "total" along with Name to the URL when user hit submit button.
I hope that make sense. Thank you very much!
With use of jquery we can do this. Try this one...
Html:
<form action="Receipt.html" method="GET">
<input type= "text" id="Name" name="txtName"/>
<div id="total">30</div>
<input type= "hidden" id="txttotal" name="txttotal"/>
<input type="submit" value="Purchase" class="submit"/>
</form>
Javascript: in document ready function
$('#txttotal').val() = $('#total').text();
In next page you can get txttotal
You can get your url from form by using:
var url = $("form").attr("action");
// add value
url+= "?divValue=" + $("#total").html();
// then you use jquery/ajax get as you planed.
if your value in div is fixed or changes once so you can directly place in action, like
<form action="Receipt.html?total=30" method="GET">
Also, using ajax will be a better option if value changes with some changes in form.

How to autosubmit a form in javascript?

I have a form with an input text field which imports data every couple of seconds and display it in the form field , let us say :
<input name="code" id="code" type="text" size="64" maxlength="128" />
and a submit button and my form has the formname form1.
I want the submit button to be clicked as soon as the data in the form field is changed.
I did try to do the following. In the header I did add the follwoing javascript:
<SCRIPT LANGUAGE="javascript">
function send_data()
{
document.form1.submit();
}
</SCRIPT>
and on the form :
<input name="code" id="code" type="text" size="64" maxlength="128" onchange="send_data();" />
but it didn`t work..
Any help ?
Thanks
Something like this would work:
<form action="#">
<input type="" id="input" />
<button type="submit"></button:>
</form>
<script>
function send_data() {
document.forms[0].submit();
}
window.onload = function(){
var input = document.getElementById('input');
input.onchange = send_data;
}
</script>
But I'd add a few caveats:
I'm assuming there is only one form on the page. You would be safer assigning and ID to your form and using getElementById and referencing that instead of document.forms[x]
The change event will only happen after you lose focus on the input, which I probably what you want? Just making sure it's expected behavior
Without knowing why you need to do this, I'd note that it could potentially be very annoying to the user, as submission will trigger a new page load. You may be better off doing a submission via ajax so as not to disrupt the user's browsing. If you do this, I strongly recommend a JS library to handle this.

Categories

Resources