Move data from on input field to another and submit form - javascript

I am trying to get one input field that is higher up the page, move it's content to a form field at the bottom of the page and submit the form.
Please see what I have done here (doesn't work):
$('#move_down').click(function() {
$('#input_1').val($('#input_2').val())
});
<input type="text" id="input_1" value="">
<br>
<button id="move_down">Click Here</button>
<br>
<input type="text" id="input_2" value="">
<script src="//code.jquery.com/jquery-3.2.0.js"></script>
Moving the data is just the first part, I am also trying to get it to take the user down to the main form and submit it - is this possible with jQuery?
Updated the question to fix my silly error of omitting the ID selectors. Just need to figure out how to submit the form now.

You are right; just correct your query selector:
$('#move_down').click(function() {
$('#input_2').val($('#input_1').val())
});
http://jsfiddle.net/82x28ryr/4/

Missing the # prefix for id selector
Works fine doing
$('#move_down').click(function() {
$('#input_2').val($('#input_1').val())
});
<input type="text" id="input_1" value="">
<br>
<button id="move_down">Click Here</button>
<br>
<input type="text" id="input_2" value="">
<script src="//code.jquery.com/jquery-3.2.0.js"></script>
As for "moving down" you have only provided html in demo for 2 inputs. You need to update question with all relevant html in order to implement additional features

Related

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>

jQuery Trigger Reset Only Resetting Some Forms

I have many forms on my page that are DYNAMICALLY added and I have a button that I want to trigger a reset to all the forms on the page except one.
An example of a dynamically added form is:
<form>
<label for="code">Question code:</label>
<input type="text" id="code" name="code" maxlength="25" class="used"/>
<div class="clear"></div>
<label for="title">Question:</label>
<input type="text" name="titl" name="title" maxlength="255" class="used"/>
<div class="clear"></div>
<label for="hint">Hint:</label>
<input type="text"id="hint" name="hint" class="used"/>
<div class="clear"></div>
<input type="hidden" name="type" value="tapper" class="used">
<input type="hidden" name="optionsType" value="none" class="used">
<input type="reset" value="Cancel" class="delete-button">
<input type="button" value="Add" class="action-button" onclick="pushQuestion(this);">
</form>
Also, after each form is dynamically added, I call:
$('form').on('submit', function (e) {e.preventDefault()});
Now, when I want to reset the forms, I call the following:
$('form').trigger('reset');
When entering this into the console, I get an array back with all the DOM forms. Some forms get reset, but others are unaffected. There are no errors being reported. Does anyone have any thoughts as to why some get reset while others do not?
EDIT Thanks for the help, but the issue has been resolved. See the problem in the comments below
After a few hours of tinkering, it was discovered that the issue was the result of the way the forms were cloned.
I was doing a deep clone of the existing forms which was yielding an odd state of the form which means that when .trigger('reset') was "triggered", it would reset the form to the default state of the clone which may or may not have included some original data yielding a reset that did not appear to be doing anything.
A workaround was to first fire a loop over all the inputs with .attr(value,'') to clear the attribute value after cloning. Then the .trigger('reset') functioned as expected.
I've noticed some inconsistencies with form handling among the various browsers. One gotcha is that the less standards-compliant browsers require an input or button with type=submit for some things to function correctly. I know this is that case at least with submitting a form by pressing the enter key in any text field.
Maybe try adding an <input type='submit'/>?

HTML Submit buttons on forms reload but not lose data

Lets say I have this: http://jsfiddle.net/oh0omatq/2/
<form>
<input placeholder="my value">Country
<button name="subject" type="submit" value="england">England</button>
<button name="subject" type="submit" value="wales">Wales</button>
<br />Your country is: Wales
<input type="submit">
</form>
Can I use this submit buttons for england and wales to set a value within the form, and reload the form, but also not loose the information already entered in the form, such as in the input box.
This above is just a preview, but I want to be able to reload and filter the input elements in the form depending on the button the user clicked, but also not loose any previously entered data in the fields.
I would recommend using javascript for this. I've edited your fiddle to use an onclick function.
<form>
<input placeholder="my value">
Country
<button name="subject" value="england" type="button" onclick="document.getElementById('value').innerHTML = this.value">England</button>
<button name="subject" value="wales" type="button" onclick="document.getElementById('value').innerHTML = this.value">Wales</button><br />
Your country is: <span id="value">Wales</span>
<input type="submit">
</form>
Changing the buttons to a type="button" so they don't submit the form allows the javascript to edit the value. Ofcourse you can make an input out of the span, allowing the chosen value to be sent with the form. Ofcourse, a select box would work as well then.
Would that do what you want?
You can see the edited fiddle here.
Keep in mind, this is a quick sketch. It is not recommended to use javascript inline.

Create new form fields with jQuery

I have a form which starts out with 2 text inputs. The standard scenario is the user enters a number in one field and his/her name in the other and then the page will be updated (not reloaded). But in some cases the user may want to enter several numbers which are connected to the same name and the way this will be implemented is by the user clicking an "add another" link next to the text box.
When the user clicks the "add another" link, the value from the textbox needs to be inserted into a new (dynamically created) text field and the text field where the user entered the number should be reset to default value. The user can enter 10 numbers this way before an alert is presented informing him/her about more efficient ways to do this operation.
I'm clueless as to how this is done (can it be done) jQuery and it would be great if someone can help out.
Here is the html I'm working with:
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6">
<span class="addRegNr">add another</div>
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
</div>
http://jsfiddle.net/RgKV9/
Cheers!
EDIT UPDATE
I've taken a liking to Aske G's example and have made some changes to it. Here is the new code I'm working with, jsfiddle.net/SDpfy Although I managed to do some minor changes to AskeG's code I cant figure out how to add unique ID's and individual delete links for each generated field that ends up in the basket. Also, how can I set the generated fields to readonly and animate them when they show up in the basket?
just add a click watcher to the span. Check this fiddle: http://jsfiddle.net/ranjith19/RgKV9/4/
I have done some basic changes. If you need custom names id's you should use a templating library and then append it
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6"
maxlength="6">
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
<p></p>
</div>
<span class="addRegNr" style="display:inline">add another</span>
<script type="text/javascript">
$(document).ready(function () {
str_to_append = '<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6">\
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">\
<input type="button" value="GET INFO" class="last" id="getBaseInf"><p></p>'
$(".addRegNr").click(function () {
$("#searchFields").append(str_to_append)
})
})
</script>
​
You can do it, using jquery append method.
here I leave a link with some examples:
http://api.jquery.com/append/
I guess, you might just be looking for something like this.
I would do something like this:
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr </label><input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6"/><br/>
</div>
<span class="addRegNr">add another</span><br/>
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
and then some js that looked like this:
var $input = $("#searchFields").children();
$(".addRegNr").on("click", function(){
var $newField = $input.clone();
// change what you need to do with the field here.
$(this).siblings("#searchFields").append($newField);
});
It's also here: http://jsfiddle.net/tatLw/
Basing solution on this blog post jQuery – Dynamically Adding Form Elements by Charlie Griefer, you could try the following:
Markup:
<div id="searchFields" class="control-group inlineForm">
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<label for="regNr">Regnr</label>: <input type="text" name="regNr" placeholder="Regnr." size="6" maxlength="6" />
<label for="poNr">PO.nr</label>: <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
</div>
<div>
<input type="button" id="btnAdd" value="add another Reg field" />
<input type="button" id="btnDel" value="remove fields" />
</div>
<input type="button" value="GET INFO" class="last" id="getBaseInf">
</form>
</div>​
Javascript:
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'regNr' + newNum).attr('regNr', 'regNr' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').removeAttr('disabled');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove(); // remove the last element
$('#btnAdd').attr('disabled',''); // enable the "add" button
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');​
DEMO: http://jsfiddle.net/chridam/qW9ra/
To add any HTML with jQuery you will eventually end up calling .append(), or one of its variations like .before, .appendTo, etc.
These can be given raw HTML strings, but unless you have an HTML template ready and plain, don't use string concatenation to build your HTM. This is fragile and insecure. Instead, create the elements with jQuery() directly, like so:
jQuery('<input type="text"/>').attr({
value: '',
placeholder: '...',
id: '..'
})
.appendTo( .. )
In addition, don't forget to create labels for these new elements as well (if appropiate).
Another few best practices relevant to this scenario:
If you're going to be dynamically making new form elements appear (as opposed to adding more additional fields for an existing field), it is best to not create these with JavaScript. Instead make sure they are present in the page output from the beginning, then hide them from $(document).ready with .hide(). That way it will be a lot easier (as all you need is a reference to the hidden element, and call .show() when you have to). And that way it doesn't rely on javascript flow being present, enabled and functioning as expected because this way if anything happened along the way (exception thrown, cdn issues, whatever) the form will fallback to a fully-present version that just works.
If you're going to have a lot of these "+" or "add" button scenarios, I'd make a .clone() of the original field, strip it (clear value, remove id-attribute), and store it in a local variable. Then from the click handler, clone that, and put it into the document where you need it. You may also want to have a server-side fallback by making the add button a submit button with a certain name/value pair that the server detects as a non-final input in which case it will return the same page with the values pre-filled but with more fields.

jQuery modal window removes elements from my form

jQuery, when i use it to create a modal window which contains form elemets,
it takes out those elements when i submit the form.
example of the form:
<form enctype="multipart/form-data" action="/system/article/add/" class="from" method="post">
<label for="article_title" class="required">Title:</label>
<input class="formfield" id="article_title" name="article_title" value="" type="text">
<label for="url" class="required">Url:</label>
<input class="formfield" id="url" name="url" value="" type="text">
<div id="add_photo" style="width: auto;" class="ui-dialog-content ui-widget-content" title="Add Photo">
<label for="photo_title" class="optional">Photo title:</label>
<input class="formfield" id="photo_title" name="photo_title" value="" type="text">
<label for="photot" class="optional">Photo thumb:</label>
<input type="file" name="photot" id="photot" class="formfield">
<label for="photo_checkbox" class="optional">Include lighbox?</label>
<input name="photo_checkbox" value="0" type="hidden">
<input class="checkbox" id="photo_checkbox" name="photo_checkbox" value="1" type="checkbox">
<label for="photo_big" class="optional">Photo:</label>
<input type="file" name="photo_big" id="photo_big" class="formfield">
</div>
</form>
exaple of JS:
<script>
$(document).ready(function(){
$("#add_photo").dialog({
autoOpen: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
});
});
So what i nocited during the inspetion via firebug, is that jquery actually removes my form elements within #add_photo and puts them outside the form in DOM, so even tough in html the modal dialog is within my form, in DOM it isn't ....
An this is the reason why i'm having the issue!
Have anyone encountered simmilar problem?
Any solution?! Thank you very much!
I just had the same problem. I solved it by adding another
<div id="beforesubmit" style="display:none"></div>
at the end (but inside) of the form and then you have to add this to jQuery:
$("form").submit(function() {
$("#add_photo").prependTo("#beforesubmit");
});
This will make sure that before the form is submit your dialog div will be put back in between the form tags. Thanks to arnorhs I came to this solution.
Cheers!
I'm not sure what dialog box plugin you're using, but I would suspect that the dialog box plugin is pulling the DIV out of the form and placing it into the body of the page, so It can bring the box in front of the page, outside of the form element.
So to rephrase, in order for the dialog box plugin to make your dialog appear in front of all the content on your page, it needs to remove it from whatever element it is sitting in, no matter if it's a form or anything else.
The form needs to be inside the div. That's how it is in all the Dialog examples. Not sure how you're going to do that with the title and url inputs not being on the dialog. Couldn't you put them on it too?
This wouldn't have the problem:
<div id="add_photo" style="width: auto;" class="ui-dialog-content ui-widget-content" title="Add Photo">
<form enctype="multipart/form-data" action="/system/article/add/" class="from" method="post">
<label for="article_title" class="required">Title:</label>
<input class="formfield" id="article_title" name="article_title" value="" type="text">
<label for="url" class="required">Url:</label>
<input class="formfield" id="url" name="url" value="" type="text">
<label for="photo_title" class="optional">Photo title:</label>
<input class="formfield" id="photo_title" name="photo_title" value="" type="text">
<label for="photot" class="optional">Photo thumb:</label>
<input type="file" name="photot" id="photot" class="formfield">
<label for="photo_checkbox" class="optional">Include lighbox?</label>
<input name="photo_checkbox" value="0" type="hidden">
<input class="checkbox" id="photo_checkbox" name="photo_checkbox" value="1" type="checkbox">
<label for="photo_big" class="optional">Photo:</label>
<input type="file" name="photo_big" id="photo_big" class="formfield">
</form>
</div>
This article describes how to solve your problem:
You’ll see that the content we had mid-way through our page has been marked up with additional classes and, most importantly, placed at the bottom of the page immediately before the closing tag. Why is this important? Because it also means that any ASP.Net controls you place within this dialog will also appear at the bottom of the page, outside of the page’s tag. This means you won’t be able to get a handle to them on postback.
What’s the solution? Well, there are two options:
Move the elements back to the form, and manually submit when the button is clicked
Clone the elements when you create the dialog, then clone the values back, trigger click on the original button (or, if you only have one or two values to post back, simply assign the values to an ASP.Net hidden field control).
From http://blog.coreycoogan.com/2010/12/01/jquerys-dialog-and-form-problems/
Tie it to the form by doing $("mydialog").parent().appendTo($("form:first")).
Note that you have to this call after you already called $("mydialog").dialog()
As seen in the answer for this question, jQuery dialog has a field appendTo, that can be used to configure where to put your dialog (div-wise) on initialization.
This seems to be the least ninja-workaround version to tackle the problem.

Categories

Resources