Input value jQuery check length and value? - javascript

I'm still stuck here when validating the value of the input. If the value is between 0.4 and 0.9 the input n2 will remove the read-only. On another hand where if value less than 0.4 or more than 0.9 it will show up modal dialog. My question here is to validate the value/length if the value key in by the user is not in decimal value? let say user insert value 1, then my jquery
won't firing out because my length is >=3.. if I put the length check > 1, then when user key the decimal value for example 0.5, the modal dialog
will pop out 3 times.. since my length value is >= 3.. if I remove the length checking, it will keep pop out the modal dialog whenever user key in value length that more than one.
My question is how to control such a situation if the valid range value is between 0.4 to 0.9, at the same time can checking value that not in decimal number as well? Is it possible?
<input type="text" class="form-control input-sm da" name="da" id="da" value="" autocomplete="off" />
<div class="form-group actionDiv" style="display:none">
<label for="cdaaction">Action </label>
<input type="text" class="form-control input-sm cdaaction" name="cdaaction" id="cdaaction" value="" />
</div>
<input type="text" class="form-control input-sm n2" name="n2" id="n2" value="" autocomplete="off" readonly />
$(document).ready(function() {
$(".da").keyup(function() {
var dInput = $(this).val();
if ($('.da').val().length >= 3)
{
if(dInput < 0.4 || dInput > 0.9)
{
var mymodal = $('#mi-modal');
mymodal.find('.modal-body').html('Is the value correct: '+ $('.da').val() +' ?');
mymodal.find('.modal-footer').html('<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button><button type="button" class="btn btn-primary" id="modal-btn-no">No</button>');
$("#mi-modal").modal('show');
$("#modal-btn-si").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').show();
});
$("#modal-btn-no").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').hide();
$("#da").focus();
});
$(".n2").attr('readonly', true);
}
else
{
$(".n2").removeAttr("readonly");
$('.actionDiv').hide();
}
}
});
});

Use parseFloat()
$(document).ready(function() {
$(".da").keyup(function() {
//var dInput = $(this).val();
var val = parseFloat($(this).val());
if (!isNaN(val) && (val < 0.4 || val > 0.9))
//if(dInput < 0.4 || dInput > 0.9)
{
var mymodal = $('#mi-modal');
mymodal.find('.modal-body').html('Is the value correct: '+ $('.da').val() +' ?');
mymodal.find('.modal-footer').html('<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button><button type="button" class="btn btn-primary" id="modal-btn-no">No</button>');
$("#mi-modal").modal('show');
$("#modal-btn-si").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').show();
});
$("#modal-btn-no").on("click", function(){
$("#mi-modal").modal('hide');
$('.actionDiv').hide();
$("#da").focus();
});
$(".n2").attr('readonly', true);
}
else
{
$(".n2").removeAttr("readonly");
$('.actionDiv').hide();
}
}
});
});

You could consider triggering your code on blur(). When the user focusses out of the input box, you can check whether the inputted value is correct or not.
Furthermore, what Carsten said is true: Use type=number for your input and you won't need the check on the input length, just on the value.

Related

Checkbox doesn't store the value

I am trying to create a dynamic Question List along with its dynamic options. With each option I maintain a flag using checkbox. If the checkbox is clicked the AnalysisFlag value should be true and if not then it should be false. However using the below mentioned method, I am always getting the false value whether I clicked the checkbox or not.
Can someone please take a look and suggest me how I can maintain the AnalysisFlag value along with its equivalent option?
function GetDynamicTextBox(value) {
var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("class", "form-control").attr("placeholder","Your Answer");
textBox.val(value);
debugger;
**var allVals = [];
$('[name="DynamicAnalysisFlag"]:checked').each(function () {
allVals.push($(this).val());
});**
return textBox, allVals;
}
var j = 66;
var x = 2;
var option = 'option' + x;
function AddTextBox() {
for (var i = j; i <= j; i++) {
$('#TextBoxContainer' + x).after("<br id='Removebr" + (x + 1) + "'><div class='input-group' id='TextBoxContainer" + (x + 1) + "'><div class= 'input-group-prepend'><div class='input-group-text'> " + String.fromCharCode(i) + " **<input type='checkbox' id='DynamicAnalysisFlag' value= 'true' name='DynamicAnalysisFlag' class='checklistitem''></div>**</div><input autocomplete='off' class='form-control test-option test-option" + x + " text-box single-line' data-val='true' data-val-required='Answer is required' id=" + option + " name='DynamicTextBox' placeholder='Your Answer' type='text' value=''><span class='field-validation-valid text-danger' data-valmsg-for='AnalysisFlag' data-valmsg-replace='true'></span></div>");
}
j++;
x++;
}
function RemoveTextBox() {
if (x != 2) {
$('#TextBoxContainer' + x).remove();
$('#Removebr' + x).remove();
--x;
--j;
}
}
$('#btnNext').on('click', function() {
var radioValue1 = $("input[name='AnalysisFlag']:checked").val();
var txtVal = $('.test-option' + radioValue1).val();
$('#hiddenRadioValue').val(txtVal);
});
$(function() {
var values = eval('#Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function() {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});
<div id="radio" class="col-xs-12">
<br id="Removebr2">
<div class="input-group" id="TextBoxContainer2">
<div class="input-group-prepend">
<div class="input-group-text">
A
<input type="checkbox" id="radio1" value="1" name="AnalysisFlag" onselect="alert('clicke')">
</div>
</div>
<input autocomplete="off" class="form-control test-option test-option1 text-box single-line" data-val="true" data-val-required="Option is required" id="opt1" name="opt1" placeholder="Your Answer" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="opt1" data-valmsg-replace="true"></span>
<input data-val="true" data-val-required="The AnalysisFlag field is required." id="hiddenRadioValue" name="AnalysisFlag" type="hidden" value="">
<br>
</div>
</div>
<div class="card-footer">
<input type="submit" id="btnNext" value="Next ยป" class="btn btn-primary vigor-btn">
</div>
<button type="button" id="btnRemove" class="btn btn-primary vigor-btn" onclick="RemoveTextBox()">Remove Options</button>
<button type="button" id="btnAdd" class="btn btn-primary vigor-btn" onclick="AddTextBox()">Add Options</button>
I have edited the GetDynamicTextBox() function in which I am getting the DynamicAnalysisFlag value which I add at the time of adding another textbox in AddTextBox() function. But now the issue is, if I tick the checkbox I am getting the true value but if I don't tick the checkbox I am getting nothing. So, what changes should I do in this code so if I check the code, I get true and if not then I get false.

Prevent submit form when using jQuery to change input number field [duplicate]

This question already has answers here:
How to prevent buttons from submitting forms
(20 answers)
Closed 1 year ago.
We use the following code to change the input number value, using button up and down.
But when we clicking the increase or decrease button, it also submits the form.
How can we prevent it from submitting the form?
HTML:
<form action="url" method="post" id="product_addtocart_form" novalidate="novalidate">
<div class="field qty">
<div class="control quantity">
<input type="number"
name="qty"
id="qty"
min="1"
size="number"
value="<?= $block->getProductDefaultQty() * 1 ?>"
title="<?= $block->escapeHtmlAttr(__('Qty')) ?>"
class="input-text qty"
data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
/>
<div class="quantity-nav"><button class="quantity-button quantity-up"><i class="far fa-angle-up"></i></button><button class="quantity-button quantity-down"><i class="far fa-angle-down"></i></button></div>
</div>
</div>
</form>
jQuery:
<script>
require(['jquery'], function ($) {
$('.quantity').each(function() {
var spinner = $(this),
input = spinner.find('#qty'),
btnUp = spinner.find('.quantity-up'),
btnDown = spinner.find('.quantity-down'),
min = input.attr('min'),
max = input.attr('max');
btnUp.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue >= max) {
var newVal = oldValue;
} else {
var newVal = oldValue + 1;
}
spinner.find("#qty").val(newVal);
});
btnDown.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue <= min) {
var newVal = oldValue;
} else {
var newVal = oldValue - 1;
}
spinner.find("#qty").val(newVal);
});
});
});
</script>
Just use the type attribute within button tag.<button type="button" class="quantity-button quantity-up">
change button type from adding type="button" , your code will work fine

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

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>

jQuery increment or decrement variable by 1

I have simple plus and minus button on either side of input field as in the code below
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%" onclick="subst()" />
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="<?php echo set_value('noOfRoom'); ?>" name="noOfRoom" />
<input type="button" value="+" id="adds" onclick="add()" class="btn btn-default" />
with aim to add or subtract rooms while adding rooms and the jquery functions as
function add() {
var a = $("#noOfRoom").val();
a++;
if (a => 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
but the following problems are shown
when i click on subtract (-) button at the initial phase -1 is shown in input box, where by default the subtract (-) button should be disabled to make rooms number negative.
Each time when I click on PLUS or MINUS buttons the numbers are added or subtracted by 2. How could I solve it?
Update add a fiddle https://fiddle.jshell.net/n7ug52dr/
Each time you click will only add and sub by 1, and it never show the -1
You can edit code like this:
function add() {
var a = $("#noOfRoom").val();
a++;
if (a && a >= 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
// this is wrong part
if (b && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
Moving comments to answer as no-one took onboard the suggestions:
I suggest not using inline onclick= handlers with jQuery. They separate the event handler from the event code for no reason and don't allow for the extra features of jQuery event handlers.
Use prop and not attr for DOM element properties (like disabled). This has the extra advantage of taking a boolean value.
You can then simply use !a to control the disabled state (as you are only checking for 0).
As a good habit always select DOM elements once and save the selector.
e.g.
$('#adds').click(function add() {
var $rooms = $("#noOfRoom");
var a = $rooms.val();
a++;
$("#subs").prop("disabled", !a);
$rooms.val(a);
});
// Set initial disabled state
$("#subs").prop("disabled", !$("#noOfRoom").val());
$('#subs').click(function subst() {
var $rooms = $("#noOfRoom");
var b = $rooms.val();
if (b >= 1) {
b--;
$rooms.val(b);
}
else {
$("#subs").prop("disabled", true);
}
});
JSFiddle: https://jsfiddle.net/k7nyv84b/4/
Here you go, champ! Made your code a little cleaner as well
See the working example below
$(function(){
$('#adds').on('click',add);
$('#subs').on('click',remove);
});
function add(){
var input = $('#noOfRoom'),
value = input.val();
input.val(++value);
if(value > 0){
$('#subs').removeAttr('disabled');
}
}
function remove(){
var input = $('#noOfRoom'),
value = input.val();
if(value > 0){
input.val(--value);
}else{
$('#subs').attr('disabled','disabled');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%"/>
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="0" name="noOfRoom" />
<input type="button" value="+" id="adds" class="btn btn-default" />
take a look at this solution
<input type="button" value="-" id="subs" onclick="subst()" disabled>
<input type="text" id="noOfRoom">
<input type="button" value="+" id="adds" onclick="add()">
function add() {
var a = $("#noOfRoom").val();
a++;
if (a >= 1) {
$("#subs").removeAttr("disabled");
}
alert(a);
$("#noOfRoom").val(a);
}
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
alert(b);
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
//alert('works well');
}
The simplest way is to use DOM to navigate through elements and get its current value and then increase/decrease them.
I extended the code to make sure when minus button is clicked value isn't reduce below zero.
<input type="button" value="-" class="qtyminus" field="quantity">
<input type="number" class="input-lg" id="quantity" name="quantity" value="1" min="1" style="padding:0px;height:30px;">
<input type="button" value="+" class="qtyplus" field="quantity">
<input type="submit" name="add" id="add" class="btn btn-large btn-border btn-dark" value="GET IT NOW" style="opacity: 1;">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
<button onClick="myfun()">+</button>
<!--<button onClick="myfun()" id="pluse">+</button>-->
<input type="text" id="pluse" >
<button onClick="myfun1()">_</button>
var a = 0;
function myfun(){
a++;
document.getElementById('pluse').value = a;
//document.getElementById('pluse').innerHTML = a;
}
function myfun1(){
a--;
document.getElementById('pluse').value = a;
}

Dynamic form validation and disable submit button

My form is loaded with different input fields like radio button , text field ,numeric field which are generated dynamically while iterating through a list.
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="number" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" id ="reason<c:out value='[${status.index}]'/>" value="" maxlength="255" >
<br><br>
<input type="submit" value="submit" id="submit" />
</c:forEach>
The numeric fields will be validated against minimum and maximum values.if any of the numeric fields fails in the validation , submit button needs to be disabled .
JSFIDDLE
Any ways to achieve this using jquery or javascript?
Thanks for your valuable time and suggestions
Give IDs to your inputs and then use jQuery's .change() function.
Example:
HTML
<input id="test" type="number"/>
<input id="test2" type="number"/>
<input id="submit" type="submit" value="Submit"/>
JS
var testVal = $('#test'),
testVal2 = $('#test2'),
submit = $('#submit'),
minVal = 22,
maxVal = 33;
testVal.change(function() {
if((testVal.val() > maxVal || testVal.val() < minVal) ||
(testVal2.val() > maxVal || testVal.val() < minVal)) {
submit.prop('disabled', true);
} else {
submit.prop('disabled', false);
}
});
jsfiddle
So, you could do something like below.
var flag = true;
if (nameVal > maxVal) {
alert(id + ' Enter the reason before proceeding');
//var reason = nameList[index].Reason;
document.getElementbyId("reason" + index).focus();
flag = false;
}
if (itemVal < minVal) {
alert(id + ' Enter the reason before proceeding');
//var reason = nameList[index].Reason;
document.getElementbyId("reason" + index).focus();
flag = false;
}
document.getElementById("submit").disabled = !flag;
return flag;

Categories

Resources