I'm trying to take some js that pulls data from another web application and populates a form by clicking "Populate Contact Info" and then click a "Submit" button to push the fields to a new php that then processes them. So basically how do I pass populated form field to a second form on the same page that I can then submit? Or is there a better way?
<form action="#" name="data" id="data">
<input type='button' value='Populate Contact Info' onclick='popAllContactFields()' />
Contact Info:
First Name: <input type='text' readonly="readonly" id='cfname' name='cfname' />
Last Name:<input type='text' readonly="readonly" id='clname' name='clname' />
Email: <input type='text' readonly="readonly" id='cemail' name='cemail' />
</form>
<script type="text/javascript">
/* popAllContactFields()
Populates all the contact fields from the current contact.
*/
function popAllContactFields()
{
var c = window.external.Contact;
{
// populate the contact info fields
popContact();
}
}
/* popContact()
Populates the contact info fields from the current contact.
*/
function popContact()
{
var c = window.external.Contact;
// set the contact fields
data.cfname.value = c.FirstName;
data.clname.value = c.LastName;
data.cemail.value = c.EmailAddr;
}
</script>
<form action="ordertest.php" method="post">
<input name="cfname" id="cfname" type="hidden" >
<input name="clname" id="clname" type="hidden" >
<input name="cemail" id="cemail" type="hidden" >
<input type="submit" value="Submit">
</form>
If you can manage to receive the data with an AJAX call as a JSON then it's vary easy. With using jQuery ($) and Lodash (_ but you can try Underscore as well):
$.get('an-url-that-returns-the-json', function(parsedData) {
_.forEach(_.keys(parsedData), function(key) {
console.log('key:', key);
$('#'+key).val(parsedData[key]);
});
});
If it's tough at first sight read some about jQuery selectors, AJAX ($.get()) and $(...).val().
You can also make a list about the keys that you want to copy, e.g. var keysToCopy = ['cfname', 'clname', 'cemail'] and then _.forEach(keysToCopy, function(key) {...}), this gives you more control with the copied data.
If you cannot use AJAX but can control the output of the source PHP, then I'd rather create the data as a raw JS object. If you cannot control the generated stuff then you must use something like you wrote, that also can be helped by some jQuery based magic, e.g.
_.forEach(keysToCopy, function(key) {
var prop = $('#source-form #'+key).val();
$('#target-form #'+key).val(prop)
});
Based on these you can think how you can solve if the source and target IDs are not the same.
Related
I am updating a product, I am able to have the product info prefill the update form and update the product info using jQuery but I want to use JavaScript. How do I convert this jQuery code to JavaScript?
I am following a tutorial online and the person is using jQuery which is cool but I want to see how to do the same method using Javascript.
Javascript Code:
$(document).on('pagebeforeshow', '#updatedialog', function() {
$('#newName').val(currentProduct.name);
$('#newQuantity').val(currentProduct.quantity);
});
function updateProduct() {
var newName = $('#newName').val();
var newQuantity = $('#newQuantity').val();
productHandler.updateProduct(currentProduct.id, newName, newQuantity);
}
HTML update form
<form>
<div class="ui-field-contain">
<label for="newName"
class="ui-hidden- accessible">Name</label>
<input type="text"
id="newName"
data-clear-btn="true"
placeholder="New Name"/>
<br/>
<label for="newQuantity"
class="ui-hidden-accessible">Quantity</label>
<input type="number"
name="number"
pattern="[0-9}"
id="newQuantity"
value=""
data-clear-btn="true"
placeholder="New Quantity"/>
<br/>
<button class="ui-btn ui-icon-plus ui-btn-icon-left"
id="btnupdate"
onclick="updateProduct()">
Update
</button>
</div>
</form>
The update form should populate with the information from the product that was already entered and then it should update the changes made to the fields and save it as a new object. I can do it in jQuery but I want help with doing it in Javascript.
Seems all you're currently doing with jquery is getting the value of input elements by their ID. You can do this with javascript by selecting the form element by ID and getting the value property.
val value = document.getElementById("elemID").value;
Your code should look like this
function updateProduct(){
var newName= document.getElementById("newName").value;
var newQuantity = document.getElementById("newQuantity").value;
productHandler.updateProduct(currentProduct.id, newName, newQuantity);
}
you can get values of of the element by id using document try the following
function updateProduct(){
var newName=document.getElementById("newName").value;
var newQuantity=document.getElementById("newQuantity ").value;
productHandler.updateProduct(currentProduct.id, newName, newQuantity);
}
I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]
I have to forms on my website, when second form is filled up (after click save button) im copying this form and inserting it into first form. Unfortunately when I submit this form, data in inserted elements are empty.
My code:
var objToCopy = $('.partnersForm').find('.modal-body').clone();
objToCopy.find('[name]').each(function(){
var objThs = $(this);
objThs.prop('name', '_' + objThs.prop('name'));
objThs.prop('id', '_' + objThs.prop('id'));
});
$('.partnersData').html(objToCopy);
And data looks like this:
[contact_county] => Hampshire
[country] => GB
[contact_title] => 4
[contact_name] => gfhf
[contact_surname] => fghfgh
[_partner_mobile] =>
[_partner_nationality] =>
[_partner_dob] =>
[_partner_email] =>
Where empty data come from inserted elements.
When I remove second form manually after insertion, then everything seems to work.
But I don't understant why I cant send this data even when I change names of inputs.
Simplified HTML structure:
<form id="form1">
<input type="text" name="contact_county" id="contact_county">
<input name="country" id="country">
<input name="contact_title" id="contact_title">
<input name="contact_name" id="contact_name">
<input name="contact_surname" id="contact_surname">
<div class="partnersData" id="partnersData">
<!-- inserted elements goes here -->
</div>
<button type="submit">Submit</button>
</form>
<form class="partnersForm" id="form2">
<div class="modal-body">
<input type="text" name="partner_mobile" id="partner_mobile">
<input type="text" name="partner_nationality" id="partner_nationality">
<input type="text" name="partner_dob" id="partner_dob">
<input type="text" name="partner_email" id="partner_email">
</div>
<div class="modal-foter">
Save
</div>
</form>
Instead of $('.partnersForm').find('.modal-body').clone();, you should use $('.partnersForm').find('.modal-body').clone(true);. When you are making the clone, only the form and associated controls are getting cloned, but the values are getting emptied. Passing "true" as the parameter to clone, the values inside the control will also get cloned.
For details, Check the JQuery Documentation to clone().
I have created a form with dynamic field. but i m getting confused that how should i post data into database. because there would be different field according to different users.
here is the basic code with one dynamic field
function add2(type) {
var element = document.createElement("textArea");
var label=prompt("Enter the name for lable","label");
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+label;
element.setAttribute("type", type);
element.setAttribute("name", type);
var col=prompt('Enter the no of columns');
element.setAttribute("cols",col);
var row=prompt('Enter the no of rows');
element.setAttribute("rows",row);
var rohit = document.getElementById("raj");
rohit.appendChild(element);
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+"<br/>";
}
here is the calling of this function.
<input type="button" value="Text Area" onclick="add2('textarea')"><br/>
</div>
<div id="content" style="height:200px;width:400px;float:left;">
<form action="#" method="post">
<span id="raj"> </span>
<input type="submit" value="submit"></div>
help me guys what should i do to store the dynamic elements into database
and what fields should i put into database
Store the field values separated in one hiddenfield, and get them from the serves side.
<input id="values" type="hidden" value="value1,value2,value3">
on submit:
var Valuearray = values.value.Split(',');
I'm trying to create a URL builder form with JavaScript or jQuery.
Basically, it will take the value of the two form fields, add them to a preset URL and show it on a third field on submit.
The resulting URL might be http://example.com/index.php?variable1=12&variable2=56
Now, this isn't the "action" of the form and the application can't read a URL (to grab the variables), so it has to be done on the page.
The resulting URL will be shown in the field named "url".
Here's a sample of the form:
<form id="form1" name="form1" method="post" action="">
<p>
<label>Variable 1
<input type="text" name="variable1" id="variable1" />
</label>
</p>
<p>
<label>Variable 2
<input type="text" name="variable2" id="variable2" />
</label>
</p>
<p>
<label>URL
<input type="text" name="url" id="url" />
</label>
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
jQuery has serialize which builds the query string values.
So if you want to do the entire form:
alert($("#form1").serialize());
If you want to do only a few fields, then just make the selector select those fields.
alert($("#variable1, #variable2").serialize());
Use something like...
var inputs = $('#form1').find('input[type=text]').not('#url');
var str = "http://www.base.url/path/file.ext?"
inputs.each(function (i, item) {
str += encodeURIComponent(item.name) + "=" + encodeURIComponent(item.value) + "&";
});
$('#url').val(str);
This will select all <input>s on in form1 with type='text', and concatenate them into a query string. See encodeURIComponent().
Orrrr.....you could just use .serialize(). Thank you, prodigitalson.
Something like the following should work:
var partFields = '#variable1,#variable2';
$(partFields).change(function(){
var url = 'static/URL/to/file.php?';
$('#url').val(url + $(partFields).serialize());
});
However, unless you want people to be able to override the URL, you might want to use a hidden field and a regular element for display and submission of the URL value in which case you'd have something like the following:
var partFields = '#variable1,#variable2';
$(partFields).change(function(){
var url = 'static/URL/to/file.php?';
var urlValue = url + $(partFields).serialize();
$('#url-display').text(urlValue); // Set the displaying element
$('#url').val(urlValue); // Set the hidden input value
});