Html form calculation with javascript - javascript

I am trying to make HTML form with javascript but I could not make one part.
If a visitor selects from the dropdown menu "Service 1", the price will be multiplied with 1,5. If he selects "Service 2", the price multiplied with 2 and then with "adet" input value. I want to make multiplier values in script part like this;
var service_prices = new Array();
service_prices["service1"]=1.5;
service_prices["service2"]=2;
I need this calculation Paket(Dropdown)*Adet(Input) Could you help me?
These are my HTML codes;
<script>
$(function(){
//Adet
var val = $('#adet').val();
output = $('#output');
output.html(val);
$('#adet').on('change', function () {
output.html(this.value);
});
$('#Paket').change(function () {
if (this.value == "80") {
$('#adet').prop({
'min': 20,
});
}
if (this.value == "81") {
$('#adet').prop({
'min': 100,
});
}
$('#adet').val();
output.html('');
});
});
</script>
<form method="post" action="process.php"></br>
<label class="control-label col-sm-3" for="inputSuccess3">Paket</label>
<div class="col-sm-9">
<select class="form-control" id="Paket" name="paket">
<option value="80">Service 1 x1.5</option>
<option value="81">Service 2 x2</option>
</select>
</div>
<br>
<label class="control-label col-sm-3" for="inputSuccess3">Adet</label>
<div class="col-sm-9">
<input class="form-control" type="number" id="adet" name="adet" min="20" max="250" value="10" required>
</div>
<label class="control-label col-sm-3" for="inputSuccess3">Link</label>
<div class="col-sm-9">
<input class="form-control" type="text" name="link" required>
</div>
<div class="col-sm-offset-4 col-sm-8">
Fee: <span id="output"></span> Credi
</div>
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" class="btn btn-primary">Order</button>
</div>
</form>

You can store the values in an array like this:
var service_prices = [{
"name": "Service 1",
"value": 80,
"multiplier": 1.5
}, {
"name": "Service 2",
"value": 81,
"multiplier": 2
}
];
You can store the multiplier value in a data-attribute in every option of the Paket dropdown.
See this example:
(function() {
var service_prices = [{
"name": "Service 1",
"value": 80,
"multiplier": 1.5
}, {
"name": "Service 2",
"value": 81,
"multiplier": 2
}];
var Paket = document.getElementById("Paket");
var adet = document.getElementById("adet");
var output = document.getElementById("output");
adet.onchange = function() {
output.innerHTML = adet.value;
if (Paket.value.length > 0) {
var multiplier = Paket.options[Paket.selectedIndex].getAttribute("data-multiplier") * 1;
output.innerHTML = adet.value * (Paket.value * 1) * multiplier;
} else {
output.innerHTML = "";
}
};
Paket.onchange = function() {
if (this.value.length > 0) {
var multiplier = this.options[this.selectedIndex].getAttribute("data-multiplier") * 1;
if (this.value === "80") {
adet.setAttribute("min", "20");
}
if (this.value === "81") {
adet.setAttribute("min", "100");
}
adet.value = 10;
output.innerHTML = adet.value * (this.value * 1) * multiplier;
} else {
output.innerHTML = "";
}
};
function fillServices(data) {
var html = "", i, len = data.length, obj;
html += "<option value=\"\">[SELECT]</option>";
for (i = 0; i < len; i++) {
obj = data[i];
html += "<option data-multiplier=\"";
html += obj.multiplier;
html += "\" value=\"";
html += obj.value;
html += "\">";
html += obj.name;
html += "</option>";
}
return html;
}
Paket.innerHTML = fillServices(service_prices);
})();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<form method="post" action="process.php">
<label class="control-label col-sm-3" for="inputSuccess3">Paket</label>
<div class="col-sm-9">
<select class="form-control" id="Paket" name="paket">
</select>
</div>
<br>
<label class="control-label col-sm-3" for="inputSuccess3">Adet</label>
<div class="col-sm-9">
<input class="form-control" type="number" id="adet" name="adet" min="20" max="250" value="10" required>
</div>
<label class="control-label col-sm-3" for="inputSuccess3">Link</label>
<div class="col-sm-9">
<input class="form-control" type="text" name="link" required>
</div>
<div class="col-sm-offset-4 col-sm-8">
Fee: <span id="output"></span> Credi
</div>
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" class="btn btn-primary">Order</button>
</div>
</form>

Related

stuck create table add row dynamically

I create table add row Dynamically but my output be 3 not be 1
is it because of I use div class and not use table(tr & td) ?
example
enter image description here
This is My javascript
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$("#add").on("click", function () {
var newRow = $("div.rounded");
var cols = "";
cols += '<label>Paket </label><input type="text" class="form-control col-md-5" name="paket"><div class="invalid-feedback">Input paket bosz!' + counter + '</div></div>';
cols += '<label>Quantity </label><input type="text" class="form-control col-md-5" name="quantity"><div class="invalid-feedback">Input Quantity!' + counter + '</div></div>';
cols += '<label>Biaya </label><input type="text" class="form-control col-md-5" name="biaya"><div class="invalid-feedback">Input Biaya' + counter + '</div></div>';
newRow.append(cols);
$("div.rounded").append(newRow);
counter++;
});
$("div.rounded").on("click", function (event) {
$(this).closest("form-group").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
</script>
This My View
Paket
Input paket bosz!
<div class="col-4" style="margin-right: -290px;">
<div class="form-group rounded">
<label class="ulang">Quantity </label>
<input type="text" class="form-control col-md-5" name="quantity">
<div class="invalid-feedback">
Input Quantity!
</div>
</div>
</div>
<div class="col-4" style="margin-right: -290px;">
<div class="form-group rounded">
<label class="ulang">Biaya </label>
<input type="text" class="form-control col-md-5" name="biaya">
<div class="invalid-feedback">
Input Biaya
</div>
</div>
<br><br><br> <!-- pembatasan antara add order now -->
</div>

innerHTML is null? JS Form Validation

Why i get this error?
I'm using window.onload, i don't understand ... Can you help me?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Pràctica DOM3</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
<script type="text/javascript" src="script.js"></script>
<style>
h2 {
text-align: center;
border-bottom: 1px solid black;
padding-bottom: 20px;
/*text-decoration: underline;*/
}
#ultimsEstudisCursatsLabel {
margin-top: 10px;
}
#submitFormButton {
margin: auto;
display: block;
}
#resetFormButton {
margin: auto;
display: block;
}
meter {
margin: 0 auto 1em;
width: 100%;
height: .5em;
}
meter[value="1"]::-webkit-meter-optimum-value { background: red; }
meter[value="2"]::-webkit-meter-optimum-value { background: yellow; }
meter[value="3"]::-webkit-meter-optimum-value { background: orange; }
meter[value="4"]::-webkit-meter-optimum-value { background: green; }
</style>
</head>
<body>
<div class="container">
<h2>Inscripció CF Informàtica Marianao</h2>
<br>
<form method="post" action="#" id="formulari">
<div class="form-group">
<label class="control-label col-sm-2" for="input1">Nom</label>
<div class="col-sm-10">
<input type="text" name="nom" class="form-control" id="inputNom" placeholder="Escriu el teu nom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Primer cognom</label>
<div class="col-sm-10">
<input type="text" name="primerCognom" class="form-control" id="inputCognom1" placeholder="Escriu el primer cognom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Segon cognom</label>
<div class="col-sm-10">
<input type="text" name="segonCognom" class="form-control" id="inputCognom2" placeholder="Escriu el segon cognom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Data naixament </label>
<div class="col-sm-10">
<input type="date" name="dataNaixement" class="form-control" id="inputNaixament" placeholder="Selecciona la teva data de naixament ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Email </label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" id="inputEmail" placeholder="Escriu el teu correu electrònic ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Telèfon</label>
<div class="col-sm-10">
<input type="tel" name="telefon" class="form-control" id="inputTelefon" placeholder="Escriu el teu telèfon ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">DNI</label>
<div class="col-sm-10">
<input type="text" name="dni" class="form-control" id="inputDni" placeholder="Escriu el teu DNI ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="form-label col-sm-2">Cicle formatiu</label>
<div class="col-sm-10">
<select class="form-control" name="cicleFormatiu">
<option value="smx">SMX: Sistemes Microinformàtics i Xarxes</option>
<option value="asix">ASIX: Administració de Sistemes Informàtics en Xarxa</option>
<option value="dam">DAM: Desenvolupament d'Aplicacions Multiplataforma</option>
<option value="daw">DAW: Desenvolupament d'Aplicacions Web</option>
</select>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" id="ultimsEstudisCursatsLabel">Últims estudis cursats</label>
<div class="col-sm-10">
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="eso" class="custom-control-input">ESO</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="batx" class="custom-control-input">Batxillerat</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="cfgm" class="custom-control-input">CF Grau Mitjà</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="cfgs">CF Grau Superior</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="altres">Altres</label><br><br>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Usuari</label>
<div class="col-sm-10">
<input class="form-control" type="text" id="inputUsuari" name="usuari" />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Contrasenya</label>
<div class="col-sm-10">
<input type="password" id="password" name="contrasenya" class="form-control" />
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text"></p>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Torna a escriure la contrasenya</label>
<div class="col-sm-10">
<input type="password" name="contrasenyaCheck" id="contrasenyaCheck" class="form-control" disabled/>
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text"></p>
<br />
</div>
<br />
</div>
<div class="form-group">
<label class="control-label col-sm-2">Observacions</label>
<div class="col-sm-10">
<textarea class="form-control" name="observacions" id="textarea" maxlength="500"></textarea>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Termes i condicions</label>
<div class="col-sm-10">
<label class="checkbox-inline"><input type="checkbox" name="termesCondicions" value="yes" class="form-check-input" >Consulta <span>aquí</span> els termes i condicions.<br></label>
<br />
<br />
<br />
</div>
</div>
<div class="form-group">
<input type="submit" value="Submit Form" class="btn btn-success" id="submitFormButton">
</div>
<div class="form-group">
<input type="reset" value="Reset Form" class="btn btn-primary" id="resetFormButton">
</div>
</form>
</div>
</body>
</html>
JS:
function main (){
var inputNom = document.getElementById("inputNom").addEventListener("blur", validarNomCognoms);
var inputCognom1 = document.getElementById("inputCognom1").addEventListener("blur", validarNomCognoms);
var inputCognom2 = document.getElementById("inputCognom2").addEventListener("blur", validarNomCognoms);
var inputNaixament = document.getElementById("inputNaixament").addEventListener("blur", validarData);
var inputEmail = document.getElementById("inputEmail").addEventListener("blur", validarEmail);
var inputTelefon = document.getElementById("inputTelefon").addEventListener("blur", validarTelefon);
var inputDni = document.getElementById("inputDni").addEventListener("blur", validarDni);
var inputUsuari = document.getElementById("inputUsuari").addEventListener("blur", validarUsuari);
var password = document.getElementById("password").addEventListener("blur", validaContrassenya);
// Recuento de carácteres en el text area.
var textAreaID = document.getElementById("textarea");
var length = textAreaID.getAttribute("maxlength");
var textAreaCount = document.getElementById("count");
textAreaCount.innerHTML = length + " caràcters restants.";
textAreaID.addEventListener ("keypress", function () {
document.getElementById("count").innerHTML = (length - this.value.length) + " caràcters restants.";
});
// Barra de seguridad METER.
document.addEventListener("keydown", function () {
var strength = {
0: "Molt feble.",
1: "Feble.",
2: "Acceptable.",
3: "Forta.",
4: "Molt forta."
}
var password = document.getElementById('password');
var meter = document.getElementById('password-strength-meter');
var text = document.getElementById('password-strength-text');
password.addEventListener('input', function() {
var val = password.value;
var result = zxcvbn(val);
meter.value = result.score;
if(val !== "") {
text.innerHTML = "<strong>" + strength[result.score] + "</strong>";
}
else {
text.innerHTML = "";
}
if (meter.value >= 2) {
document.getElementById("contrasenyaCheck").disabled = false;
}
else {
document.getElementById("contrasenyaCheck").disabled = true;
document.getElementById('contrasenyaCheck').value = "";
}
});
});
// VALIDACIONES.
// Primera validación.
function validarNomCognoms () {
var pattern = /^[a-zA-Z]*$/;
if (this.value.length > 0) {
if(!this.value.match(pattern)) {
this.setCustomValidity("No pot contindre números!");
this.reportValidity();
}
else {
this.setCustomValidity("");
}
}
else {
this.setCustomValidity("No pot citear buit ");
this.reportValidity();
}
}
// Segunda validación.
function validarData () {
if (this.value != "") {
var dataRecibida = this.value;
dataRecibida = dataRecibida.split("-").reverse().join("-");
// Obtener la fecha actual.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = dd + '/' + mm + '/' + yyyy;
if (dataRecibida > today) {
alert ("Data incorrecta.");
}
//this.value.setCustomValidity("");
}
else {
alert ("citeá vacío.");
}
}
// Tercera validación.
function validarEmail () {
if (this.value != "") {
var emailPattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (emailPattern.test(this.value)) {
return;
}
else {
alert ("Mail incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Cuarta validación.
function validarTelefon () {
if (this.value != "") {
var emailPattern = /^\d{9}$/;
if (emailPattern.test(this.value)) {
return;
}
else {
alert ("Telèfon incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Quinta validación.
function validarDni () {
if (this.value != "") {
var emailPattern = /^\d{8}[A-Z]$/;
if (emailPattern.test(this.value)) {
var lletres = ['T', 'R', 'W', 'A',
'G', 'M', 'Y', 'F',
'P', 'D', 'X', 'B',
'N', 'J', 'Z', 'S',
'Q', 'V', 'H', 'L',
'C', 'K', 'E', 'T'];
var index = this.value % 23;
var my_array = this.value;
var last_element = my_array[my_array.length - 1];
var boolean = false;
for (var i = 0; i < lletres.length; i++) {
if (last_element == lletres[i]) {
boolean = true;
}
}
if (boolean) {
return;
}
else {
alert ("Lletra DNI incorrecte.");
}
}
else {
alert ("DNI incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Sexta validación.
function validarUsuari () {
if (this.value != "") {
if (this.value.length < 5) {
alert ("Longitud mínima de 5 caràcters.");
}
else if (this.value.length > 12) {
alert ("Longitud màxima de 12 caràcters.");
}
else {
return;
}
}
else {
alert ("Está vacío.");
}
}
// Seéptima validación.
function validaContrassenya () {
var meter = document.getElementById('password-strength-meter');
if (meter.value < 2) {
document.getElementById("cite9").style.display = "block";
}
else {
document.getElementById("cite9").style.display = "none";
}
}
}
window.onload = main;
Thanks guys!!
ERROR:
You never defined an element with id="count". Just check.
Also, when you define it, make sure it is a direct child of the body. You may try not to do this, but sometimes errors are caused.
Hope you understand now!

Calculating multiple inputs value with javascript

i'm having trouble going trough making a calculator (sum only) of 5 inputs fields in html/javascript and i can't manage to find what's wrong in my code
i tried messing around with types such as int instead of var and passing the value into parseInt, i somehow managed to have a result like "11111" where it should be like "5" but alongside that case the result is never printed in the innerHTML even after i added the "if not null" condition
Here is my html
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute();">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
and here is my javascript
function ratingCompute()
{
var designValue = document.getElementById("design").value;
var plotValue = document.getElementById("plot").value;
var charValue = document.getElementById("character").value;
var enjoyValue = document.getElementById("enjoyment").value;
var musicValue = document.getElementById("music").value;
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
Any clue?
JavaScript is not a type variable language try using let or const. And here is how you properly parse it. If you did it already then its because of your variable declaration.
let designValue = parseInt(document.getElementById("design").value);
let plotValue = parseInt(document.getElementById("plot").value);
let charValue = parseInt(document.getElementById("character").value);
let enjoyValue = parseInt(document.getElementById("enjoyment").value);
let musicValue = parseInt(document.getElementById("music").value);
In javascript you should use keyword var/let/const instead of int. and you have to convert String type input value to int using parseInt method.
Please check this:
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute()">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
As mentioned by #Joshua Aclan, JavaScript does not have an "int" variable declaration, only "var". Also you have to cast all of the inputs to int or float, because otherwise you are adding strings and the values of input fields are always strings. Also the output is most likely empty because int designValue... produces an error.
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}

Adding lines in a form an autocomplete function breaks

In a form I have 2 inputs. In the 1st input I use a datalist which I load it through JSON and the 2nd input is autocomplete it when the 1st input is changed.
Till here all works!
Then I added an add button where I add the same lines. The problem is that because I use id to select the input, when I add the new line I have the same id.. So the autocomplete doesn't work..
How can I solve this? Here the jssFiddle.
counter = 0;
var dataList = document.getElementById('products');
var jsonOptions = [{
"product": "11111",
"description": "description 1"
}, {
"product": "22222",
"description": "description 2"
}, {
"product": "33333",
"description": "description 3"
}];
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.value = item.product;
option.text = item.description;
dataList.appendChild(option);
$(function() {
$('#product').on('change keyup', function() {
var i = this.value;
var description = "";
var productsInBox = 0;
jsonOptions.forEach(function(a) {
if (a.product == i) {
description = a.description;
productsInBox = a.productsInBox;
}
});
$('#description').val(description);
});
});
});
$('#form1')
// Add button click handler
.on('click', '.addButtonDED', function() {
counter++;
var $template = $('#addLineInDed'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-index', counter)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="product"]').attr('name', 'product-' + counter).end()
.find('[name="description"]').attr('name', 'description-' + counter).end()
})
// Remove button click handler
.on('click', '.removeButtonDED', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-index');
counter--;
// Remove element containing the fields
$row.remove();
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" class="form-horizontal" role="form">
<fieldset>
<div class="form-group">
<div class="col-xs-2">
<input type="text" id="product" list="products" class="form-control" name="product-0" />
<datalist id="products"></datalist>
</div>
<div class="col-xs-4">
<input id="description" type="text" class="form-control" name="description-0" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default addButtonDED"><i class="fa fa-plus"></i></button>
</div>
</div>
<div id="addLineInDed" class="form-group hide">
<div class="form-group">
<div class="col-xs-2">
<input type="text" id="product" list="products" class="form-control" name="product-0" />
<datalist id="products"></datalist>
</div>
<div class="col-xs-4">
<input id="description" type="text" class="form-control" name="description-0" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default removeButtonDED"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<div class="col-md-10 ">
<button type="submit" name="formAction" value="next" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
Use classes, rename your selecs to array values:
counter = 0;
var dataList = $('.products');
var jsonOptions = [{
"product": "11111",
"description": "description 1"
}, {
"product": "22222",
"description": "description 2"
}, {
"product": "33333",
"description": "description 3"
}];
jsonOptions.forEach(function(item) {
var option = '<option value="' + item.product + '">' + item.description + '</option>';
dataList.append(option);
});
$(function() {
$('body').on('input', '.product,.products', function() {
var i = this.value;
var description = "";
var productsInBox = 0;
jsonOptions.forEach(function(a) {
if (a.product == i) {
description = a.description;
productsInBox = a.productsInBox;
}
});
$(this).closest('.form-group').find('.description').val(description);
});
});
$('#form1').on('click', '.addButtonDED', function() {
var $template = $('.form-group:last').clone(true, true).find('input').val('').end()
.find('.addButtonDED').removeClass('addButtonDED').addClass('removeButtonDED').end()
.find('i').removeClass('fa-plus').addClass('fa-minus').end();
$template.insertAfter('.form-group:last');
})
// Remove button click handler
.on('click', '.removeButtonDED', function() {
var $row = $(this).closest('.form-group');
$row.remove();
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" class="form-horizontal" role="form">
<fieldset>
<div class="form-group">
<div class="col-md-2">
<input type="text" list="products" class="form-control product" name="product[]" />
<datalist id="products" class="products"></datalist>
</div>
<div class="col-md-4">
<input id="" type="text" class="form-control description" name=" description[]" />
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButtonDED"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="col-md-10 ">
<button type="submit" name="formAction" value="next" class="btn btn-primary">sUBMIT</button>
</div>
</fieldset>
</form>
</fieldset>
</form>
to read the values do a loop:
foreach($_POST['product'] as $product) {
//do stuf
}
Seeing as you said you've tried to use classes,
How about encapsulating your code so that you'll have a function like so:
function FilldatalistOptions(element,options)
You can then have the 2 datalists with different id's (products1 and products2 perhaps).
And just call the function like so:
var dataList1 = document.getElementById('products1');
var dataList2 = document.getElementById('products2');
FilldatalistOptions(datalist1, jsonOptions);
FilldatalistOptions(datalist2, jsonOptions);

Javascript I can't reach result variables in function

I called my datas with ajax then created variables in result but I cannot reach my variables in other function. How can I reach variables or create as a public function ? $("#btBilgileriAktar") is my new function .I want to take variables in this function.
Thank you for your helps.
$.ajax({
type: 'POST',
data: {
data: gripin
},
datatype: 'html',
url: '<?php echo site_url('
servis / bring_Cari '); ?>',
success: function(result) {
var obj = $.parseJSON(result);
// console.log(obj);
$.each(obj, function(key, value) {
// console.log(value);
$("table#cariler tbody").append("<tr class=\"cariKayit\"><td class=\"tdCariAdi\">" + obj[key].CARI_ISIM + "</td><td class=\"tdVergiNo\">" + ((obj[key].VERGI_NUMARASI == null) ? "" : obj[key].VERGI_NUMARASI) + "</td><td class=\"tdVergiDairesi\">" + ((obj[key].VERGI_DAIRESI == null) ? "" : obj[key].VERGI_DAIRESI) + "</td><td class=\"tdCariAdres\">" + ((obj[key].CARI_ADRES == null) ? "" : obj[key].CARI_ADRES) + "</td><td class=\"tdCariTel\">" + ((obj[key].CARI_TEL == null) ? "" : obj[key].CARI_TEL) + "</td><td class=\"tdCariIlce\">" + ((obj[key].CARI_ILCE == null) ? "" : obj[key].CARI_ILCE) + "</td><td class=\"tdCariIl\">" + ((obj[key].CARI_IL == null) ? "" : obj[key].CARI_IL) + "</td><td><input type=\"checkbox\" id=\"checks\"/></td></tr>");
});
$('#checks').on("click", function() { //Çalışıyor
var nAdi = $(this).parent().parent().find(".tdCariAdi").text();
var nVno = $(this).parent().parent().find(".tdVergiNo").text();
var nVdairesi = $(this).parent().parent().find(".tdVergiDairesi").text();
var nAdres = $(this).parent().parent().find(".tdCariAdres").text();
var nTel = $(this).parent().parent().find(".tdCariTel").text();
var nIlce = $(this).parent().parent().find(".tdCariIlce").text();
var nIl = $(this).parent().parent().find(".tdCariIl").text();
});
$('#btBilgileriAktar').on('click', function() { //Buda seçimi çekiyor ama burada sıkıntı var verileri almıyor.
var tcLength = nVno.toString();
if (tcLength.length == 11) {
$("#spTc").val(tcLength);
} else if (tcLength.length == 10) {
$("#spVno").val(tcLength);
} else {
$("#spTc").val("");
$("#spVno").val("");
}
$("#spCariAdi").val(nAdi);
$("#spVergiDairesi").val(nVdairesi);
$("#spAdres").val(nAdres);
$("#spTel").val(nTel);
$("#spIlce").val(nIlce);
$("#spIl").val(nIl);
});
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="tab-pane fade active in" id="musteri">
<div class="form-group">
<label class="control-label" for="focusedInput">Müşteri Adı</label>
<input class="form-control" id="spCariAdi" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Adres</label>
<input class="form-control" id="spAdres" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">İlçe</label>
<input class="form-control" id="spIlce" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">İl</label>
<input class="form-control" id="spIl" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Tel</label>
<input class="form-control" id="spTel" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Vergi Dairesi</label>
<input class="form-control" id="spVergiDairesi" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">TC Kimlik No</label>
<input class="form-control" id="spTc" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Vergi No</label>
<input class="form-control" id="spVno" type="text" value="">
</div>
</div>
Because you are declaring variables in another function. You need global variables for accessing them from different function.
var nAdi = ''; //global var declaration
$('#checks').on("click", function() { //Çalışıyor
nAdi = $(this).parent().parent().find(".tdCariAdi").text(); //assigning value
});
$('#btBilgileriAktar').on('click', function() {
$("#spCariAdi").val(nAdi); // retrieving value
});

Categories