简体   繁体   中英

How to change the input value when entering the new value

I have an input with placeholder="YYYY/MM", when the user click the input to enter the data, I want the year and month to dissappear, so only "/" stays.

I already try with my code, however it doesn't work, please help/

 var birthdayId = "document.querySelector("#BIRTHDAY")"; if(birthdayId.maxlength < 4){ birthdayId.value = "/"; }
 <input type="text" id="BIRTHDAY" name="BIRTHDAY" placeholder="YYYY/MM" maxlength="7" value="YYYY/MM">

Run your code in a focus event listener.

You should be checking the length of the value, not the maxlength property, which never changes.

You shouldn't put the call to document.querySelector in quotes.

Don't set the default value of the input to YYYY/MM , since that will prevent the length test from working. The placeholder is used to display the desired format, you don't need to do it with value as well.

 var birthdayId = document.querySelector("#BIRTHDAY"); birthdayId.addEventListener("focus", function() { if (birthdayId.value.length < 4) { birthdayId.value = "/"; } });
 <input type="text" id="BIRTHDAY" name="BIRTHDAY" placeholder="YYYY/MM" maxlength="7" value="">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM