Sagar Kodte
Sagar Kodte

Reputation: 3815

Select only value attribute which have numbers in it

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');

Upvotes: 0

Views: 91

Answers (2)

Eddie
Eddie

Reputation: 26844

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="">

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138267

Maybe iterating and checking will do it:

for(const el of $("[value*='']").toArray())
  if(parseInt(el.value))
    $(el).attr('type','number');

Upvotes: 0

Related Questions