I have form with two fields and until those fields are filled with some text my submit button will be disabled but now if i add third field dynamically angular JS will not support validation for the third field which is added dynamically.
link https://jsfiddle.net/vikrantkki/zzhgaguz/57/
<button ng-click="adddynamicfield()">add dynamic field<button>
<form name="dynamicform" novalidate="true">
<input type ="text" dynamic-name name="name" ng-model="dynamicform1.name" required>
<input type ="text" dynamic-name name="age" class="age" ng-model="dynamicform1.age" required >
<button type="submit" ng-disabled="dynamicform.$invalid">submit</button>
</form>
The problem is you are not compiling the newly added html. You can research on $compile and it should solve the issue.
But what I recommend for your case is to use an array to represent the dynamic fields, so you can get the model values more easily.
fiddle
$scope.dynamicFields = [];
$scope.adddynamicfield = function() {
var index = $scope.dynamicFields.length;
$scope.dynamicFields.push({
name: 'field' + index,
model: '',
className: 'field',
});
}
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);
}
So I have a page called Index.cshtml
I have this input in a form with the id "cvr":
#using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{
<input type="hidden" value=#Html.ViewData.Model.StudentId name="studentId" />
<input type="hidden" value=#Html.ViewData.Model.CompanyId name="companyId" />
<input type="hidden" value=#Html.ViewData.Model.ApplicationId name="applicationId"/>
if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
<input type="text" name="companyCVR" placeholder="Indsæt CVR-nr."/>
}
}
and at the bottom of the page I have the submit button with the id above ("cvr") where I am trying to add two more forms to pass on to the controller (repFirstName and repLastName):
#if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{
<input type="text" name="repFirstName" placeholder="Indsæt fornavn" />
<input type="text" name="repLastName" placeholder="Indsæt lastnavn" />
}
<input type="button" value="Submit" onclick="$('#cvr').submit();" class="btn btn-success" />
}
However they will not pass on submit, only the first value (the CPR above). However if I have all three values at the start, they will pass successfully.
How can I have the input in both places and still be able to submit and pass the data to the controller? Do I need two separate forms/ids ?
Only one form is required, remove the second form declaration and associate element with form using form attribute which is defined at the bottom of page.
The form attribute is used to associate an input, select, or textarea element with a form (known as its form owner).
#if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
<input type="text" name="repFirstName" placeholder="Indsæt fornavn" form="cvr"/>
<input type="text" name="repLastName" placeholder="Indsæt lastnavn" form="cvr"/>
<button form="cvr" class="btn btn-success">Submit</button>
}
If your generated HTML results in multiple elements that have the same ID, and then you have some inline javascript like this:
<input type="button" value="Submit" onclick="$('#cvr').submit();" />
Then the above javascript will work only for the first #cvr
That is one example of why you cannot / must not have multiple elements on the page with the same ID.
You must refactor your code to only use one element with any given ID. If need to have multiple elements with same moniker, use a class - so your javascript would become:
<input type="button" value="Submit" onclick="$('.cvr').submit();" />
and your generated HTML would be class="cvr" instead of id="cvr"
Alternately, you could ensure that each of your forms uses a different ID, such as id="cvr1", id="cvr2", id="cvr3" and then your javascript could be:
<input type="button" value="Submit" onclick="$('#cvr1, #cvr2, #cvr3').submit();" />
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.
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 am creating a set of textboxes dynamically while pressing (+) button, by cloning the following HTML template:
<div id= "other_leaders" class="controls form-input">
<input type="text" name="other_leader_fname[]" class="input_bottom other_leader_fname" id="other_leader_fname" placeholder="First Name" value="'.$val[0].'" />
<input type="text" name="other_leader_lname[]" class="input_bottom other_leader_lname" id="other_leader_lname" placeholder="Last Name" value="'.$val[1].'" />
<input type="text" name="other_leader_email[]" class="other_leader_email" id="other_leader_email" placeholder="Email Address" value="'.$val[2].'" />
<input type="text" name="other_leader_org[]" class="other_leader_org" id="other_leader_org" placeholder="Organisation/College" value="'.$val[3].'" />
<span class="remove btn"><i class="icon-minus"></i></span>
</div>
I am able to do single textbox validation by following code:
$("input[name*='other_leader_fname']").each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
});
Now my question is how to do empty validation for all four textboxes, if any one textbox field is filled by the user in that particular textbox group.
for example: if i enter values in the <div> with id other_leader_fname, then it should perform empty validation for other three textboxes of this particular group.
how can i do it?
Try this , You can apply your validation rules to all the text box in the div by using following code:
$("#other_leaders :input[type='text']").each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
});
As you have just one element so there is no need to have a loop over it:
var $othLeader = $("input[name*='other_leader_fname']");
if($othLeader.val()=="" || !RegExpression.test($othLeader.val())){
$(this).addClass('custom-error');
fnameflag = 0;
}
And if you have form then you can validate this in your form's submit function.
You can iterate over the .controls using the each() and check for filled inputs in each group using filter for performing the validation as follows:
$('.controls').each(function(){
var $inputs = $(this).find('input');
var filled = $inputs.filter(function(){
return this.value != "";
});
if(filled.length){
$inputs.each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
})
}
});
Demo
side note: since the above is a template for dynamically generated content, You should remove the id and use class instead since id should be unique in a document.