jQuery - How to get the first character of an input?

Asked

Viewed 575 times

-1

I have an input that I want to create custom validations, I need to take its value and validate the first character of the input, what would be the best way to do this?

  • 6

    var primeiro = input.value[0];

2 answers

5


Take the input value and use the charAt function with the character position in case 0.

var valor = $('#id_input').val();
alert(valor.charAt(0));

4

Version without jQuery.

Because it’s not necessary jQuery for that.

const input = document.getElementById('input1');
const primeiro = input.value[0];
console.log(primeiro);
<input id="input1" type="text" value="um monte de texto" />

  • 2

    Depends, the issue in this is not even the jQuery, but rather the use of charAt or [...], that is to say in general "is not using jQuery", if one already uses jQuery for other things I see no harm in $(...).val();, then just take the test console.log("foo"[0]);. Do you agree that in none of the answers was in fact jQuery who did something?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.