AngularJS dynamically add input fields and keep reference to each - javascript

I am currently trying to figure out how to keep reference to individual dynamically added input fields. I have a modal popup as follows:
<div ng-controller="SamplesQueryController">
<button ng-click="toggleModal()" class="btn-splash-small">Add Sample</button>
<modal title="Create New Sample" visible="showModal">
<form role="form">
Sample Name:<br>
<input type="text" ng-model="newSampleName.sampleName">
<br> Attribute 1 Name:<br>
<input type="text" ng-model="newAtt1Name.att1Name">
<br> Attribute 1 Value: <br>
<input type="text" ng-model="newAtt1Value.att1Value"> <br>
<button id="submitSample" ng-click="createSample();toggleModal()">Submit
Sample</button>
<button id="addAttribute">Add Attribute</button>
<button ng-click="toggleModal()">Close</button>
</form>
</modal>
</div>
which currently has an input field for att1Name and att1Value, I have an addAttribute button which should add 2 new input fields (for att2Name and att2Value). I can dynamically create the inputs using a method such as:
<input type="text" ng-repeat="myinput in myinputs" ng-model="myinput">
</input>
but how can I keep reference to each of the typed in values in the input fields and how can I create 2 fields for each element in myinputs
Preferably, I would be storing these values in some sort of structure like attributes.att1.name, attributes.att1.value, attributes.att8.name, etc

You'll want to have your model as an Array that contains Objects, which has the property 'name' and 'value' initiated.
Then it's pretty easy to create a ng-repeat div, that contains 2 text input fields:
<div ng-repeat="input in inputs">
<input type="text" ng-model="input.l">
<input type="text" ng-model="input.v">
</div>
Then you can subsequently add the fields by pushing newly initiated object to the $scope.inputs.
function add() {
var obj = {attr1Name: '', attr1Value: ''};
$scope.inputs.push(obj);
}
Working fiddle here: https://jsfiddle.net/ccvLhmps/

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<h2>Cost Calculator</h2>
<p></p>
<p></p>
<p></p>
<div ng-app>
<input name="amount" ng-model="a" placeholder="Amount" />
<input name="adjustment" ng-model="b" placeholder="Adjustment" />
<input name="advance" ng-model="c" placeholder="Total" value='{{ a-b}}' />
<input name="balance" placeholder="Total" readonly required value='{{ a-b-c}}' />
</div>
</body>
</html>

Related

Prevent input to get cleared when the parend is modified

Can I have some inputs on this ?
Issue
When a form or a parent element of a form is modified, the text that was typed inside the inputs of the form get cleared. As this snipper show :
function modifyParent() {
document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" id="child">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
Hello everyone,
Solution 1
I found a first esay way to prevent it if I know where the parent is modified. As this snipper show
function modifyParent() {
var child = document.getElementById("child");
child.setAttribute("value", child.value)
document.getElementById("parent").innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" id="child" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
This solution look great, but only if i know where ans when the parent is modified. Also if i have a multiple inputs i need to loop on document.getElementsByTagName("input").
Solution 2
Since i dont know how many buttons i have and how many inputs, this is my best solution so far :
function modifyParent() {
setInputValues();
document.getElementById("parent").innerHTML += "<br>a line get added";
}
function setInputValues() {
for (var c of document.getElementsByTagName("input"))
c.setAttribute("value", c.value);
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
</div>
It work well for multiple inputs but i have to call the setInputValues() function before i modify any parent everytime. I started to consider to add setInterval on this function but I stop here because i'm starting to go a bit far and it's very likely that their is a better way.
Any help will be apreciated
A cleaner solution is to use a new element for the messages. This way you can set the messages inside a container without messing with the inputs.
const messageBox = document.querySelector(".messages");
function modifyParent() {
messageBox.innerHTML += "<br>a line get added";
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
<div class="messages"></div>
</div>
Another quick notice, innerHTML is vulnerable for XSS attacks Try using createElement and appendChild if possible.
const parent = document.getElementById("parent");
function modifyParent() {
const br = document.createElement("br");
const text = document.createTextNode("a line get added");
parent.appendChild(br);
parent.appendChild(text);
}
<div id="parent">
<form>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</form>
<button type="button" onclick="modifyParent()">click</button>
<div class="messages"></div>
</div>

How to change <p> tag content in input box value?

I have a one word <p>, and I'm looking to change the content of that paragraph to the value of a input box. It's really simple but I'm new to JavaScript and jQuery.
This is the paragraph to change
<p class="editor-example" id="screen-name">Name</p>
and this is the form and the button I'm using to get and apply the change
<form id="info">
<input id="nameID" name="name" type="text" size="20">
</form>
<button id="apply" type="button">Apply</button>
Making the paragraph automatically change when the input box changes instead of a button would be handy if you want to take your time.
Thanks!!
Put the button inside the form and add an event listener to it. Then grab the value from the input and use innerHTML to replace the content inside p tag
document.getElementById('apply').addEventListener('click', function() {
document.getElementById('screen-name').innerHTML = document.getElementById('nameID').value.trim()
})
<p class="editor-example" id="screen-name">Name</p>
<form id="info">
<input id="nameID" name="name" type="text" size="20">
<button id="apply" type="button">Apply</button>
</form>
You need to write keypress event for the text box
$("#text").keypress(function() {
$("#p").html($("#text").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p">p</p>
Please change the value of imput to change p: <input id="text"></input>
You can do like this:
$(document).ready(function(){
$("#nameID").keyup(function(){
var name = $("#nameID").val();
$("#screen-name").text(name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="editor-example" id="screen-name">Name</p>
<form id="info">
<input id="nameID" name="name" type="text" size="20">
</form>
<button id="apply" type="button">Apply</button>
As you said:
Making the paragraph automatically change when the input box changes instead of a button would be handy if you want to take your time. Thanks!!
In Jquery:
$(document).ready(function(){
$('#nameID').keyup(function(){
$('#screen-name').text($(this).val());
});
});
In html:
<p class="editor-example" id="screen-name">Name</p>
<form id="info">
<input id="nameID" name="name" type="text" size="20">
</form>
<button id="apply" type="button">Apply</button>
$("#apply").click(function() {
$("#paragraph").text($("#nameID").val());
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<p id="paragraph">This Text changes from the form below</p>
<form>
<input id="nameID" type="text" >
<button id="apply" type="button">Apply</button>
</form>

how to get set of input boxes values using getElemntById?

I have set of input boxes to add names and designaions.and iwant to print those in a <p> tag when user click print button. how to proceed.
<div class="form-group">
<label for="inputRegNo" >Name & Designation<span style="color:#c0392b;padding-left:5px;">*</span></label>
<div class="form-group">
<input required type="text" name="fname[]" class="fname" onkeyUp="document.getElementById('refa5').innerHTML = this.value" placeholder="Name" />
<input required type="text" name="lname[]" placeholder="Designation" />
</div>
</div>
<div class="form-group">
<label for="inputRegNo" ></label>
<div class="form-group">
<input type="text" name="fname[]" placeholder="Name" class="fname" onkeyUp="document.getElementById('refa5').innerHTML = this.value" />
<input type="text" name="lname[]" placeholder="Designation" />
</div>
</div>
print
<div>
<label>Name & Designation</label>
<p id="refa5"> - </p>
</div>
its looks you are new in javascript.. it's simple give the name to all the input field like
<input type="text/checkbox" name="txtName">
and in javascript you can access this field value by
<script type="text/javascript">
var name = document.getElementsByName("txtName");
</script>
if you wish to print the element on button click simply specify their click event on javascript like
function onClick() {
alert("helo from click function");
}
and then on button ..
<input type="button" onclick="onClick()">
w3schools is a great resource for this. Here is some example code on how to do this :
<button onclick="myFunction()">Click me</button>
<input id="inputID"></input>
<p id="demo"></p>
<script>
function myFunction() {
var inputID = document.getElementById("inputID").value;
document.getElementById("demo").innerHTML = inputID;
}
</script>
What the code above does is it takes the value of an input, then it sets the innerHTML of a <p> element to it. You can obviously do this with other things like <h1> elements as well.

Input type text value cannot be updated via jQuery

Below is the simple requirement in html, jQuery, servlet
Implementation: Forgot password module
Username text field and send button. --> OK
User enters username and press send button. --> Ok
Fire jquery on click event, post method --> OK
From DB get the security question for username --> OK
Get result in jquery call --> OK
display security question value in text field --> NOK
Some how I feel, the text field is updated and refreshed to old value.
so in my case,
step 1) Text value - placeholder property value
step 2) update from jQuery
step 3) again refreshed to placeholder property value
jQuery
$(document).on("click", "#btnuserName", function() {
$.post("/zmcwebadmin/ForgotPasswordServlet",function(securityQuestion) {
alert("I got the response in ajax "+ securityQuestion);//value is correct
$("input[type=text].txt_securityQuestion").val(securityQuestion); //problem here
console.log("txt_securityQuestion");
});
});
html
<input type="text" id="ForgotPassUname" name="user_name" class="changepassformat"placeholder="Enter Username">
<button class="buttonformat" id="btnuserName" name="btnuserName">SEND</button><br>
<input type="text" id="txt_securityQuestion" name="txt_securityQuestion" class="changepassformat" placeholder="Security Question"><br>
<input type="text" id="SecurityAns" name="SecurityAns" class="changepassformat" placeholder="Enter the Answer">
Entire html code
<body background="../Images/zebra_background.jpg">
<div id="header">
<span style="float: left">ZMC Server </span> <img
src="../Images/zebra_logo.png" width=150px height=50px
style="float: right; padding-top: 5px">
<form id="form_logout">
<input type="image" class="logbuttonformat" id="logoutbtn"
src="../Images/logout_deselected.png" onclick="changeLogoutImage()"
alt="submit" style="padding: auto">
</form>
</div>
<form id="form_forgotpswd" >
<p class="slectedNameformat"> FORGOT PASSWORD </p>
<input type="text" id="ForgotPassUname" name="user_name" class="changepassformat"placeholder="Enter Username">
<button class="buttonformat" id="btnuserName" name="btnuserName">SEND</button><br>
<input type="text" id="txt_securityQuestion" name="txt_securityQuestion" class="changepassformat">
<br>
<input type="text" id="SecurityAns" name="SecurityAns"class="changepassformat" placeholder="Enter the Answer">
<br><input type="button" class="buttonformat" value="SUBMIT">
</form>
</body>
</html>
You need id selector instead of class selector here as txt_securityQuestion is id of element and not its class:
$("#txt_securityQuestion").val(securityQuestion);

Data manipulation with div classes and forms

How to take content from a div class one by one and then load it into array? Then I need to insert these one by one to some other div class.
Basically, I have 2 forms, one of which is dummy and this dummy gets its content from CMS. The dummy form is hidden, while real form is shown, but empty at first.
I need to use jquery to take dummy text from form and insert it to real form.
Something like this:
<form name="real" method="post" action="">
<input type="text" name="first" id="a"/>
<input type="text" name="second" id="b"/>
<input type="text" name="third" id="c"/>
<input type="text" name="fourth" id="d"/>
<input type="submit" value="submit"/>
</form>
<form name="extract" style="display:none;">
<div class="generic">data_1</div>
<div class="generic">data_2</div>
<div class="generic">data_3</div>
<div class="generic">data_4</div>
</form>
must become something like this:
<form name="real" method="post" action="">
data_1 <input type="text" name="first" id="a"/>
data_2 <input type="text" name="second" id="b"/>
data_3 <input type="text" name="third" id="c"/>
data_4 <input type="text" name="fourth" id="d"/>
<input type="submit" value="submit"/>
</form>
Is there a way to do this?
Thanks!
There are many ways to do this. For example:
$('[name=extract] div').each(function(index){
$('[name=real] input:eq('+index+')').before($(this).text());
});
http://jsfiddle.net/seeSv/
edit: here are the api pages to the methods used:
http://api.jquery.com/attribute-equals-selector/
http://api.jquery.com/each/
http://api.jquery.com/eq-selector/
http://api.jquery.com/before/
You may want to check out the jQuery DataLink Plugin
I'll offer this version:
$('.generic').each(
function(i){
$('input:text').eq(i).val($(this).text());
});
JS Fiddle demo.
Assumptions:
a 1:1 ratio between div.generic:input[type=text]
References:
each(),
:text pseudo-selector
eq().

Categories

Resources