separate two html forms - javascript

I create a two forms here http://jsfiddle.net/B9r22/8/ and when you submit them, they convert to JSON, and the problem is when you submit the first form and then the second form, there are both data from form in JSON, how can I reset forms or seperate them?
<form name="first" id="1" action="" method="post">
Which city is in Great Britain?<br/>
London:<input type="radio" name="first" data-questionid="1" value="11"/><br/>
New York:<input type="radio" name="first" data-questionid="1" value="12"/><br/>
<p><input type="submit" /></p>
</form>
<form name="second" id="2" action="" method="post">
Which city is in USA?<br/>
Washington:<input type="radio" name="second" data-questionid="2" value="13"/><br/>
Tokio:<input type="radio" name="second" data-questionid="2" value="14"/>
<p><input type="submit" /></p>
</form>

Use the form as scope when you get the radio buttons:
$('input[type="radio"]:checked', this)
Demo: http://jsfiddle.net/B9r22/11/

You can use a form reset, this will set inputs to their default values, but ignores some fields like type=hidden
$('#1')[0].reset();

As far as I can see, the problem lies in line 6. Your script collects data from all input fields in the whole DOM (document) with a type of radio. Instead, give the selector the context of the currently submitting form to only match those particular fields (using $(this).find where $(this) refers to the submitted form):
Change line 6 to $(this).find('input[type="radio"]:checked').each(function(){
http://jsfiddle.net/B9r22/12/

You need to limit the
$('input[type="radio"]:checked')
to the submitted form:
$('form').submit(function() {
var form = $(this);
//....
$('input[type="radio"]:checked', form).each(function(){
//...
http://jsfiddle.net/B9r22/9/

you should use $(this)
$(this).find('input[type="radio"]:checked').each(function(){
http://jsfiddle.net/B9r22/10/

Related

How to use getElementById on a link to pick up textfield value

I want use document.getElementById('YourElementId') to pick up the Textfield value and then send it to another page called request.php as URL parameter.
Example, if i type (3) on the Textfiled and click submit, the Link will pick up the form variable as url parameter just like the folowing (.../requst.php?=id=3) Onsubmit.
Bellow is my textfield and the submit link/button but it doesnt work. Someone please help me.
<input name="consigno" type="text" id="YourElementId" value="3">
ENTER
Actually you can do this by using html form. This will do same thing.
<form method="GET" action="remote.php">
<input name="nav" id="YourElementId" type="text" value="3">
<input type="submit" value="ENTER">
</form>

jQuery targeting selector by input type and form name

I want to target any input of text type belonging to a form of a specific name. Because the form will have numerous input fields, I don't want to target a particular input name, but rather, capture the blur (or focusout) event for any input[type="text"] occurring within the form wrap.
My present code, which doesn't work:
$( document ).ready(function() {
$('form[name="tax_form"] input[type="text"]').on("blur",function() {
alert($(this).val());
});
});
I answered my own question. Because the code sample is essentially correct, there is no need for multiple people to try to solve the unsolvable. The problem had something to do with where I placed the javascript code, and nothing to do with structure or syntax of the code, itself.
The way the event "change" works is what it sounds like you want. An event handler doesn't actually fire when the input is clicked or if text is keyed in, it fires when text is entered and then the input loses focus.
In the following Snippet the same selector you are using is delegated to the "change" event. You'll notice that the ['tax_form'] has 4 text inputs yet the last one is the only one working. The reason is because if an input isn't assigned a type attribute, then by default type is 'text". So when using a selector based on an input's type="text", you must keep that in mind. So if you are in full control of your HTML, make sure that each input has a type attribute with an explicit value, or use classes which is better IMO.
SNIPPET
$(document).ready(function() {
$('form[name="tax_form"] input[type="text"]').on("change", function() {
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='notIt'>
<fieldset>
<legend>Not a Tax Form</legend>
<input>
<input type="text">
<input>
<input type="text">
</fieldset>
</form>
<br/>
<br/>
<form name='stillNotIt'>
<fieldset>
<legend>Still not a Tax Form</legend>
<input type="text">
<input>
<input type="text">
<input>
</fieldset>
</form>
<br/>
<br/>
<form name='tax_form'>
<fieldset>
<legend>Tax Form</legend>
<input class='klass' value='TEXT INPUT BY DEFAULT'>
<input value='TEXT INPUT BY DEFAULT'>
<input name='text' value='TEXT INPUT BY DEFAULT'>
<input type='number'>
<input type='text' value='THIS ONE COUNTS'>
</fieldset>
</form>
Previous commentators were right, that my code was fine as-is. I took my selector code out of a header script file, and placed it at the bottom of my footer script, and it worked as expected.
In the end, it wasn't my code that was the problem, but rather something to do with where I placed it. Possibly other javascript or jQuery code stepping on it.
Your code should work fine. Here's a working example of it to prove it's working. The tax_form fields should console.log() on blur. The another_form should not.
$(function() {
$('form[name="tax_form"] input[type="text"]').on("blur",function() {
console.log($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Tax Form</h1>
<form name="tax_form">
<input type="text" name="first" value="first">
<input type="text" name="second" value="second">
<input type="text" name="third" value="third">
</form>
<h1>Another Form</h1>
<form name="another_form">
<input type="text" name="first2" value="first2">
<input type="text" name="second2" value="second2">
<input type="text" name="third2" value="third2">
</form>

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.

How to add a hidden list of IDs to a form in Javascript?

I've got a simple form in html:
<form action="" method="post">
<input id="title" name="title" size="30" type="text" value="">
<input type="submit" value="Save this stuff">
</form>
I also have a file upload on the page, which handles uploads using ajax and adds the files to a mongoDB. The file upload returns the mongoDB id of the file (for example 12345) and I want to add that id to the form as a hidden field so that the id is POSTed to the server upon submitting the form. Since the user can add multiple files though, I want to add a list of id's to the form.
I found how I can add one hidden field to a form from javascript, but this always handles a single field, not a field with multiple values. So I thought of adding a checkbox field to the form so that I can submit multiple values in one element, but it kinda feels like a hack.
Can anybody hint me in the right direction on how I can add a hidden list of values to a form using Javascript? All tips are welcome!
[EDIT]
In the end I would like the form to look something like this:
<form action="" method="post">
<input type="hidden" name="ids" value="[123, 534, 634, 938, 283, 293]">
<input id="title" name="title" size="30" type="text" value="">
<input type="submit" value="Save this stuff">
</form>
I am not sure if I understand your question correctly, so I may just be guessing here.
Try adding multiple hidden inputs with a name such as ids[] so that they will be posted to the server as an array.
Example:
<form action="" method="post">
<input type="hidden" name="ids[]" value="123">
<input type="hidden" name="ids[]" value="534">
<input type="hidden" name="ids[]" value="634">
<input type="hidden" name="ids[]" value="938">
<input type="hidden" name="ids[]" value="283">
<input type="hidden" name="ids[]" value="293">
<input type="submit" value="Save this stuff">
</form>
Why not simply concatenating all the ids into a string like so "123,456,890,..etc" and then adding them as a value to ids inupt. When you need them, simply split by ',' which would give you an array with ids?
Todo so only with javascript something like this should work
var elem = document.getElementById("ids");
elem.value = elem.value + "," + newId;
Do you mean that for each time the user clicks the 'upload' button you need to add a hidden field to the form?
Can you post the entire form, that should clear things up...
[Edit]
you could store the id's in an Array, everytime an id should be added to the hidden field's value you could do somthing like:
$('#ids').attr('value', idArray.join());
I'm just typing this out of the box so excuse any little errors

adding inputs to html form, using javascript

I have an html form that I would like to add inputs fields to using javascript. Originally I had the input fields by themselves underneath the 'body', and the following was able to add the fields:
// Create number input field
var phoneInput = document.createElement("INPUT");
phoneInput.id = "phone" + instance;
phoneInput.name = "phone" + instance;
phoneInput.type = "text";
// Insert that stuff
document.body.insertBefore(document.createElement("BR"), element);
document.body.insertBefore(phoneLabel, element);
document.body.insertBefore(phoneInput, element);
I then added a 'form' element around the original inputs in the html file.
<body>
<form action=searchform.php method=GET>
<LABEL for="phone1">Cell #: </LABEL>
<input id="phone1" type="text" name="phone1">
<input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" />
</form>
</body>
Now the button doesn't add new text boxes. Have I structured this incorrectly?
Thanks!
This is because you are appending the elements to the body, which means that insertBefore cannot find element (because it's in the <form>, not the <body>), so it never gets inserted.
A quick way to fix this would be to use document.body.firstChild.insertBefore. However, if the form is no longer the first element in the body, this will no longer work.
A cleaner, better way would be to give your form an ID (e.g. <form id="myform">), and then access the form using: document.getElementById("myform").insertBefore. Then you can place your form anywhere, and it will still be accessible using the ID.
Easiest would be to use jQuery. Add an ID to your form, for easier reference:
<form id="myform" action="action" method="GET">
<input type="hidden" name="a" value="1"/>
<input type="hidden" name="b" value="2"/>
</form>
<script type="text/javascript">
$("#myform").append('<input type="hidden" name="c" value="3"/>');
</script>
You can later change the value of your new input, by easily referring to it:
$("#myform input[name='c']").val(7);
Gve the form an id
<form id="myForm" action="searchform.php" method="GET">
Create the JavaScript elements just as you used to, then you can just add the elements like so:
var f = document.getElementById('myForm');
f.appendChild(document.createElement('br'));
f.appendChild(phoneLabel);
f.appendChild(phoneInput);
(insertbefore would work on f as well, although I think this is more readable.)

Categories

Resources