Appended input field elements are not working in angularjs - javascript

I am creating form in angularjs. In that, I am creating add more fields functionality by clicking on "Add more" button. I've implemented add more functionality using javascript.
Below is the code for HTML:
<form method="POST" name="form" ng-submit="insert(user)" role="form">
<div class="top_gets" id="innerdivs">
<input ng-model="user.amount" type="text"/>
<input ng-model="user.description" type="text"/>
<input type="submit" onclick="addMore();" value="Add more"/>
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
Below is Javascript Code:
<script>
var counter = 0;
function addMore() {
counter += 1;
var div = document.getElementById('innerdivs');
var innerdiv = '<div id="innerdivs"><!-- Same Form Field Elements---></div>';
$('#innerdivs').append(innerdiv);
}
</script>
My problem is, whenever I add more fields by clicking on "Add more" button and submit the form, then only first loaded input fields posts/sends the data means newly appended field input does not posts the data. Whatever the fields are appended using javascritpt that won't works that is form does not sends/posts the inputs. This works with core PHP but it does not works in angularjs. Is there any way to fix this in angularjs?

You are doing it absolutely wrong. You shall not add dom elements manually. Instead, you shall have array in controller and push new object in it:
<form name="form" ng-submit="save(users)" role="form" ng-controller="addUserCtrl">
<div class="top_gets" ng-repeat="user in users">
<input ng-model="user.amount" type="text" />
<input ng-model="user.description" type="text"/>
<input type="button" ng-click="addMore();" value="Add more" />
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
In controller:
angular.module(<module_name>).controller('addUserCtrl', ['$scope', function (scope) {
scope.users = [{}];
scope.addMore = function () {
scope.users.push({});
};
scope.save = function () {
// send `scope.users` to server with $http or $resource
};
}]);

Related

Form with two buttons

I am trying to create multiple forms which have two buttons, each will submit the form to different script, one via ajax and second one will just submit the form.
<?php foreach($objects as $object) : ?>
<div class="card-body">
<form id="edit-form" action="#" method="POST">
<input name="subject" value="<?=$object['subject']?>" type="text" id="title" class="input-xxlarge">
<textarea id="content" name="content" rows="25"><?=$object['content']?></textarea>
<button type="button" id="send-button" class="btn btn-primary">Send</button>
<input type="submit" id="submit-button" value="Submit"/>
</form>
</div>
<?php endforeach; ?>
First I am trying to get the current form, but I have problem with that. console.log shows something only on the first form, if I click on the buttons from other forms then It will do nothing.
$('#send-button').on('click', function(e) {
e.defaultPrevented;
$form = $(this);
$url = $form.attr('action');
$data = $form.serialize(); console.log($form);
console.log($url);
});
Is it because my button has same ID for every form ?
You shouln't use ID's multiple times on the same page. Try to use a class for that case. Also as stated in the comments use e.preventDefault(); to stop the event.
$(this) will result in the #send-button beeing targeted. To access the form you need to find the closest form element like this:
$form = $(this).closest('form');
html:
<form method="POST" action="#">
<input type="text">
<button type="button">send</button>
<input type="submit" value="submit" />
</form>
<form method="POST" action="#">
<input type="text">
<button type="button">send</button>
<input type="submit" value="submit" />
</form>
js:
$("form").each(function() {
var form = this;
$(form).find('button').on('click', function(e) {
e.preventDefault();
console.log(form);
console.log(this);
})
});
this will add events on every form you have on your page, button will submit form via script and submit will just submit it. also here's a fiddle to play with

angular's ng-submit() directive does not submit while pressing enter on one of text fields

I've constructed a simple form using angular.
I want that once the user enter some value and then press enter - the ng-click function (in this case updateMsg({name: name,room: room})) will be run.
However, this code does not work like that.. the function run only after pressing the button (not like I want - enter keyboard value, then enter..)
Code is below...
help please?
Thanks
<body>
<div class="Member">
<h1>Sign In</h1>
<form name="myForm" ng-submit="updateMsg({name: name,room: room})">
Please enter your details:
<br>
Name: <input name="name" ng-model="name" autocomplete="off">
<br>
Room: <input name="room" ng-model="room" autocomplete="off">
<br>
<button type="button" ng-click="updateMsg({name: name,room: room})">
Enter
</button>
</form>
</div>
</body>
You should not use ng-click and ng-submit directives together. Add type="submit" to your button like this:
<button type="submit">Enter</button>
and keep only ng-submit:
<form name="myForm" ng-submit="updateMsg({name: name,room: room})">
Please enter your details:
<br> Name:
<input name="name" ng-model="name" autocomplete="off">
<br> Room:
<input name="room" ng-model="room" autocomplete="off">
<br>
<button type="submit">Enter</button>
</form>
Also there is no point in doing ng-submit="updateMsg({name: name,room: room})" to pass your updated data like that. Since you are using ng-model you are ready to go. You can declare your scope vars initially in the controller and when the form gets submitted you can use them right away. Because of dual-binding your vars will be already updated:
angular
.module('myApp', [])
.controller('MemberController', ['$scope', function($scope) {
$scope.name = '';
$scope.room = '';
$scope.updateMsg = function() {
// use updated $scope.name in here
// use updated $scope.room too
}
}]);
A small plunker to help you some more.
I think the button should have type=submit instead.
<button type="submit">
instead of
<button type="button" ng-click="updateMsg({name: name,room: room})">Enter</button>
Are you calling a event.preventDefault() method so the form doesn't submit by default? Maybe share the code where you're creating the updateMsg({name: name,room: room}).

Putting specific element into variable

how can i get a specific element of a text input into a variable via javascript, in other words take the example below
<form id="123">
<input type="text" id="supply_qty" />
<input type="submit" name="submit" id="123" />
</form>
How do i get the element within the text input into a variable when the submit button is clicked, the problem i have is that i have multiple instances of the code above, with lots of text inputs, so i only want to get the element specific to the submit button clicked. Hopefully you will get what i mean. The reason i need this done via JavaScript and not php etc... is that i later want to use ajax with it, but for the moment i just need the variable.
Thanks
The most easiest way is to give and id to the element and user getElementById() method to grab the element on variable. Just like what you are doing right now
Simple Example:
var button = document.getElementyById("123");
button.onclick = function() {
var text = document.getElementById('supply_qty'); //now you got your element in varaiblle
};
Using jQuery make a slight change to your markup. I am just going to add some classes.
<form>
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
then
$(".submit").click(function() {
var txtbox = $(this).parent("form").children(".textbox")[0];
});
Or, it might be better to bind to the submit handler of the form, on that case, give a common class to the form.
<form class="tinyforms">
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
Then
$('.tinyforms').submit(function() {
var txtbox = $(this).children(".textbox")[0];
});
If you accept using jQuery you can do this:
DOM
<form class="form" action="false">
<input type="text" value="some input" name="textInput" />
<input type="text" value="some text" name="textInput2" />
<input type="submit" class="sumbit" value="Send" />
<div id="results"></div>
</form>​​​​​​​​​​​​​​​​​​​
And JavaScript
$(".form").submit( function(){
var inputs = $(this).serializeArray();
$.each(inputs , function(i, input){
$("#results").append(input.value + "<br />");
});
return false;
} );​
EDIT: Updated code and Fiddle: http://jsfiddle.net/65Xtp/4/

Jquery multiple forms in same page

I have the following dynamically generated HTML
<div id="1">
<form name = "inpForm">
<input name="FirstName" type="text"/>
<input type="submit" value="Submit"/>
</form>
</div>
<div id="2">
<form name = "inpForm">
<input name="FirstName" type="text"/>
<input type="submit" value="Submit"/>
</form>
</div>
The outer divs have different IDs but the form names are the same. I am using Jquery to perform some validation when the form is submitted. However, when the second form is submitted, I always get the values of the first form.
$(document).ready(function () {
$('form[name="inpForm"]').live('submit', function () {
alert($('input[name="FirstName"]').val());
return false;
});
});
How can I modify myJquery to find the "FirstName" element that matches the current form where the submit was triggered?
Thanks
Add some context:
alert($(this).find('input[name="FirstName"]').val());
Use this (the form-element) as context-argument:
alert($('input[name="FirstName"]',this).val());

HTML form with two submit buttons and two "target" attributes

I have one HTML <form>.
The form has only one action="" attribute.
However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note: This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="submit" formaction="firsttarget.php" value="Submit to first" />
<input type="submit" formaction="secondtarget.php" value="Submit to second" />
</form>
</body>
</html>
This works for me:
<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />
<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila.
Very "fancy", three word JavaScript!
Here's a quick example script that displays a form that changes the target type:
<script type="text/javascript">
function myTarget(form) {
for (i = 0; i < form.target_type.length; i++) {
if (form.target_type[i].checked)
val = form.target_type[i].value;
}
form.target = val;
return true;
}
</script>
<form action="" onSubmit="return myTarget(this);">
<input type="radio" name="target_type" value="_self" checked /> Self <br/>
<input type="radio" name="target_type" value="_blank" /> Blank <br/>
<input type="submit">
</form>
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
http://jsfiddle.net/arzo/unhc3/
<form id='myForm'>
<input type="button" name="first_btn" id="first_btn">
<input type="button" name="second_btn" id="second_btn">
</form>
<script>
$('#first_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "https://foo.com";
form.submit();
});
$('#second_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "http://bar.com";
form.submit();
});
</script>
It is do-able on the server side.
<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin" action="/facebook_login">Facebook</button>
and in my node server side script
app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
function(email_login) {...}
}
if(req.body.signin == "fb_signin"){
function(fb_login) {...}
}
});
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.
<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>
Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not
function v(){
var check = document.getElementsByTagName("input");
for (var i=0; i < check.length; i++) {
if (check[i].type == 'checkbox') {
if (check[i].checked == true) {
x[i]=check[i].value
}
}
}
console.log(x);
}
This might help someone:
Use the formtarget attribute
<html>
<body>
<form>
<!--submit on a new window-->
<input type="submit" formatarget="_blank" value="Submit to first" />
<!--submit on the same window-->
<input type="submit" formaction="_self" value="Submit to second" />
</form>
</body>
</html>
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
e.submitEvent.originalEvent.submitter.value
if you use event of form

Categories