Skip to content Skip to sidebar Skip to footer

How To Set A Value And Placeholder Together For Input Text?

I need to put a hint for a text box.I know it can be done via placeholder , but I also need to set value for the same text box (The initial value should be hidden).Is there any way

Solution 1:

Set the placeholder value via the standard JQM method identified via the JQM docs. Then, have JQuery watch for the user selecting the input field. Then tell JQuery to add a value to the input field.

You could try something like this:

To set an input field with a placeholder:

<input type="text" name="fname" id="input" placeholder="YOUR PLACEHOLDER TEXT">

To add the default value:

$("#input").focus(function() {
     $(this).InnerHTML("ADD DEFAULT VALUE HERE");
 });

JQuery Placeholder info

JQuery Focus info


Solution 2:

This will help, check and run code snippet here.

const inputElement = document.getElementById('my-input');
const suffixElement = document.getElementById('my-suffix');


inputElement.addEventListener('input', updateSuffix);

updateSuffix();

function updateSuffix() {
  const width = getTextWidth(inputElement.value, '12px arial');
  suffixElement.style.left = width + 'px';
}



function getTextWidth(text, font) {
    // re-use canvas object for better performance
    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
}
#my-input-container {
  display: inline-block;
  position: relative;
  font: 12px arial;
}

#my-input {
  font: inherit;
}

#my-suffix {
  position: absolute;
  left: 0;
  top: 3px;
  color: #555;
  padding-left: 5px;
  font: inherit;
}
<div id="my-input-container">
  <input type="number" id="my-input" value="15">
  <span id="my-suffix">%</span>
</div>

Post a Comment for "How To Set A Value And Placeholder Together For Input Text?"