Inserting new elements to form causing issue when form is sent (empty data) - javascript

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().

Related

Why isn't a single form element is not returning value in the controller?

In my Form 3 fields including a hidden.and the rest of the values are perfectly returns in controller ,But the value in the hidden field is not getting .
the value in the hidden field is passing from an anchor tag using java script.
The value for the hidden field is passing from here
<a href="#" onclick="func(#c.vid)" data-toggle="modal" data-target="#myModal3" class="modalLink">
Javascript code to pass the value is
function func(vd){
document.getElementsByClassName("hiddenid").value = vd;
}
Form is look like
<form action="/Home/AddToCart" method="post">
<input type="hidden" id="vid" name="vid" class="hiddenid" />
<div class="styled-input agile-styled-input-top">
<input type="text" placeholder="Name" name="name" id="name"required>
</div>
<div class="styled-input">
<input type="text" placeholder="Star Name" onclick="showsss()" name="star" id="star" required>
</div>
<input type="submit" value="Add To Cart">
</form>
Controller
[HttpPost]
public ActionResult AddToCart(cart data)
{
userService.AddToCart(data);
ViewBag.p = userService;
return RedirectToAction("Temple");
}
The value is passing to the hidden field perfectly.i checked using an alert box.am attaching a screen shot of what am getting in the controller.
getElementsByClassName return an array.
function func(vd){
document.getElementsByClassName("hiddenid")[0].value = vd;
}
getElementsByClassName returns an array. Access single element using array index.
document.getElementsByClassName("hiddenid")[0].value = vd;
Instead of className you can use id as it is present on your hidden field i:e vid.
document.getElementsById("vid").value = vd;
or you can use document.querySelector which will retrieve first match element.
document.querySelector('.hiddenid').value = vd;
or
document.querySelector('#vid').value = vd;
Since you are using byclass its return an array. try this
document.getElementsByClassName("hiddenid")[0].value = vd;
But if you have a multiple products then do you have a add to cart button better to used id like vid-unique_number

Scraping data from input value

there is website which has:
<html>
<body>
<form action="/action_page.php">
First name: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="John"></strong></div>
Last name: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="Miller"></strong></div>
Email: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="j.miller#gmail.com"></strong></div>
<input type="submit" value="Send">
</form>
</body>
</html>
Is it possible to scrape data from input value (John, Miller, j.miller#gmail.com) and show it in my page (maybe putting that site into iframe and scrape from it?) or maybe using something like:
// Get HTML from page
$.get( 'http://example.com/', function( html ) {
// Loop through elements you want to scrape content from
$(html).find("ul").find("li").each( function(){
var text = $(this).text();
// Do something with content
} )
} );
I don't know. I am not good with javascript. And there is bonus: input values on every refresh are different. Can I extract somehow data from 100 refresh or something? Thank you for any help!
i will assume that you need to get the data from the input element and then use it somewhere else in your site
you could easily do so using the jquery .val() function
here is some sample code
<form id="my-form">
name: <input type="text" id='test-input'/>
<input type="submit" />
</form>
<script>
var input;
$('#my-form').on('submit', function() {
input = $('#test-input').val();
});
</script>
you could then use the variable anyway you want, whether it is to cache data or for improving user experience
Get the value and var _value = $('#elementId').val(); and use it anywhere on the page $('#elementID').val(_value); or $('selector').text(_value);

How To use Query string in java script?

I have Created calculator project. I have only two pages. Now my question how to pass input field value to another page? trying too many ways its Not Working.
What to do to pass input fields values from one page to another page?
My input fields code Looks Like
<p class="pull-right">DPA Minimum Buyer Contribution<br /></p>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6" style="padding-right:1%">
<input type="text" id="txtLocationContactName5" class="txt"/>
</div>
<div class="col-md-3" style="padding-left:0%">
Another page name default_results.php I have created input fields
<div class="col-md-5 padding-rht">
Minimum Buyer Contribution
</div>
<div class="col-md-2 padding-Zero">
<input type="text" id="txtCustomerName3" class="txt" />
</div>
I have tired in jQuery script
<script>
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "default_results.php?id=" + encodeURIComponent($("#txtLocationContactName5").val()) + "&technology=" + encodeURIComponent($("#txtCustomerName3").val());
window.location.href = url;
});
});
</script
but Not working so how to pass value one page to other page ?
You're making life hard for yourself! A simple form is needed to help you pass data to another page :). See here for info on html Forms - http://www.w3schools.com/html/html_forms.asp
Here is a simple example for you:
<form action="page_2_link" method="POST">
<input type="text" name="field1" value="easy">
<input type="submit" name="button1" value="Submit">
</form>
Then on the second page you can do this to retrieve the form data:
<?php
$blah = $_POST['field1']; // this now has the posted fields value
?>
I have given the second page answer in PHP as you have used this as a tag for this question, so I hope you are using this or my answer won't work.

posting javascript populated form to another php page

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.

Angularjs- keeps data of nonexistent dom element (ngIf=false)

My form has different fields for each type:
<form>
<select ng-model="message.type">
<option>SMS</option>
<option>Email</option>
</select>
<div ng-if="message.type=='sms'">
<textarea ng-model="message.body"></textarea>
</div>
<div ng-if="message.type=='email'">
<input type="text" ng-model="message.subject" />
<textarea ng-model="message.body" class="ckeditor"></textarea>
</div>
</form>
It works great BUT when the user selects email first, writes something in the subject field, then changes back to sms type, then when I send the message object in $http.post, it sends the object with subject child, even though the dom element was deleted.
How do I fix it? I want to send only the data that is linked to existing dom elements.
Thanks
I can imagine several solutions:
Delete the inappropriate attribute
You can do this when the selected option change:
$scope.deleteInappropriateAttribute = function () {
if ($scope.message.type !== 'email') {
delete $scope.message.subject;
}
};
<select ng-model="message.type" ng-change="deleteInappropriateAttribute()">
<option>SMS</option>
<option>Email</option>
</select>
It's even better to make this action just before you post the form, in order to not force the user to rewrite the message.subject if he's switching frequently between the different options.
Associate a different variable to each part of the form
<form>
<select ng-model="message.type">
<option>SMS</option>
<option>Email</option>
</select>
<div ng-if="message.type=='sms'">
<textarea ng-model="message.global.body"></textarea>
</div>
<div ng-if="message.type=='email'">
<input type="text" ng-model="message.email.subject" />
<textarea ng-model="message.global.body" class="ckeditor"></textarea>
</div>
</form>
And then, only post the appropriate variable:
$http.post(
'myUrl.php',
angular.extend(
{},
$scope.message.global,
$scope.message[$scope.message.type]
)
);

Categories