Sam
Sam

Reputation: 207

How to add dollar sign to input field without affecting the value of input?

How can i add $ to the following input:

<td class="td10"><input type='text' class='form-control' id="boqRate" name="boq[boqRate]"></td>

Upvotes: 3

Views: 9056

Answers (2)

Code Guru
Code Guru

Reputation: 15578

Try this. I have added span element with position:absolute.

.prefix {
  margin-right: -10px;
  position: absolute;
}

.my-input {
  padding-left: 5px;
}
<td class="td10"><span class="prefix">$</span><input class="my-input" type='text' class='form-control' id="boqRate" name="boq[boqRate]"></td>

Upvotes: 6

Ajay Gupta
Ajay Gupta

Reputation: 2033

This should work:

let input = document.getElementById("name");

input.addEventListener("keydown", () => {
  let inputValue = input.value;
  if (inputValue) {
    if (inputValue.charAt(0) === "$") {
      inputValue = inputValue.substring(1);
    }
  }
  let newValue = `$${inputValue}`;
  input.value = newValue;
});
<input id="name" />

Hope it helps!

Upvotes: 1

Related Questions