Jquery send form POST change value of inputs if collapse = false - javascript

Hi i'm trying to make a validation on my form and change the values that send through form if a collapse element(of that value) = False to a null value (i'm still kinda new to javascript and Jquery).
if (document.getElementById("filter_form")) {
var slider1 = document.getElementById("price_min");
var slider2 = document.getElementById("price_max");
output1.value = slider1.value; // Display the default slider value
output2.value = slider2.value;
output1.oninput = function() {
slider1.value = this.value;
}
output2.oninput = function() {
slider2.value = this.value;
}
// Update the current slider value (each time you drag the slider handle)
slider1.oninput = function() {
output1.value = this.value;
}
slider2.oninput = function() {
output2.value = this.value;
}
}
$(document).ready(function() {
$('#search').click(function(event) {
if ($('#price').attr("aria-expanded") == "true") {
var price_min = Number($('#price_min').val());
var price_max = Number($('#price_max').val());
} else {
var price_min = null;
var price_max = null;
$('#price_min').value = null;
$('#price_max').value = null;
}
if (price_min > price_max) {
event.preventDefault();
iziToast.warning({
title: 'Fail!',
message: 'min price cant be larger than max price',
position: 'bottomRight'
}); //my alert
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/js/iziToast.min.js"></script>
<form method="POST" action="/search_url/'">
<div class="form-group">
<p>
<button id="price" class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample-1" aria-expanded="false" aria-controls="collapseExample-1" style="width: 100%">
Price
</button>
</p>
<div class="collapse" id="collapseExample-1">
<div>Min: <input type="number" id="price_min_value" min="0" max="100000000000" value="0" /></div>
<input type="range" id="price_min" class="form-control" min="0" max="100000000000" value="0" name="price_min">
<div>Max: <input type="number" id="price_max_value" min="0" max="100000000000" value="100000000000" /></div>
<input type="range" id="price_max" class="form-control" min="0" max="100000000000" value="100000000000" name="price_max">
</div>
</div>
<button class="btn btn-primary mr-1" id="search">Search</button>
</form>
On the server when i received the data from POST request with collapse flase, i got price_min = '0' and price_max ='100000000000'
Expected results:
It should be price_min = null and price_max = null
I don't know why it doesn't set the POST data equal NULL, and i don't know why.
EDIT:
ok this is weird when i change my set value code to:
$('#price_min').val("");
$('#price_max').val("");
and send the form post it return server to the value equal to the middle value of the range input(50000000000), but when i tried to do this:
$('#price_min').val("1234");
$('#price_max').val("12345");
and on the server i actually got the changed value of price_min = 1234 and price_max = 12345
why does this work? but when i try to set it value or null or none it doesn't work and just take the middle value of the range input?
I'm so confused
Thank for reading

You are setting value with .value but in jQuery we use .val() and set value as 0 instead of null as number type input does not accept null. Change the logic at server side to check if value is 0 instead of null.
Also, use preventDefault as first line in the search button click so that button will not submit the form directly.
See below code
$(document).ready(function() {
$('#search').click(function(event) {
event.preventDefault(); // it will prevent default behavior of button clicked
console.log('button clicked');
if ($('#price').attr("aria-expanded") == "true") {
var price_min = new Number($('#price_min').val());
var price_max = new Number($('#price_max').val());
} else {
var price_min = 0;
var price_max = 0;
$('#price_min').val(price_min);
$('#price_max').val(price_max);
}
if (price_min > price_max) {
iziToast.warning({
title: 'Fail!',
message: 'min price cant be larger than max price',
position: 'bottomRight'
}); //my alert
} else {
$("#searchForm").submit();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/js/iziToast.min.js"></script>
<form method="POST" action="/search_url/'" id="searchForm">
<div class="form-group">
<p>
<button id="price" class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample-1" aria-expanded="false" aria-controls="collapseExample-1" style="width: 100%">
Price
</button>
</p>
<div class="collapse" id="collapseExample-1">
<div>Min: <input type="number" id="price_min_value" min="0" max="100000000000" value="0" /></div>
<input type="range" id="price_min" class="form-control" min="0" max="100000000000" value="0" name="price_min">
<div>Max: <input type="number" id="price_max_value" min="0" max="100000000000" value="100000000000" /></div>
<input type="range" id="price_max" class="form-control" min="0" max="100000000000" value="100000000000" name="price_max">
</div>
</div>
<button class="btn btn-primary mr-1" id="search">Search</button>
</form>

Related

JQuery function does not respect clicked component

I have a product page where you can make customizations to the product such as adding or removing "ingredients" and for each customization that can be added or removed I create an input with a + and - button to increase or decrease my choice.
I inform via parameter to the javascript function the component (input) that will receive the increment or decrement, the maximum value that can be increased, the minimum value (decrement) and the increment interval.
However, for each possible customization in the product I must present a component like this:
<div class="qty mt-5">
<span class="minus" name="diminuir[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">+</span>
</div>
And this is my java script function that should add or subtract the value and present it in the correct input
<script>
function AumentaDiminui(controle, valorMinimo, valorMaximo, valorIncremento) {
$(document).ready(function () {
$('[name="aumentar[]"]').click(function () {
if ($("[name=" + controle + "]").val() == valorMaximo)
return;
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) + valorIncremento);
});
$('[name="diminuir[]"]').click(function () {
if ($("[name=" + controle + "]").val() <= valorMinimo) {
$("[name=" + controle + "]").val(valorMinimo);
return;
}
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) - valorIncremento);
});
});
}
</script>
It turns out that the value is not incremented by 1 in 1 as I inform via parameter and if I have more than one component on the screen, when clicking on + or - the value of all inputs are changed regardless of the button I click on
A few comments about your code:
If jquery will handle the click events on the <span>, one should not define a onclick event in the span tag.
There is no need to define a function. You can just wait for the ready event and then monitor for clicks on both <span> (using the jquery .click() function).
You can access the values of min and max value defined in the <input> using the jquery .attr() function.
This is a working code:
$(document).ready(function () {
$('.qty .minus, .qty .plus').click(function () {
var input = $(this).parent().find('input[type=number]');
var newVal = +input.val();
var step = +input.attr('step');
if ($(this).hasClass('plus')){
newVal += step;
} else {
newVal -= step;
}
var min = input.attr('min');
var max = input.attr('max');
if (newVal > max) {
newVal = max;
} else if (newVal < min){
newVal = min;
}
input.val(newVal);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Step: 1</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="1" max="5" min="0">
<span class="plus">+</span>
</div>
<p>Step: 2</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="2" max="5" min="0">
<span class="plus">+</span>
</div>
There is a much easier way to do this, with just a few data-* attributes. This will work on any number of div elements with these attributes and a plus and minus button.
$('.qty').on('click','.minus', function(){
var $parent = $(this).parent();
var min = $parent.data('min');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val > min)
$input.val(val - inc);
})
$('.qty').on('click','.plus', function(){
var $parent = $(this).parent();
var max = $parent.data('max');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val < max)
$input.val(val + inc);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="qty mt-5" data-min="0" data-max="5" data-inc="1">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
<div class="qty mt-5" data-min="0" data-max="100" data-inc="5">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
You could also choose to read min, max and step from the input if you prefered with much the same logic.
create an jquery extension
(function($){
$.fn.AumentaDiminui = function(options) {
var settings = $.extend({ control: null, minvalue:1, maxvalue: 5 , action:'+' }, options );
var curval = $(settings .control).val ();
if ('+'==settings.action){
if (curval==settings.maxvalue) return;
curval++;
}
else {
if (curval==settings.minvalue) return;
curval++;
}
$(settings .control).val (curval);
};
}(jQuery));
call so as
$('div.qty.mt-5 span.minus').click(function (){ $.fn.AumentaDiminui({ action:'-', control:'div.qty.mt-5 input.count' }); });
$('div.qty.mt-5 span.plus').click(function (){ $.fn.AumentaDiminui({ action:'+', control:'div.qty.mt-5 input.count' }); });

Javascript for counting the values of text input fields

I am trying to create a hotel booking form with an increment counter which I have already setup. Its got 3 input fields and at the end there is a "group total" text input field. I need to ask if anyone could help me with the JS in order to counter the number of individuals in the total group box for when they incrementally add people in the 3 increment counters?
My code is as follows:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
textbox.value++;
}
function decrease() {
var textBox = document.getElementById("text");
textBox.value--;
}
function increase2() {
var a = 1;
var textbox2 = document.getElementById("text2");
textbox2.value++;
}
function decrease2() {
var textBox2 = document.getElementById("text2");
textBox2.value--;
}
function increase3() {
var a = 1;
var textbox3 = document.getElementById("text3");
textbox3.value++;
}
function decrease3() {
var textBox3 = document.getElementById("text3");
textBox3.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease()">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease2()">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase2()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease3()">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase3()">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="">
</a>
You can simplify your code by adding this to all onclick function calls so we can know which element called the function and with that we can figure out it's parent along with the correct input element to increment. In the end we call the increaseTotal() or decreaseTotal() function to update the group total field.
Note: I'm guessing you don't want to be able to decrease a field beyond 0, so I added that constraint as an if statement in the decrease() function. I also made the totalPersons input field's value to default to 3 because all of the 3 other inputs default to 1.
Run and test:
function increase(el) {
var textbox = el.parentElement.querySelector('input');
textbox.value++;
increaseTotal();
}
function decrease(el) {
var textBox = el.parentElement.querySelector('input');
if(textBox.value > 0) { // <- if value is at least 1
textBox.value--;
decreaseTotal();
}
}
function increaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value++;
}
function decreaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="3">
</a>
You could just increase/decrease the value attribute of the totalpersons element within the increase/decrease methods as well.
For example:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
var totalpersons = document.getElementById("totalPersons");
textbox.value++;
totalpersons.value++;
}
Note that the values of text boxes are always strings in javascript. The parseInt() function will convert them to integers.
https://jsfiddle.net/y473L1bt/2/
function updateTotal() {
var textbox = document.getElementById("text");
var textbox2 = document.getElementById("text2");
var textbox3 = document.getElementById("text3");
var total = document.getElementById("totalPersons");
total.value = parseInt(textbox.value) +
parseInt(textbox2.value) + parseInt(textbox3.value);
}
function increase(id) {
var textbox = document.getElementById(id);
textbox.value++;
updateTotal();
}
function decrease(id) {
var textBox = document.getElementById(id);
var a = textBox.value - 1;
if (a >= 0) {
textBox.value = a;
}
updateTotal();
}

JQuery returns NaN value while calculating multiple inputs in a row

I have a multiple input rows and all rows have a total column at the end. Now, I want to put the total result of each rows in column Total. I tried but it returns NaN value instead of total result. Attached is my view & script please help what I am missing??? Thanks
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('.dosiaPlace').find('input').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('.dosiaPlace').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dosiaPlace">
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
</div>
Result:
The container, the .dosiaPlace, I presume, has 3 inputs: the .bgpending, the .registered, and the .total-row. Your el.closest('.dosiaPlace').find('input') finds all 3 of those, including the .total-row. But the .total-row is empty (initially), so
totalRow = totalRow + parseInt($(this).val());
for it results in
totalRow = totalRow + parseInt('');
And the empty string can't be parseInt'd (results in NaN). (You also probably don't want to be including the .total-row anyway)
Use input:not(.total-row') instead of input:
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('body').find('input:not(.total-row)').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('body').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
Your variable get null value or NaN just asign o if it is nan or empty
if(totalRow=='' || totalRow ==NaN )
{
totalRow=0;
}

How to send into modal 4 different values for input radio with javascript

I have a sales script and my client need a modal with 4 prices per product within in a input radio. I have tried in several ways, but I can not understand how to send the 4 prices to a radio input within modal for each line of product.
Every line of product is added by javascript, like this:
var addNewRow = function(id){
html = '<tr id="tr_'+i+'">';
html += '<td class="prod_c" width="50%"><input type="text" data-type="nombreProd" name="nombreProd[]" id="nombreProd_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td width="10%"><input type="text" name="cantidad[]" id="cantidad_'+i+'" class="form-control changesNo cq totalCantidad" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td width="10%"><input type="text" name="venta[]" id="venta_'+i+'" class="form-control changesNo vventa" data-toggle="modal" data-target="#escoger" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" readonly="readonly"></td>';
html += '<td width="25%"><input type="text" name="total[]" id="total_'+i+'" class="form-control totalLinePrice pisto" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" ></td>';
html += '<td class="trash_td"><i class="fa fa-trash fa-delete" aria-hidden="true" data-id="'+i+'"></i></td>';
html += '</tr>';
if( typeof id !== "undefined"){
$('#tr_'+id).after(html);
}else{
$('table').append(html);
}
$('#caseNo_'+i).focus();
i++;
return (i-1);
};
Here is the part where the javascript call the DB to add in every input the data from the product selected:
$(document).on('focus','.autocomplete_txt',function(){
type = $(this).data('type');
id_arr = $(this).attr('id');
id = id_arr.split("_");
element_id = id[id.length-1];
autoTypeNo =1;
if(type =='cod' ){
autoTypeNo=0;
$('#add_icon_'+element_id).removeClass('hide');
} else if(type =='nombreProd' ) {
autoTypeNo=1;
}
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'partes/include/aPos.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
beforeSend: function(){
$('#msg').html('<img src="images/ajax-loader.gif"/> <span class="label label-primary">verificando</span>');
},
success: function( data ) {
$('#msgCod').html("");
if(!data.length && readonly != 'readonly'){
$('#product_code_modal').val( $('#itemNo_'+element_id).val() );
$('#product_name_modal').val( $('#itemName_'+element_id).val());
$('#current_element_id').val(element_id);
//$('#add_product_form').find('.form-group').removeClass('animated fadeIn').addClass('animated fadeIn');
//$('#addNewProduct').modal('show');
/*var result = [
{
label: 'No record found',
value: ''
}
];
response(result);*/
}else{
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[autoTypeNo],
value: code[autoTypeNo],
data : item
};
}));
}
}
});
},
autoFocus: true,
selectFirst: true,
minLength: 2,
open: function(e, ui){
var first = $(".ui-menu-item:eq(0) div").html();
//$(this).val(first);
console.log(first);
return false;
},
select: function( event, ui ) {
if( typeof ui.item.data !== "undefined" ){
var names = ui.item.data.split("|");
if( type == 'general'){
var currentTextid = $('#reciboPos tr:last').find("td.prod_c > input").attr('id');
if(typeof currentTextid !== 'undefined') {
var currentTextArr = currentTextid.split("_");
element_id = currentTextArr[currentTextArr.length-1];
var cod = $.trim( $("#"+currentTextid).val() );
element_id = parseInt(element_id);
if (cod !=='') {
element_id = addNewRow();
}
} else {
element_id = addNewRow();
}
}
$('#nombreProd_'+element_id).val(names[1]);
$('#cantidad_'+element_id).val(1);
$('#venta_'+element_id).val(names[2]);
$('#total_'+element_id).val(names[2]);
// Here I added thee others three values for each product
$('#venta1_'+element_id).val(names[3]);
$('#venta2_'+element_id).val(names[4]);
$('#venta3_'+element_id).val(names[5]);
setTimeout(function(){
$("#autocomplete_top").val("");
},100);
}else{
return false;
}
calculateTotal();
}
});
});
When the product is showed I clicked into the input "venta" to show the modal
//modal to choose the price
$('#escoger').on('show.bs.modal', function(e) {
var venta = $('#venta_0'+id[1]).val();
var venta1 = $('#venta_1'+id[1]).val();
var venta2 = $('#venta_2'+id[1]).val();
var venta3 = $('#venta_3'+id[1]).val();
$('input[name="venta"][value="'+venta+'"]').prop('checked',true);
$('input[name="venta"][value="'+venta1+'"]').prop('checked',false);
$('input[name="venta"][value="'+venta2+'"]').prop('checked',false);
$('input[name="venta"][value="'+venta3+'"]').prop('checked',false);
});
This is the modal, but I don't know how to send the data into each input radio:
<div id="escoger" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_0">1
</label>
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_1">2
</label>
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_2">3
</label>
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_3">4
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
-----EDIT------
Here the video link with the issue:
video
Here the another part of script:
//price change
$(document).on('change keyup blur','.changesNo',function(){
// .changeNo are the class inside of ventas, cantidad(quantity) inputs
// in this part the ID came from
id_arr = $(this).attr('id');
id = id_arr.split("_");
cantidad = $('#cantidad_'+id[1]).val();
existencia = $('#existencia_'+id[1]).val();
venta = $('#venta_'+id[1]).val();
venta1 = $('#venta1_'+id[1]).val();
venta2 = $('#venta2_'+id[1]).val();
venta3 = $('#venta3_'+id[1]).val();
if( cantidad!='' && venta!='')
calculateTotal();
});
Maybe this is what are you looking for. Do something like below.
JAVASCRIPT
$('#escoger').on('shown.bs.modal', function () {
var venta0 = Math.floor((Math.random() * 100)); // Test value (random). Change it back according to your code later.
var venta1 = Math.floor((Math.random() * 100)); // Test value (random). Change it back according to your code later.
var venta2 = Math.floor((Math.random() * 100)); // Test value (random). Change it back according to your code later.
var venta3 = Math.floor((Math.random() * 100)); // Test value (random). Change it back according to your code later.
var vt0 = $('input[name="venta"]:eq(0)',this); // Set target input with their own index (eq).
var vt1 = $('input[name="venta"]:eq(1)',this); // Set target input with their own index (eq).
var vt2 = $('input[name="venta"]:eq(2)',this); // Set target input with their own index (eq).
var vt3 = $('input[name="venta"]:eq(3)',this); // Set target input with their own index (eq).
vt0.val(venta0).prop('checked',true) // Set the value
.closest("label").html(function(){ // Customize/Set again the html in label. Because this input inside the label and its text value
return [$("input",this),$("input",this).val()]; // Return the input in this label with its text value back into html
});
vt1.val(venta1) // Set the value
.closest("label").html(function(){ // Customize/Set again the html in label. Because this input inside the label and its text value
return [$("input",this),$("input",this).val()]; // Return the input in this label with its text value back into html
});
vt2.val(venta2) // Set the value
.closest("label").html(function(){ // Customize/Set again the html in label. Because this input inside the label and its text value
return [$("input",this),$("input",this).val()]; // Return the input in this label with its text value back into html
});
vt3.val(venta3) // Set the value
.closest("label").html(function(){ // Customize/Set again the html in label. Because this input inside the label and its text value
return [$("input",this),$("input",this).val()]; // Return the input in this label with its text value back into html
});
});
JSFiddle example : http://jsfiddle.net/synz/72pasuzw/
Forgive me if I'm misunderstanding, but it looks like the problem is simply that you haven't added a value attribute to each of your radio buttons. I've added some samples here; you can run it and see if this is what you're missing.
$('input').on('click', function(e) {
alert($('#'+ e.target.id).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="escoger" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_0" value="venta_0 value">1
</label>
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_1" value="venta_1 value">2
</label>
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_2" value="venta_2 value">3
</label>
<label class="radio-inline mr10">
<input type="radio" name="venta" id="venta_3" value="venta_3 value">4
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

on keyup validation is working but on keypress its not working

Input box requires following validations:
1) Length input box should take upto 3 integer length values (decimals not allowed)
2) Height input box should take 3 integer number and decimals upto 2 places Its working fine for the first time, but after clicking + button(near of Open New Row 1) same input fields are opening but now: In the new boxes validations are not working even if I use the same classes for input boxes, i.e, newly added input boxes are taking any number of digits and characters.
In keyup function it is working,but if user presses any key it doesn't work for newly opened row, so how to make its working on keypress also in both the cases; on keyup validation is working but on keypress its not working
var app = angular.module('Calc', []);
var inputQuantity = [];
$(function() {
$(".form-control").each(function(i) {
inputQuantity[i]=this.defaultValue;
$(this).data("idx",i); // save this field's index to access later
});
$(".form-control").on("keyup", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10); // retrieve the index
// window.console && console.log($field.is(":invalid"));
// $field.is(":invalid") is for Safari, it must be the last to not error in IE8
if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});
app.controller('Calc_Ctrl', function ($scope, $http) {
$scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
$scope.areas = [{id : 'choice2', total : 0}];
$scope.addNewChoice = function () {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
});
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if (lastItem !== 0) {
$scope.choices.splice(lastItem);
}
};
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="newscript.js"></script>
<body>
<div ng-app="Calc" ng-controller="Calc_Ctrl">
<div data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
<h6>Open New Row {{$index + 1}}
<button type="button" class="btn btn-default pull-right btn-right-gap btn-red" aria-label="Left Align" ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</h6>
<div class="row walls top-gap">
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="length">Length :</label>
<input type="number" class="form-control text-red bold" id="length" ng-model="choice.l2" min="0" max="999" maxlength="6" step="0.00">
</div>
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="height">Height :</label>
<input type="number" class="form-control text-red bold" id="height" ng-model="choice.b2" min="0" max="999" maxlength="6" step="0.01">
</div>
<button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align" ng-click="removeChoice()" id="minus_icon">
</button>
</div>
</div>
</div>
</body>
</html>
To fire keyup event for all fields we need to change the listener's definition slightly,the selector .form-control should be defined inside the on() as a child selector & document as main selector:
$(document).on("keyup",".form-control", function (e) {
// listener code
});
keypress event behaves differently than keyup event. keypress is fired for each key pressed & just before the value is set in the field.Whereas keyup event is fired for each key released & just after the value is set in the field.So the same approach will not work for keypress.
var app = angular.module('Calc', []);
var inputQuantity = [];
$(function() {
$(".form-control").each(function (i) {
inputQuantity[i] = this.defaultValue;
$(this).data("idx", i); // save this field's index to access later
});
$(document).on("keypress", ".form-control", function (e) {
if (e.charCode!=0){
var $field = $(this),
val = this.value + '' + String.fromCharCode(e.charCode), pattern;
if (this.step == 0.00)
pattern = /[^0-9]/
else
pattern = /[^0-9.]/
if (val > parseInt(this.max, 10) || pattern.test(val) || (val.match(/\./) && (val.match(/\./g).length > 1 || val.replace(/\d+\./, '').length > 2))) {
e.preventDefault();
}
}
});
$(document).on("keyup",".form-control", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10);
if (parseInt(val,10) > parseInt(this.max, 10) ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});
app.controller('Calc_Ctrl', function ($scope, $http) {
$scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
$scope.areas = [{id : 'choice2', total : 0}];
$scope.addNewChoice = function () {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
});
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if (lastItem !== 0) {
$scope.choices.splice(lastItem);
}
};
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="newscript.js"></script>
<body>
<div ng-app="Calc" ng-controller="Calc_Ctrl">
<div data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
<h6>Open New Row {{$index + 1}}
<button type="button" class="btn btn-default pull-right btn-right-gap btn-red" aria-label="Left Align" ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</h6>
<div class="row walls top-gap">
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="length">Length :</label>
<input type="text" class="form-control text-red bold" id="length" ng-model="choice.l2" min="0" max="999" maxlength="6" step="0.00">
</div>
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="height">Height :</label>
<input type="text" class="form-control text-red bold" id="height" ng-model="choice.b2" min="0" max="999" maxlength="6" step="0.01">
</div>
<button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align" ng-click="removeChoice()" id="minus_icon">
</button>
</div>
</div>
</div>
</body>
</html>

Categories

Resources