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.)
Related
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>
1) I have 3 input radio buttons with unique values.
For e.g.
<input type="radio" id="id1" value="This is first value" />
<input type="radio" id="id2" value="This is second value" />
<input type="radio" id="id3" value="This is third value" />
2) Next, I have 2 hidden form like this:
<form action="//mysite.com/process1.php"><input type="hidden" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" id="uniqueid" value=""></form>
3) Based upon whichever radio button the user clicks, I need to copy its value to the value of both the above forms hidden field.
For e.g. If user clicks on radio with id1, then it's value "This is first value" should be copied to both the forms hidden field.
CONSTRAINTS:
1) Have to use javascript or jquery, no server side processing available.
2) Note: both the final forms have one input field, but with same id. This is a constraint.
3) Why? Because based on some other actions on the page, the user gets to see one of the 2 forms. The only difference between them is their action is unique. All fields are same.
WHAT I HAVE SO FAR:
Using this, I am able to copy the value from the radio button to a hidden field's value, but it only copies to a field with a UNIQUE ID.
var $unique = $("#unique");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
Can someone guide as to how can the value be copied to multiple input fields, but with same id's?(Yes, the id's of the initial radio buttons can be unique.)
Having two HTML elements with same ID is an error.
You cannot treat this as a constraint, this is NOT a valid HTML code and it will cause inconsistent behavior in different browsers.
Use classes instead:
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" value=""></form>
And javascript:
var $unique = $(".uniqueid");
However, I couldn't find any #radio1 or #email in your code, are you sure you have the right selectors?
My recommendation for the JS will be: (Working jsFiddle)
var $unique = $(".uniqueid");
$('input[type="radio"]').click(function(){
$unique.val(this.value);
});
Notes for jsFiddle:
I've used click event instead of keyup (don't really understand why you used keyup here..).
I've given all radio buttons the same name so they will cancel each other out when selected.
I've turned the hidden fields to text so you could see the result.
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
var $unique = $("input[type=hidden].uniqueid");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
As said by others, id must be unique. Try using a data-attribute:
<form action="//mysite.com/process1.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
<form action="//mysite.php/process2.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
Now you can use that attribute as selector to do something like:
$('[data-shouldupdate]').val(this.value);
I agree with all other who posted that id have to be unique to have correct HTML document. So if it's possible I strictly recommend you to fix the HTML document to remove all duplicates.
I write my answer only for the case that you can't remove id duplicates because of some reason and you still have the same requirements. In the case you should change the line
var $unique = $("#uniqueid");
to
var $unique = $("*[id=uniqueid]");
The selector *[id=uniqueid] (or just [id=uniqueid]) works slowly as #uniqueid, but it allows you to get all elements with the specified id attribute value. So it works even in case of id duplicates on the HTML page.
The most simple solution is to give a same name to both inputs. Check this link jsfiddle to see a working example. The code used is the one given is below:
HTML:
<input type="radio" name="copiedValue" id="id1" value="This is first value" />
<input type="radio" name="copiedValue" id="id2" value="This is second value" />
<input type="radio" name="copiedValue" id="id3" value="This is third value" />
<form action="//mysite.com/process1.php"><input name="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input name="uniqueid" id="uniqueid" value=""></form>
jQuery/javascript:
$("input:radio[name=copiedValue]").click(function() {
$("input[name=uniqueid]").val($(this).val());
});
The radio-buttons should have the same name. I removed the type="hidden" so u can see it working correctly.
Hope it useful!
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/
I have a form, with a couple of <input> tags inside. I have a submit button (actually an <input> of type BUTTON, not SUBMIT) that is outside the form. I have the form set up similar to this —
<form name="testform" id="testform" action="test.jsp" onsubmit="return modify_value();" method="POST">
<input name="test1" id="test1" type="TEXT" value="A"/>
<input name="test2" id="test2" type="TEXT" value="B"/>
<input name="test3" id="test3" type="HIDDEN"/>
</form>
The submit button, which is outside the form, is defined this way —
<input type="BUTTON" id="_submit" onclick="document.forms[0].submit();"/>
And the modify_value() JavaScript method looks like this —
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking';
return true;
}
When the submit button is clicked, I am trying to modify the value of the test3 element before the form gets submitted. For some reason, I can never read the new value in my servlet.
Alternate Method - (Doesn't Work Either) WORKS!
I have tried submitting the form in a slightly different way as well - by setting the button's onclick event to point to the modify_value() method and in the last line of that method, calling form.submit() instead of returning a value (EDIT: And of course, removing the onsubmit attribute in the form). This doesn't work either.
What am I doing wrong here?
When you call .submit() in JavaScript. The form's onsubmit event handler is not called.
I would put the button inside the form, and make it a submit button. Otherwise it's just a dead button (semantically, and when JavaScript is not available).
In HTML validation you're not allowed an INPUT element outside of a FORM element anyway. Weird, it seems you are! Ha ha I never knew that...
If you need to work within the restrictions specified within your answer, then remove the onsubmit attribute:
<form name="testform" id="testform" action="test.jsp" method="POST">
<input name="test1" id="test1" type="TEXT" value="A"/>
<input name="test2" id="test2" type="TEXT" value="B"/>
<input name="test3" id="test3" type="HIDDEN"/>
</form>
...and change the onclick attribute to modify the value...
<input type="BUTTON" id="_submit" onclick="modify_value()"/>
...and add the form submission to the end of the function, no need to return any value...
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking';
document.forms[0].submit();
}
you can try this
<input type="BUTTON" id="_submit" onclick="modify_value()"/>
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking';
document.getElementById("testform").Submit();
}
You can actually now do this entirely in HTML, see the form attribute for submit buttons all <input> elements — new with HTML5.
The form element that the input element is associated with (its form owner). The
value of the attribute must be an id of a <form> element in the same
document. If this attribute is not specified, this <input> element
must be a descendant of a <form> element. This attribute enables you
to place <input> elements anywhere within a document, not just as
descendants of their form elements.
Here's an example of how to use it:
<input type="submit" form="download" value="Download Selection" />
This button can then be placed anywhere on your page.
Obviously this only works on a limited number of browsers at the moment, but I figured it's worth a mention.
try this...
HTML
<form name="testform" id="testform" action="test.jsp" onsubmit="return false;" method="POST"> // onsubmit to return false
.....
<input type="submit" id="_submit" onclick="modify_value()"/> //call javascript function
</form>
JAVACRIPT
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'new_test_value_set_on_clicking'; // do the things here
document.getElementById('testform').Submit(); // submit the form
}
Hi i have a requirement like follows i have a file element in one form this form contains many
other fields also so i cannot submit it but after the file has chosen i need to upload that
so i created the second form with iframe. I am not able to copy the file element from one form to another especially in ie i tried with cloneNode and appendChild both are not working any suggestions. i am really stuck.
<form name ="form1">
<input type="file"/>
</form>
<form name="form2">
<form>
Looks like cloneNode has allowed to clone file inputs. Possible code may be as follows:
<form name="form1">
<input id="file1" type="file" onchange="copy_file_input()" />
</form>
<form name="form2" enctype="multipart/form-data">
<input type="hidden" name="test" value="form2sent" />
</form>
function copy_file_input() {
var target_form = document.forms.form2;
if (target_form.file2 != undefined) {
target_form.removeChild(target_form.file2);
}
var elem = document.getElementById('file1');
var copy = elem.cloneNode(true);
copy.name = 'file2';
target_form.appendChild(copy);
}
Also this link may be useful.