0

I have an element:

<input type="number">

When I type in $500, it fails validation, so

console.log("el.value");
//returns ""

This is expected.

Here's the question: How can I check that there is content?

I'm trying to show/hide placeholder text (no, I can't use the native stuff). It needs to be type="number" because I need to force the mobile number keyboard.

Any thoughts?

Update:
From the responses below I can see that I wasn't clear enough in my question.

1) I need to use JavaScript to tell me whether there is content in the input. (I don't need to extract it, I just need to see whether there is content).

This is tricky, because invalid content (like putting words in a number input field) means the value="" even if there is content typed in.

This is the exact problem I need to solve.

inputEl.validity.valid might work but I can't find any docs on how well it is supported across browsers.

Jamis Charles
  • 5,827
  • 8
  • 32
  • 42

5 Answers5

0

Check if you can do something with that :

html

<input id="my-input" type="number">

js

$(document).ready(function(){
    $('#my-input').on('input', function(){
        console.log($(this).val());
    });
});
Oliboy50
  • 2,661
  • 3
  • 27
  • 36
0

At mobile device specially Samsung append value in field do not throw key press event, you can validate the field with onChange="check(this)"

Muhammad Ali
  • 1,992
  • 1
  • 13
  • 20
0
if (variablename==""){
    //no content
}

or

if (variablename.length==0){
    //no content
}
reinhard
  • 13
  • 4
0

If the only reason you need to force the input type to be a number is for the number-pad, why don't you instead make type="text" and pattern="\d*"? This way you can handle and check the input any way you'd like, but still, force the number-pad to show.

<input type="text" pattern="\d*">

Joey N
  • 328
  • 1
  • 2
  • 7
0

This was the one that actually answered it:

How to get the raw value an <input type="number"> field?

Basically you can check input.validity.valid or input.validity.badInput.

Not supported in IE but good support elsewhere.

More details on it here: https://developer.mozilla.org/en-US/docs/Web/API/ValidityState

Community
  • 1
  • 1
Jamis Charles
  • 5,827
  • 8
  • 32
  • 42