1

I have a textbox with "text-transform: capitalize;" and it works fine, but when I try to get it's value it's not transformed. For example I write in "test" and it shows "Test" in the textbox, but when I do "console.log("document.getElementById("search").value")" it displays "test".
How can I fix this?

Here is my code :

HTML:

<input type="text" id="search"/>
<button type="submit" onclick="query()">Submit</button>
<div class="query-div"><p class="query-p">Test-a</p></div>
<div class="query-div"><p class="query-p">Test-b</p></div>
<div class="query-div"><p class="query-p">Test-ba</p></div>

Javascript:

function query() {
var x = document.querySelectorAll(".query-p");
var y = document.getElementById("search");
var i;
        for(i = 0; i < x.length; i++) {
        if(x[i].innerHTML.includes(y.value)) {x[i].style.display = 'block';} else {x[i].style.display = 'none';}
             console.log(x[i].innerHTML);
    }
}
beannshie
  • 89
  • 1
  • 1
  • 12

1 Answers1

1

You could use string.toUpperCase() on the first char.

function query() {
  var x = document.querySelectorAll(".query-p");
  var y = document.getElementById("search");
  var i;
  for(i = 0; i < x.length; i++) {
    if(x[i].innerHTML.includes(y.value)) {
      x[i].style.display = 'block';
    } else {
      x[i].style.display = 'none';
    }
    var text = x[i].innerHTML
    console.log(text[0].toUpperCase() + text.slice(1));
  }
}
<input type="text" id="search"/>
<button type="submit" onclick="query()">Submit</button>
<div class="query-div"><p class="query-p">Test-a</p></div>
<div class="query-div"><p class="query-p">Test-b</p></div>
<div class="query-div"><p class="query-p">Test-ba</p></div>
Rafael Quintela
  • 1,908
  • 2
  • 12
  • 14
  • `toUpperCase()` is not the same output as `text-transform: capitalize`. – Cᴏʀʏ Oct 30 '17 at 19:34
  • I need to capitalize only the first letter of every word. – beannshie Oct 30 '17 at 19:34
  • sorry, fixed; text[0].toUpperCase() + text.slice(1) – Rafael Quintela Oct 30 '17 at 19:37
  • 1
    Another much quicker way to handle the word capitalization would be using regex like so: `str.replace(/^\w|\s\w/g, t => t.toUpperCase())`. That will also handle multi-word input rather than just a single word. So in this case, `var text = x[i].innerHTML.replace(/^\w|\s\w/g, t => t.toUpperCase())` – jmcgriz Oct 30 '17 at 19:58