Select only value attribute which have numbers in it - javascript

I have lots of input tags with type text and number respectively. I want to replace all input type text which have values in numbers to the input type number but not getting how to take only numbers in value. I'm using below code to do it.
$( "[value*='']").attr('type','number');

You can try .filter and use isNaN to check whether the value is number or not
$(document).ready(function() {
$("input[type='text']").filter(function() {
return !isNaN( $(this).val() ) && $(this).val().trim() !== "";
}).attr("type", "number");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="Javascript">
<input type="text" value="Apple">
<input type="text" value="1">
<input type="text" value="3">
<input type="text" value="1000">
<input type="text" value="">

Maybe iterating and checking will do it:
for(const el of $("[value*='']").toArray())
if(parseInt(el.value))
$(el).attr('type','number');

Related

Multiplication in jQuery dynamically

I am trying to make a multiplication function in jquery where which helps change the default value-based output.
For example - if I type the input#mainInput value then it will change all the inputs value base own his default value * input#mainInput and if the value == 'NaN' it will do dirent funcion.
Please help me how to I make this function in jQuery.
$(document).on('keyup', 'input#mainInput', function() {
thisParentQtyValueBox = $(this).val();
daughtersBoxValueAttr = $("input.input__bom").attr("inputid");
daughtersBoxValue = $("input#daughterInput_" + daughtersBoxValueAttr).val();
$("input#daughterInput_" + daughtersBoxValueAttr).val(thisParentQtyValueBox * daughtersBoxValue);
if ($("input#daughterInput_" + daughtersBoxValueAttr) == 'Nan') {
$("input#daughterInput_" + daughtersBoxValueAttr).val('3' * daughtersBoxValue)
}
});
//If
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" value="25" /><br/>
If I understand correctly, when the input is not a number, you want to do as if the input was 3.
Some issues in your code:
$("input.input__bom").attr("inputid") is always going to evaluate to 1, as only the first matching element is used. And it is strange to use this attribute value to then retrieve that element again via its id property.
You would need a loop somewhere so to visit each of the "input__bom" elements.
== 'Nan is never going to be true. You should in fact test the main input itself to see if it represents a valid number. For that you can use isNaN.
It is a bad idea to give these elements a unique id attribute. You can use jQuery to visit them each and deal with them. There is no need for such id attribute.
Don't use the keyup event for this, as input can be given in other ways than pressing keys (e.g. dragging text with mouse, or using the context menu to paste). Use the input event instead.
There is no good reason to use event delegation here on $(document). Just bind your listener directly the main input element.
Declare your variables with var (or let, const). It is bad practice to no do that (it makes your variables global).
It seems like the 5 "bom" input elements are not really intended for input, but for output. In that case the placeholder attribute makes no sense, and they should better be marked with the readonly attribute.
$("#mainInput").on('input', function() {
var mainInput = $(this).val();
var multiplier = +mainInput; // convert to number with unary +
// default value in case input is not a valid number, or is empty
if (Number.isNaN(multiplier) || !mainInput) {
multiplier = 3;
}
$('.input__bom').each(function() {
$(this).val( multiplier * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" type="text" readonly data-value="5" value="5"><br/>
<input class="input__bom" type="text" readonly data-value="10" value="10"><br/>
<input class="input__bom" type="text" readonly data-value="15" value="15"><br/>
<input class="input__bom" type="text" readonly data-value="20" value="20"><br/>
<input class="input__bom" type="text" readonly data-value="25" value="25" /><br/>
You have to store the default value in the data attr so then it will not multiple by result value and it will multiple by your default value. for dynamic multiplication, you can use jquery each. check below code.
$(document).on('input', 'input#mainInput', function() {
thisParentQtyValueBox = parseInt( $(this).val() );
if( Number.isNaN( thisParentQtyValueBox ) ){
thisParentQtyValueBox = 3;
}
$('.input__bom').each(function(){
$(this).val( thisParentQtyValueBox * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" data-value ="5" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" data-value ="10" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" data-value ="15" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" data-value ="20" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" data-value ="25" value="25" /><br/>

Input type="text" currency validation

I currently have an input type="text" that I transform into a currency value on the "keyup" event. In order to keep this functionality (works fine), the input type has to be set to "text". At the same time, I would like to have a minimum value of "100.00" set to it.
Any way I can accomplish this? Also, would I able to customize my jquery validation message to say "Minimum Amount $100.00"?
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required id="balance" name="balance" type="text" class="number" />
You can add this property in your input filed: minlength="5"
<input required id="balance" name="balance" type="text" class="number" minlength="5" />
And in your JS code you can add a 'if' statement to check that this input contain at least 5 char.
Furthermore you can add the same 'if' statement in your back-end to check it again.
Thank you all for your input.
I've ended up keeping the input type="text" for the number of digits users can type in and called a function to check the input value against the 100.
function checkAmount() {
var valueBalance = $("#balance").val();
var valueNumberBalance = parseFloat((valueBalance).replace(/[^\d\.]/, ''));
if (valueNumberBalance < 100) {
$("#balance").get(0).setCustomValidity("Minimum Amount of $100.00");
}
else {
$("#balance").get(0).setCustomValidity("");
}
}
A snippet created using the type="number" instead of type="text" on the input still allows the jQuery functionality to work.
The validation message is HTML5 and not jQuery as you did not provide that code. I did the following:
Changed to type="number"
Added min="100"
Added step="0.01" to handle currency stepping
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Text input (original): <input required id="balance" name="balance" class="number" type="text" /><br />
Number input: <input required id="balance" name="balance" class="number" type="number" min="100" max="99999" step="0.01" /><br />
<input type="submit" />
<small>Enter less than 100 and press 'submit' to see validations.</small>
</form>
you can try to currency validation using regex
<div class="col-sm-3 form-group">
<b>Premium :*</b><br>
<p><input type="text" class="form-control" oninput="this.className = ''" name="premium" id="premium" valideAtt="currency" title="Premium" onblur="defaultValidation(this)"></p>
<span id="er_premium" style="display: block; width:100%; float: left;"></span>
</div>
<script type="text/javascript">
var REG_CURRENCY = /(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$/;
function defaultValidation(src){
var getAttributeValue=src.attributes.valideAtt.value;
if(getAttributeValue=="currency"){
if(!src.value.match(REG_CURRENCY)){
$("#"+src.id).addClass("invalid");
$("#er_"+src.id).html("<span style=\"color:red\">Please Enter Valide currency Value.<\span>");
return false;
}else{
$("#er_"+src.id).html("");
return true;
}
}
}
<script>

jquery increment input values

Using Jquery I need to add all values of input.
Using jquery each is there any way to use regix in element name
like
items[regix_goes_here][debit]
I need values of all input and I want them incremented using each.
My code
<input name="items[1][debit]" type="number">
<input name="items[341][debit]" type="number">
<input name="items[31][debit]" type="number">
<input name="items[431][debit]" type="number">
First, assign a class to your inputs, for example:
<input class="js-inc" name="items[1][debit]" type="number">
<input class="js-inc" name="items[341][debit]" type="number">
<input class="js-inc" name="items[31][debit]" type="number">
<input class="js-inc" name="items[431][debit]" type="number">
Now you can increment all of them, without even jquery. Use .value to access the value as a string. Use Number("..") to convert it to a number. Add one to it, and assign it back.
var inputs = document.querySelectorAll("input.js-inc")
inputs.forEach(function(input) {
input.value = Number(input.value) + 1
})
Here's a live example
If you want to sum all the values of inputs with name="items[X][Y]", you can filter them by testing if their name attribute matches this /items\[\d+\]\[debit\]/ Regex.
This is how should be your code:
var sum = 0;
$('input[type="button"]').click(function() {
$('input').each(function() {
if ($(this).attr('name') && $(this).attr('name').match(/items\[\d+\]\[debit\]/)) {
sum += $(this).val() ? parseInt($(this).val()) : 0;
}
});
console.log(sum);
});
Demo:
var sum = 0;
$('input[type="button"]').click(function() {
$('input').each(function() {
if ($(this).attr('name') && $(this).attr('name').match(/items\[\d+\]\[debit\]/)) {
sum += $(this).val() ? parseInt($(this).val()) : 0;
}
});
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="items[1][debit]" type="number" value="2">
<input name="items[341][debit]" type="number" value="2">
<input name="items[31][debit]" type="number" value="2">
<input name="items[431][debit]" type="number" value="2">
<input type="button" value="SUM" />

How to get values of multiple input in one string by ".val()" using jquery?

I want to get the values of all input at once using one .val() function in jQuery.
$("#txt1").val();
$("#txt2").val();
$("#txt3").val();
Instead of this I want to write the below code
$("#txt1, #txt2, #txt3").val();
Use .map() to convert selected input to value of them and then use Array.prototype.join() to convert array result to string.
var values = $("#txt1, #txt2, #txt3").map(function(){
return this.value;
}).get().join(" ");
console.log(values)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt1" value="a" />
<input type="text" id="txt2" value="b" />
<input type="text" id="txt3" value="c" />
var arr= $("input").map(function(){
return $(this).val();
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="1">
<input type="text" value="11">
<input type="text" value="11">
You need to loop through them try using .map()

Read HTML array using javascript or jQuery

I have array element in HTML
<input type="checkbox" value="Value1" name="model[settings][]">
<input type="checkbox" value="Value2" name="model[settings][]">
<input type="checkbox" value="Value3" name="model[settings][]">
I am reading all the HTML input, iterating it and building a hash in the javascript. But this will read the array element and only pick the last model[settings][] element.
var inputs = jQuery(" :input", "#elementID");
Is there a way in jQuery or JavaScript to read and build an array variable in javascript which then can be passed to controller ?
Thank You
If I understand you correctly, you are trying to iterate through all your input elements to get their value and store that as a JS object, correct?
If that's the case, I would add a unique ID to all my inputs, and then create an object with the structure { id : value }:
function getInputObject(sel) {
sel = $(sel);
var out = {};
sel.each(function() {
out[$(this).attr("id")] = $(this).val();
});
return out;
}
$(document).ready(function() {
console.log( getInputObject("input") );
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" value="value input 1" type="text" />
<input id="input2" value="value input 2" type="text" />
<input id="input3" value="value input 3" type="text" />

Categories