I am working in ASP.Net MVC4. My div elements contents are generated in a loop as below:
#foreach (var product in Model.Products)
{
<div class="col-md-2 vcenter">
<span class="product-price">Preço: #Model.Price.ToString("C")</span>
</div>
#if (Model.IsValid != null && Model.IsValid != "")
{
<div class="col-md-2" style="text-align: end;">
<span>Enter number.</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
#Html.TextBoxFor(m => m.CouponTemp, new {
#class = "product-discount-coupon",
chart_price = Model.Price.ToString(),
dicsount_price = Model.SpecialPrice.ToString(),
product_coupon = Model.Coupon,
style = "width:50px;"
})
<button type="button" class="apply-discount">Recalculate</button>
</div>
}
}
JavaScript portion
$(".apply-discount").on("click", function () {
var applyCoupon = $(this).parent().find(".product-discount-coupon").val();
var price = $(this).parent().find(".product-price").val();
var cost = 0;
if (applyCoupon === NaN) {
applyCoupon = 0;
}
if (price === NaN) {
price = 0;
}
$(this).parent().find(".product-price").val(applyCoupon);
});
Browser generated html is below
<div>
<div class="col-md-1">
<img src="/Astrology/Product/GetImage/51da66b7-3cb9-418b-ae9a-bc9fe8073b26" style="width: 50px; height: 50px;" alt="Mapa Natal Cármico" />
</div>
<div class="col-md-6 vcenter">
<span style="font-size: large">Mapa Natal Cármico. Escrito por Marcelo Dalla</span>
</div>
<div class="col-md-2 vcenter">
<span class="product-price">Preço: R$ 44,00</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
<button type="button" class="dec-count">-</button>
<input chart-price="44,0000" class="product-count" data-val="true" data-val-number="The field Quantity must be a number." data-val-required="The Quantity field is required." dicsount-price="10,0000" id="products_7819060a-0f29-4637-83de-9262beb1a13f__Quantity" name="products[7819060a-0f29-4637-83de-9262beb1a13f].Quantity" product-coupon="10" readonly="readonly" style="width:50px;" type="text" value="1" />
<button type="button" class="inc-count">+</button>
</div>
<span>If you have a discount coupon for the purchase please enter it here and press the recalculate button.</span>
<div class="col-md-2 vcenter" style="text-align: end;">
<input chart-price="44,0000" class="product-discount-coupon" dicsount-price="10,0000" id="products_7819060a-0f29-4637-83de-9262beb1a13f__CouponTemp" name="products[7819060a-0f29-4637-83de-9262beb1a13f].CouponTemp" product-coupon="10" style="width:50px;" type="text" value="" />
<button type="button" class="apply-discount">Recalculate</button>
<input id="apply-product-coupon" type="hidden" name="apply-product-coupon">
</div>
<div class="col-md-1 vcenter">
<a href="/Astrology/Shop/DeleteFromCard?productId=41f7e40b-62ad-4202-964a-cbed7381b06c">
<i class="fa fa-remove"></i>
</a>
</div>
</div>
When the user clicks on the Recalculate button I want to put CouponTemp textbox value in another span. Note that clicking on block-1 does not impact on block-2 or rest, in the same way click on block-2 not impact on another block content.
<span>Preço: #Model.Price.ToString("C")</span>
Here is your script:
$(document).ready(function(){
$("button.apply-discount").click(function(){
//get your input value
var discount = $(this).prev('input.product-discount-coupon').first().val();
//Get your span
var resultSpan = $(this).parent().prev().prev().prev().find('span');
//Update your span with input value
resultSpan.html("Preço: R$ " + discount);
});
});
I create JSFiddle to show how it works.
Following code snippet may help you.
$(".apply-discount").on("click", function () {
var applyCoupon = $(this).parent().find(".product-discount-coupon");
var price = applyCoupon.val();
//to get others info
var chart_price= applyCoupon.attr('chart_price');
var dicsount_price= applyCoupon.attr('dicsount_price');
var product_coupon= applyCoupon.attr('product_coupon');
$(this).parent().prev().prev().find(".product-price").html('Preço: '+price*1);
});
N.B: price*1 will convert it to a number.
Well, pretty easy if you just assign ids to the elements. Use something like id from your product to ensure they are unique and match.
#foreach (var product in Model.Products)
{
<div class="col-md-2 vcenter">
<span>Preço: #Model.Price.ToString("C")</span>
</div>
#if (Model.IsValid != null && Model.IsValid != "")
{
<div class="col-md-2" style="text-align: end;">
<span id="#product.Id">Enter number.</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
#Html.TextBoxFor(m => m.CouponTemp, new {
#class = "product-discount-coupon",
chart_price = Model.Price.ToString(),
dicsount_price = Model.SpecialPrice.ToString(),
product_coupon = Model.Coupon,
style = "width:50px;",
id = "txt_" + #product.Id
})
<button type="button" class="apply-discount" onclick="adjustPrice(#product.Id);">Recalculate</button>
</div>
}
}
Then have a function that handles it:
<script type="text/javascript">
var adjustPrice = function (id) {
var txt = $('#txt_' + id).val();
$('#' + id).val(txt);
};
</script>
Related
I'm trying to give a for or foreach based on my data-index to add value to each of the adesaoTest fields
If the data-index is equal to zero it normally goes through the process
The first time the code is compiled normally, but the second time when the data-index is = 1 it does not calculate
JavaScript
adesao = 0.00;
const totalAdesao = document.querySelectorAll('.quota-row');
totalAdesao.forEach(adesaoTest => {
var index = adesaoTest.getAttribute('data-index');
var entrada = document.getElementById(`quota-entrada-${index}`);
var parcelas = document.getElementById(`quota-parcelas-${index}`);
var adesaoTest = document.getElementById(`quota-adesao-${index}`);
adesao = parseFloat(entrada.value) / parcelas.value;
adesaoTest.value = adesao;
})
For each of the fields var adesaoTest = document.getElementById(quota-adesao-${index})
must perform calculation above
Note:
I'm using fetch to add the new entries that will go through for or foreach
When the second element is created it gives the following error
This is the function that adds the other elements
var quotasDiv = document.getElementById('quotas');
const id = quotasDiv.querySelectorAll('.row').length + 1;
var quotaPrincipal = document.getElementById('quota-principal');
const request = new Request('/configuracoes/listFormaPagamento/json', { method: 'POST' });
fetch(request)
.then(res => {
res.json()
.then(data => {
var html = `<div class="row quota-row" data-index="${id}">
<div class="col-8" id="quota-${id}" >
<div>
<div class="col-xs-2">
<span>Entrada ${(id + 1)}</span>
<input onblur="calculaRestante(this)" type="text" data-index="${id}" id="quota-entrada-${id}" required="" name="entrada[]" placeholder="Primeira Parte" id="valor8" value="0">
</div>
<div class="col-xs-2 dateInput">
<span>Forma de Pagamento</span>
<select onchange="onChangeFormaPagamento(this)" data-index="${id}" id="quota-forma-pagamento-${id}" name="forma_pagamento[]">
<option value="">Selecione a forma de pagamento</option>
${data.map(forma_pagamento => {
return `<option value="${forma_pagamento.id_formas_pagamento}"> ${forma_pagamento.forma_pagamento} </option>`
})}
</select>
</div>
<div class="col-xs-1 dateInput">
<span>Parcelas</span>
<select data-index="${id}" id="quota-parcelas-${id}" onchange="calculaAdesao()" name="parcelas[]" >
<option value=""></option>
</select>
</div>
<div class="col-xs-2">
<span>Vencimento</span>
<input data-index="${id}" type="date" required="" id="quota-vencimento-${id}" name="vencimento[]" placeholder="Entrada">
</div>
<div class="col-xs-2">
<span>Adesão</span>
<input data-index="${id}" type="text" required="" id="quota-adesao-${id} "name="adesao[]" placeholder="Valor de entrada" id="valor6">
</div>
<div class="col-xs-2">
<span style="color: red; cursor: pointer; margin-top: 3rem" onclick="deleteQuotaHtml(this)"><i class="fas fa-trash-alt"></i></span>
<div>
</div>
</div>
</div>`;
quotasDiv.innerHTML += html;
})
})
}
In the form I am making, there is a section that requires users to enter the amount of people in their family. After they provide it, the form generates enough input fields so that the user can enter information for each family member.
What I am having trouble with is none of the attributes that I am trying to apply to the input element actually work.
function addHouseMembers(that){
var family = document.getElementById("family-input-container");
while(family.hasChildNodes()){
family.removeChild(family.lastChild);
}
for(var i = 1; i < that.value; i++){
family.appendChild(document.createTextNode("Family Member " + (i+1)));
family.appendChild(document.createElement("br"));
//name
family.appendChild(document.createTextNode("Name: " ));
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i + "_name";
input.pattern = "/^[a-zA-Z ]*$/";
input.required = true;
family.appendChild(input);
family.appendChild(document.createElement("br"));
}
}
The parameter that refers to the input where the user would put in the number of people in their family.
And here is the relevant HTML:
<form>
<div class="form-group">
<label class="col-lg-3 control-label">What is the total amount of people living in your household?</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group">
<input type="text" class="form-control" name="household-size" required onchange="addHouseMembers(this);"/>
</div>
</div>
</div>
<div class="form-group", id="family-info">
<label class="col-lg-12">Information for other Family Members</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group" id = "family-input-container" required>
</div>
</div>
</div>
</form>
The element shows up as it should, and is submitted with the form when the user hits the submit button, but the regex pattern and required attributes are not enforced.
in addHouseMembers(that) the value of that is a string, not a number, and you have to check if is value can be 'translated' in an integer value.
use the "onchange" event on the input field household-size is not a good idea because this event is triggered each time a digit of the number entered, which has the effect of erasing and completely rewrite the family-input-container part
I Imagine you are looking for something like that ?
const myForm = document.getElementById('my-form')
, familyElm = document.getElementById('family-input-container')
, parserDOM = new DOMParser()
;
function newHouseMember(ref)
{
let div=
` <div>
Family Member ${ref}<br>Name: <br>
<input type="text" name="member${ref}_name" pattern="/^[a-zA-Z ]*$/" required >
</div>`
return parserDOM.parseFromString( div, 'text/html').body.firstChild
}
myForm.btPeoples.onclick=_=>
{
let nbPeoples = parseInt(myForm['household-size'].value)
if (!isNaN(nbPeoples) && nbPeoples > 0 )
{
familyElm.innerHTML = ''
for (let i=1; i<=nbPeoples; i++)
{
familyElm.appendChild( newHouseMember(i) )
}
}
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" >
<form id="my-form">
<div class="form-group">
<label class="col-lg-3 control-label">What is the total amount of people living in your household?</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group">
<input class="form-control" name="household-size" required value="" placeholder="number of peoples" pattern="\d*" />
<button name="btPeoples" class="btn btn-info" type="button" >check it!</button>
</div>
</div>
</div>
<div class="form-group", id="family-info">
<label class="col-lg-12">Information for other Family Members</label>
<div class="col-lg-3 inputGroupContainer">
<div class="input-group" id="family-input-container">
</div>
</div>
</div>
</form>
I've got a dropdown box which is populated with ajax according to what option i choose from another dropdown. I need to duplicate the dropdown box keeping the same options loaded via ajax, this is what i've done o far. Many thanks for your help
This is the code to get tha value from the first dropbox and then use it for ajax
$('#flatGroup').on('change',function(){
var countryID = $(this).val();
console.log(countryID);
if(countryID){
$.ajax({
type:'POST',
url:'../controllers/ctrl_admin_group_table_app/ctrl_admin_get_building_table.php',
data: {
group_id: countryID
},
success:function(html){
$('#flatTable-1').html(html);
$(".bs-select").selectpicker('refresh');
}
});
}
});
This is the code i'm using to close the second dropbox that receive the option from ajax
// start repeating form tabelle
//Start repeating form group add limit
var maxGroup1 = 5;
//add more fields group
var fieldGroup1= $(".fieldGroup1").clone();
$(".addMore1").click(function() {
var fgc1 = $('body').find('.fieldGroup1').length;
if (fgc1 < maxGroup1) {
var fieldHTML1 = '<div class="form-group fieldGroup1">' + fieldGroup1.html() + '<div class="col-md-1"><label class="control-label"> </label><i class="fa fa-close"></i></div></div>';
fieldHTML1 = fieldHTML1.replace('flatTable-1', 'flatTable-' + (fgc1 + 1));
fieldHTML1 = fieldHTML1.replace('flatMillesimi-1', 'flatMillesimi-' + (fgc1 + 1));
$('body').find('.fieldGroup1:last').after(fieldHTML1);
$('.bs-select').selectpicker({
iconBase: 'fa',
tickIcon: 'fa-check'
});
} else {
swal("Operazione Annullata", "Hai raggiunto il massimo numero di proprietari registrabili", "error");
}
});
//remove fields group
$("body").on("click", ".remove", function() {
$(this).parents(".fieldGroup1").remove();
});
// end repeating form
This is the HTML code
<div class="row">
<div class="col-md-9">
<div class="portlet-body form">
<div class="col-md-9">
<div class="mt-repeater">
<div data-repeater-list="group-b">
<div data-repeater-item class="row">
<div class="form-group fieldGroup1">
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Tabella</label>
<select class="form-control bs-select" id="flatTable-1" name="flatTable[]" title="Seleziona tabella millesimale"></select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">
<i class="fa fa-info-circle red tooltips" data-placement="top" data-original-title="Quota del titolare dell'immobile" ></i>Millessimi<span class="required"> * </span>
</label>
<input type="text" id="flatMillesimi-1" name="flatMillesimi[]" class="form-control" placeholder="Millessimi dell'immobile" >
</div>
</div>
</div> <!-- Fine field group -->
</div>
</div>
<!-- <hr> -->
<a href="javascript:;" data-repeater-create class="btn btn-info mt-repeater-add addMore1">
<i class="fa fa-plus"></i> Aggiungi tabella</a>
<br>
<br>
</div>
</div>
</div>
</div>
</div>
I'm trying to pass form values, check them and then return the response with jquery, everything gets passed correctly, the image gets uploaded and the path gets added to the database, but instead of returning the message on the same page, it redirects to the addmember.php, doesn't even go through the checks - like the javascript file doesn't even exist and it has been bothering me for quite a while... I've tried searching but I didn't find anything relatable to me since the problem lies in the picture/image...
Uncaught TypeError: Cannot read property 'val' of null
addmember.js and the **form
$(document).ready(function() {
$("#submit").click(function() {
var membershipnumber = $("#membershipnumber").val();
var membername = $("#membername").val();
var membersurname = $("#membersurname").val();
var memberdate = $("#memberdate").val();
var memberphonenumber = $("#memberphonenumber").val();
var memberemail = $("#memberemail").val();
var memberpicture = document.getElementById("#memberpicture").val();
if ((membershipnumber == "") || (membername == "") || (membersurname == "") || (memberdate == "") || (memberphonenumber == "")) {
$("#message").html("<div class=\"alert alert-danger alert-dismissable fade in\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Polja označena sa * ne smeju biti prazna.</div>");
} else {
$.ajax({
type: "POST",
url: "addmember.php",
data: {
"membershipnumber": membershipnumber,
"membername": membername,
"membersurname": membersurname,
"memberdate": memberdate,
"memberphonenumber": memberphonenumber,
"memberemail": memberemail,
"memberpicture": memberpicture
},
success: function(html) {
var text = $(html).text();
var response = text.substr(text.length - 4);
$("#message").html(html);
},
error: function() {
},
beforeSend: function() {
$("#message").html("<p class='text-center'><img src='images/ajax-loader.gif'></p>")
}
});
}
return false;
});
});
<form name="createnewmember" id="createnewmember" method="post" action="addmember.php" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<!-- name and surname -->
<label for="membername" class="col-xs-2 control-label">Ime i prezime:<font color="#d9534f">*</font></label>
<div class="col-xs-10">
<div class="form-inline">
<input name="membername" id="membername" type="text" class="form-control" placeholder="Ime" autofocus />
<input name="membersurname" id="membersurname" type="text" class="form-control" placeholder="Prezime" />
</div>
</div>
</div>
<!-- /name and surname -->
<div class="form-group">
<!-- date of birth -->
<label for="memberdate" class="col-xs-2 control-label">Datum rođenja:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberdate" id="memberdate" type="date" class="form-control" value="1990-01-01" />
</div>
</div>
<!-- /date of birth -->
<div class="form-group">
<!-- membership number (scanned with barcode scanner) -->
<label for="membershipnumber" class="col-xs-2 control-label">Članski broj:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="membershipnumber" id="membershipnumber" type="text" class="form-control" placeholder="Članski broj" data-toggle="tooltip" data-placement="right" title="Očitajte bar-kod sa nekorišćene kartice." />
</div>
</div>
<!-- /membmership number -->
<div class="form-group">
<!-- phone number -->
<label for="memberphonenumber" class="col-xs-2 control-label">Broj telefona:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberphonenumber" id="memberphonenumber" type="text" class="form-control" placeholder="Broj telefona" />
</div>
</div>
<!-- /phone number -->
<div class="form-group">
<!-- email -->
<label for="memberemail" class="col-xs-2 control-label">Email adresa:</label>
<div class="col-xs-3">
<input name="memberemail" id="memberemail" type="text" class="form-control" placeholder="Email adresa" />
<div class="checkbox">
<label><input name="memberemailinglist" id="memberemailinglist" type="checkbox" disabled/> Prijavi na mailing listu?</label>
</div>
</div>
</div>
<!-- /email -->
<div class="form-group">
<!-- picture -->
<label for="memberpicture" class="col-xs-2 control-label">Slika:</label>
<div class="col-xs-10">
<label class="btn btn-default" for="memberpicture">
<input id="memberpicture" name="memberpicture" type="file" style="display:none;" onchange="$('#memberpicture-info').html($(this).val());" accept=".jpg,.png,.jpeg" class="form-control" />
<span class="glyphicon glyphicon-camera"></span> Traži...
</label>
<span class="label label-danger" id="memberpicture-info">Nije izabrana ni jedna slika...</span>
</div>
</div>
<!-- /picture -->
<div class="form-group">
<span class="pull-right">Polja označena sa <font color="#d9534f">*</font> su obavezna!  </span>
<!-- required fields text -->
</div>
<button name="Submit" id="submit" class="btn btn-default pull-right" type="submit">Podnesi</button>
<!-- submit button -->
</form>
<!-- /form -->
addmember.php
<?php
require 'includes/functions.php';
include_once 'config.php';
$membershipnumber = $_POST['membershipnumber'];
$membername = $_POST['membername']." ".$_POST['membersurname'];
$membersurname = $_POST['membersurname'];
$memberdate = $_POST['memberdate'];
$memberphonenumber = $_POST['memberphonenumber'];
$memberemail = $_POST['memberemail'];
$memberpicture_dir = '/images/members';
if(isset($_FILES['memberpicture'])) {
$memberpicture_temp = $_FILES['memberpicture']['tmp_name'];
$ext = pathinfo(basename($_FILES['memberpicture']['name']), PATHINFO_EXTENSION);
$memberpicture = $membershipnumber.".".$ext;
move_uploaded_file($memberpicture_temp , $_SERVER['DOCUMENT_ROOT'] . '/spartangym/images/members/' . $memberpicture);
} else {
$memberpicture = "nopicture.jpg";
}
$regdate = new DateTime();
$memberregdate = $regdate->getTimestamp();
$memberexpires = $memberregdate + 2592000;
if (strlen($memberemail) > 0 && !filter_var($memberemail, FILTER_VALIDATE_EMAIL) == true) {
echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Email adresa nije validna.</div><div id="returnVal" style="display:none;">false</div>';
} else {
$a = new AddMemberForm;
$response = $a->createMember($membershipnumber, $membername, $memberdate, $memberphonenumber, $memberemail, $memberpicture, $memberregdate, $memberexpires);
if ($response == 'true') {
echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Član '. $membername .' je uspešno dodat u bazu.</div><div id="returnVal" style="display:none;">true</div>';
} else {
mySqlErrors($response);
}
};
?>
Your problem is here
var memberpicture = document.getElementById("#memberpicture").val();
Native methods don't have val(), nor should you include the hash.
As val() is a jQuery method, you probably wanted to do
var memberpicture = $("#memberpicture").val();
The native alternative would be
var memberpicture = document.getElementById("memberpicture").value;
Your validation looks fine, but on-click you should use event.preventDefault() to keep the form from submitting and only allow the submission in the event of all fields being valid.
Usage here:
https://api.jquery.com/event.preventdefault/
at first check
before check
var membershipnumber = $("#membershipnumber").val();
after check
var membershipnumber='none object';
if(typeof($('#membershipnumber'))!="undefined")
{
membershipnumber= $('#membershipnumber').val();
}
alert(membershipnumber);
I have the following HTML and JS Code and the problem, that I'm not quite sure how to get the values from the input-boxes with the classes bti, bi, bp and bb when I click on the savebtn Button. I really hope someone can help me and give me a hint! best regards
$(document).ready(function() {
$('.savebtn').click(function() {
//how to i get the values?
});
});
<div class="modal-body">
<?php
for ($i=0; $i<count($barkeeperarr); $i++) {
?>
<div class="panel panel-primary" value="<?php echo $barkeeperarr[$i]->getID(); ?>" >
<div class="panel-heading clickablePanel">
<div class="panel-title"><?php echo $barkeeperarr[$i]->getFirstname().' '.$barkeeperarr[$i]->getLastname(); ?></div>
</div>
<div class="panel-body" style="display: none">
<div class="container-fluid">
<div class="row" value="row" style="margin-bottom: 3px">
<div class="col-xs-5">
<input type="text" class="form-control bti" placeholder="Gesamtumsatz">
</div>
<div class="col-xs-5">
<input type="text" class="form-control bi" placeholder="Einladung">
</div>
<div class="col-xs-2">
<button type="button" class="btn btn-primary btn-sm savebtn">Hinzufügen</button>
</div>
</div>
<div class="row" style="margin-bottom: 3px">
<div class="col-xs-5">
<input type="text" class="form-control bp" placeholder="Personal">
</div>
<div class="col-xs-5">
<input type="text" class="form-control bb" placeholder="Bruch">
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
It will something like this,
$('.savebtn').click(function() {
$.each($('input:text.form-control'), function(){
if ($(this).prop('class') === 'bti'){
alert('form-control bti value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bp'){
alert('form-control bp value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bb'){
alert('form-control bb value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bi'){
alert('form-control bi value = ' + $(this).val()));
});
});
You could store the values in an array and then process that array to add the values to your database.
For instance, let's create an array called values :
var values = [];
Then add an object to that array with the values of the respective classes bti, bi, bp and bb like :
jQuery(document).ready(function ($) {
var formControl = $(".form-control");
$('.savebtn').on("click", function () {
//how to i get the values?
for (var i = 0; i < formControl.length; i++) {
values[i] = {
name: formControl[i].className.split(" ")[1],
val: formControl[i].value
}
}
});
}); // ready
Notice we targeted the selector .form-control, which is a common class to all input fields.