clone/add-new form fields - javascript

<div class="input url required addnew" id="ConfigurationValues">
<label>Bigblue</label>
<input name="data[Configuration][value][]" value="cool" type="text">
<input name="data[Configuration][value][]" value="awesome" type="text">
<input name="data[Configuration][value][]" value="neat" type="text">
<div class="actions" style="padding-left:0px;">
<a onclick="return FALSE;" href="#" id="AddNew">Add</a>
</div>
</div>
I would like to replicate/clone the input. I have the below code that works for text.
$('a.AddNew').click(function(){
var pool = $(this).closest('.addnew');
pool.find('input[type=text]:first').clone().val('').insertAfter(pool.find("input[type=text]:last"));
return false
})
Now i want to write generalized code the takes care of type=url,email,tel,number and select tag.
In the above code line 3-6 will change as folows
<input name="data[Configuration][value][]" value="neat" type="url">
or
<input name="data[Configuration][value][]" value="neat" type="tel">
or
<select></select>

Do you mean something like this:
function cloneElement(selector) {
$('a.AddNew').click(function(){
var pool = $(this).closest('.addnew');
var inputs = pool.find(selector);
inputs.first().clone().val('').insertAfter(inputs.last());
return false;
});
}
function cloneInput(type) {
return cloneElement('input[type=' + type + ']');
}
function cloneSelect() {
return cloneElement('select');
}
EDIT: Ok, what about:
$('a.AddNew').click(function(){
var pool = $(this).closest('.addnew');
var inputs = pool.find("input, select");
inputs.first().clone().val('').insertAfter(inputs.last());
return false;
});

Related

on click the result appears then auto refreshes

document.querySelector('.login').addEventListener('click', function() {
const check = document.querySelector('.username').value;
console.log(typeof check);
if (!check) {
document.querySelector('.errorMessage').textContent =
'kindly enter your username';
}
});
<div class="user-login">
<form>
<label for="">User Name : <input type="text" name="userName" class=" username"></label> <br>
<label for="">Password: <input type="password" name="" class="password"></label> <br>
<button class="login">Login</button>
</form>
</div>
<div class="errorMessage">
<label for=""></label> <br>
</div>
To your html modify the button like this:
<button type="button" class="login">Login</button>
or in your javascript you can do something like this:
document.querySelector('.login').addEventListener('click', function(e) {
e.preventDefault(); // Add this after set 'e' as parameter
const check = document.querySelector('.username').value;
console.log(typeof check);
if (!check) {
document.querySelector('.errorMessage').textContent =
'kindly enter your username';
}
});

How to change the value of an Input control when the text of another Input control is changed?

I need the following output as shown in the gif below.
I created three inputs which I put in the box below. How can I have such output?
Please help with an example
NOTE:Suppose we have 50 inputs and the class is the same
I can't use it after Get ID
MY HTML code
<span class="pricing-heading">Your sale price:</span><div class="pricing-field"><input class="pricing-set-price" type="number" value="24.00"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span><div class="pricing-field"><input class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span><div class="pricing-field"><input class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
JS code :
$(".pricing-set-price").change(function(){
var item_rrp = $(this).val();
var item_base = $(this).parent().parent().parent().find('.pricing-base-price').val();
var profit = item_rrp - item_base;
var profit_format = profit.toFixed(2);
$(this).parent().parent().parent().find('.pricing-profit').val(profit_format);
});
You may try like
$(".pricing-set-price").change(function(){
let currentValue = $(this).val();
var previousValue = this.defaultValue;
if(previousValue < currentValue){
this.defaultValue = currentValue;
console.log('Increment');
}else{
console.log('Decrement');
}
});
You can call the function that changes the value of Profit (input) on the onchange , oninput, or onClick events of the SalePrice(input)
function increment() { document.getElementById('salePrice').stepUp();
calculateProfit()
}
function decrement() {
document.getElementById('salePrice').stepDown();
calculateProfit()
}
function calculateProfit(){
let sp = document.getElementById("salePrice").value;
document.getElementById("profit").value = sp - 10;
}
<input id="salePrice" type=number value=10 min=10 max=110 />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<br/>
Base Price :: <input type="text" id="basePrice" value=10
disabled >
<br/>
Profit :: <input type="text" id="profit" value=0 />
For more info about:
stepUp()
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp
stepDown()
https://www.w3schools.com/Jsref/met_week_stepdown.asp
Hi i think this might help. use id for your input fields.
function calculateProfit(val){
var baseCost = document.getElementById("baseCost").value;
document.getElementById("Profit").value = (val - baseCost).toFixed(2);
}
<div class="prt-pricing-heading">
<span class="pricing-heading">Your sale price:</span>
<div class="pricing-field"><input id="SalePrice" class="pricing-set-price" type="number" value="24.00" onchange="calculateProfit(this.value);" oninput="calculateProfit(this.value)"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span>
<div class="pricing-field"><input id="baseCost" class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span>
<div class="pricing-field"><input id="Profit" class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
For More info regarding:
oninput() https://www.w3schools.com/tags/att_oninput.asp
onchange() https://www.w3schools.com/tags/ev_onchange.asp

How to make an array with dynamic jQuery input?

I have a form with dynamic input. Inputs have same name attributes. So I want to make array for each row.
Like this;
[{'company':'Apple'},{'address':'USA'}],
[{'company':'Samsung'},{'address':'Korea'}]
I am using this simple form (it's dynamic);
<form id='companies'>
<input name='company[]'>
<input name='address[]'>
</form>
And this;
$('form').submit(function(event) {
var newFormData = $('#companies').serializeArray();
console.log(newFormData);
event.preventDefault();
});
Console Log; (All inputs in same array)
[{'company':'Apple'},{'address':'USA'},{'company':'Samsung'},{'address':'Korea'}]
This is an example of solution of your problem :)
<form id='companies'>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
... -> Now you have dynamic containers
</form>
You could use this approach to solve the problem with jQuery.
$('#companies').submit(function(event) {
var $data = [];
var $containers = $(".container-input");
$containers.each(function() {
var $contenedor = $(this);
var $inputCompany = $contenedor.find('input[name^="company"]');
var $inputAddress = $contenedor.find('input[name^="address"]');
var $objectInput = [{
'company': $inputCompany.val()
}, {
'address': $inputAddress.val()
}];
$data.push($objectInput);
});
console.log($data);
});
May help :) more dynamically.
$('#companies').submit(function(event) {
var $data = [];
$.each($(this).children("div"),function(){
obj={};
$.each($(this).find(":input"),function(){
obj[$(this).attr("name").replace("[]","")]=$(this).val();
$data.push(obj);
});
})
console.log($data);
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='companies'>
<div class="input">
<input name='company[]'>
<input name='address[]'>
<input name='phone[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<input type="submit"/>
</form>

How to disable button until input field has a value using AngularJS

I know nothing about Angular but I was asked to create a validation for the new google map input. All I want to do is have the #lugar_continuar button stay disabled until the input #ciudad is filled in, but the button isn't disabled for some reason.
index.php, input to validate
<div class="">
<input id="ciudad" name="ciudad" class="ciudad" type="text"
placeholder="Ciudad" value="" required ng-model="ciudadSet">
<div id="map"></div>
<input type="hidden" id="distance" size="31" value="31">
</div>
Input type button that should stay disabled
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && ciudadSet" ng-click="from_precio = true" >
Using ng-model doesn't work. I also tried with JS, in main.js:
var ReservasApp = angular.module('Reservas',['rzModule']);
ReservasApp.controller('ReservasController',function($scope){
$scope.ciudad = "";
$scope.validacionCiudad = function() {
var disabled = false;
if( $scope.ciudad != null && $scope.ciudad != "" )
{
disabled = false;
}
else
{
disabled = true;
}
}
}
index.php
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && validacionCiudad()" ng-click="from_precio = true" >
I also tried using only JS:
var validacionCiudad = function() {
var ciudad = document.getElementById('ciudad');
var btn = document.getElementById('lugar_continuar');
if (ciudad.value == "") {
btn.setAttribute("disabled", "disabled");
} else {
btn.removeAttribute("disabled");
}
}
validacionCiudad();
I have tried many ways to achieve this but nothing is working!
you can try this: ng-disabled = "ciudadSet == ''", since ng-disabled is valid when the expression equals true. If you must call function validacionCiudad to judge this, you have to return bool value in your function. May this will help.
Change $scope.ciudad ="" to $scope.ciudad = undefined;
change your ng-model to:
ng-model="ciudad"
and your ng-disabled to:
ng-disabled="!ciudad"
that shall work
You can validate it like this.
<div ng-controller="MyCtrl">
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<input name="name" ng-model="name" type="text" required >
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Enviar</button>
</form>
</div>
https://jsfiddle.net/ivanm07/y2t88817/

How do I remove the whole last html line in div?

What I basically am trying to accomplish is a form, where one can add a whole html line dynamically using javascript using one button, or remove an existing line using another.
I got the add function to work, yet I cannot seem to figure out the remove function.
Here is my code:
window.onload = function(){
var addHw = document.getElementById("addhw");
var removeHw = document.getElementById("removehw");
// Here is my add function
addHw.addEventListener('click', function () {
var homeworkGrade = document.createElement('input');
homeworkGrade.className = 'grade';
homeworkGrade.type = 'text';
homeworkGrade.size = 3;
var overallGrade = document.createElement('homework');
overallGrade.className = 'homework';
overallGrade.type = 'text';
overallGrade.size = 3;
var form = document.getElementById("assignments");
var r = "HW <input class=\"grade\" type = \"text \"size=\"3 \">/<input class=\"homework \" type = \"text \" size= \"3 \"><br />";
form.insertAdjacentHTML('beforeend',r);
});
// Here is my attempt at the remove function:
removeHw.addEventListener('click', function () {
var form = document.getElementById("assignments").lastChild;
var hw = document.getElementById("homework");
var grade = document.getElementById("grade");
});
}
<form id="myForm">
<div id="assignments">
<!-- add HWs here -->
HW <input class="grade" type="text" size="3">/<input class="homework" type="text" size="3"><br />
HW <input class="grade" type = "text" size="3 ">/<input class="homework " type = "text " size= "3 "><br />
HW <input class="grade" type = "text "size="3 ">/<input class="homework " type = "text " size= "3 "><br />
</div>
<div>
<!-- add curve here -->
<input type="checkbox" name="curve" />Curve + 5?
</div>
<div id="resultsarea ">
<p>
<!--add buttons-->
<button type="button" id="compute">Compute!</button>
<button type="button" id="addhw">Add HW</button>
<button type="button" id="removehw">Remove HW</button>
<button type="button" id="clear">Clear</button>
</p>
<!-- add the results here -->
<div id="result"></div>
</div>
</form>
I tried the removeChild and tried to remove the last child of "assignments", with no luck.
If someone would like to comment on my code and if it's efficient or provide me some comments that would benefit my progress, I'll be the most thankful.
By far the easiest way to do it is to update your code so that your "HW" are wrapped (e.g. in a span), and give all of these spans a class (e.g. "hw").
If you want them to be in different lines anyway, you may as well use a p or a div and remove the <br />.
window.addEventListener('load', function(){
var addHw = document.getElementById('addhw');
var removeHw = document.getElementById('removehw');
var hwHTML = '<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>';
var form = document.getElementById("assignments");
// Add hw.
addHw.addEventListener('click', function () {
// A lot of core were useless here as you only
// use the string at the end (and it is sufficient).
form.insertAdjacentHTML('beforeend', hwHTML);
});
// Remove hw.
removeHw.addEventListener('click', function () {
form.removeChild(form.querySelector(".hw:last-child"));
});
});
<form id="myForm">
<div id="assignments">
<!-- add HWs here -->
<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>
<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>
<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>
</div>
<div>
<!-- add curve here -->
<input type="checkbox" name="curve" />Curve + 5?
</div>
<div id="resultsarea ">
<p>
<!--add buttons-->
<button type="button" id="compute">Compute!</button>
<button type="button" id="addhw">Add HW</button>
<button type="button" id="removehw">Remove HW</button>
<button type="button" id="clear">Clear</button>
</p>
<!-- add the results here -->
<div id="result"></div>
</div>
</form>
It would be great to place every HW into its container. Because removal of the whole container is much easier.
Javascript:
(function(){
var addHw = document.getElementById("addhw");
var removeHw = document.getElementById("removehw");
// Here is my add function
addHw.addEventListener('click', function () {
var form = document.getElementById("assignments");
var r = "<div>HW <input class=\"grade\" type = \"text \"size=\"3 \">/<input class=\"homework \" type = \"text \" size= \"3 \"></div>";
form.insertAdjacentHTML('beforeend',r);
});
// Here is my attempt at the remove function:
removeHw.addEventListener('click', function () {
var form = document.getElementById("assignments");
var lastHW = form.lastChild;
if(lastHW) {
form.removeChild(lastHW);
}
});
})();
Html:
...
<div id="assignments">
<!-- add HWs here -->
<div>HW <input class="grade" type="text" size="3">/<input class="homework" type="text" size="3"></div>
<div>HW <input class="grade" type = "text" size="3 ">/<input class="homework " type = "text " size= "3 "></div>
<div>HW <input class="grade" type = "text "size="3 ">/<input class="homework " type = "text " size= "3 "></div>
</div>
...
Example: https://jsfiddle.net/61ytuoyb/
Can you try wrapping the individual assignments in an assignment and add a unique identifier to each assignment ?
<div id="assignments">
<div id="assignment_1">HW etc ...</div>
<div id="assignment_2">HW etc ...</div>
<div id="assignment_3">HW etc ...</div>
</div>
Use like a global counter variable to create the unique identifier for each assignment.
Then use the javascript
var idToDelete;
addHw.addEventListener('click', function () {
idToDelete = this.id; //not sure this is how to obtain the id in pure js.
});
removeHw.addEventListener('click', function () {
var parent = document.getElementById("assignments");
var child = document.getElementById("assignment_" + idToDelete);
parent.removeChild(child);
});
This off the top of my head. Untested code.

Categories

Resources