Insert Parentheses between an acronym in the input field

Asked

Viewed 124 times

2

Good afternoon guys, I’m having a little trouble inserting parentheses between acronyms of a field that I created. Follow my code:

function maiusculo(){
    var quadro = document.getElementById("quadro").value;
    quadro = quadro.toUpperCase();
    quadrocorrige= "("+ quadro +")";
    document.getElementById("quadro").value = quadrocorrige;
}

The user can enter the Parentheses, but can only exit only one pair, that is, if the user type the acronym RJ, the input corrects to (RJ)! But if the user types (RJ), javascript is putting ((RJ)).

I need the acronyms to be capitalized and between parentheses.

  • I didn’t understand your problem. You want this to be like a mask, or rather, run every time the user presses a key?

  • @Weslleycxsardinha, like a mask

  • You are using Jquery?

  • No @Weslleycxsardinha

4 answers

0

For a function to be executed at each key typed, we use the event oninput:

document.getElementById("quadro").oninput = function(){

    var value = this.value;

    var arr = value.split(' ');

    if(arr[0] && arr.length > 1){
        arr[0] = '(' + arr[0].replace(/\(|\)/g, '').toUpperCase() + ')';
    }

    this.value = arr.join(' ');

}

0

I made some adjustments here, and it worked if the user enters the parentheses the function does not insert more. see if anything helps you post a comment that helps you.

function maiusculo(){
    var quadro = document.getElementById("quadro");
    quadro = quadro.value.toUpperCase();
    
    if(quadro.charAt(0) !== "(" && quadro.charAt(quadro.length -1) !== ")" ){
        quadro = "(" + quadro +")";
    }
    
    
    var quadro = document.getElementById("quadro").value = quadro
    document.getElementById("a").innerHTML = quadro;
    
}
    
<input id="quadro">
<button onclick="maiusculo()">ver valor</button>
<h1 id="a"></h1>

0

Just another way that can be done:

var quadro = document.getElementById("quadro");

function maiusculo() {
  var valor = quadro.value;
  quadrocorrige = "(" + valor + ")";
  document.getElementById("quadro").value = quadrocorrige.toUpperCase();
}

quadro.onkeyup = function() {
  var valor = quadro.value;
  var rgex = /[(|)]/;  // regex que impede o uso dos () pelo usuário
  
  if(valor.length == 2) {
    maiusculo();
  } else if(valor.length == 3 ) {
    quadro.value = ''
  } else if(valor.match(rgex)) {
    quadro.value = '';
  }
}
<input id="quadro">

-1

Tries to put a replace to remove the ( )

function maiusculo(){
    var quadro = document.getElementById("quadro").value;
    quadro = quadro.toUpperCase();
    quadrocorrige= "("+ quadro.replace("(", "").replace(")", "") +")";
    document.getElementById("quadro").value = quadrocorrige;
}
<input id="quadro">
<button onclick="maiusculo()">ver valor</button>

Browser other questions tagged

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