I want to create a input field with date but when user type his name for search then it also work in the same field.
More specifically I want make a dynamic input field with text and date input field in a search filter button in JavaScript.
Is it possible to create a field with date and later when user want to search by name then he able to search the name in same field and if he wants to search filter by date he also able to search in same field.
If it's possible then how can I do this?
You can use setAttribute(attr, value) property to change the attribute types.
More can be found here
Example using buttons:
function searchByName(){
document.getElementById("search").setAttribute("type","text");
}
function searchByDate(){
document.getElementById("search").setAttribute("type","date");
}
<button onclick="searchByName();">Search by name</button>
<button onclick="searchByDate();">Search by date</button>
<input type="date" name="search" id="search" />
EDIT
If you want to dynamically change based on input, you can try this:
const searchInput = document.getElementById("search");
searchInput.addEventListener("keydown",(e)=>{
const isNumber = /\d/.test(e.key)
if(isNumber){
searchByDate();
}
else{
searchByName()
}
},{once:true});
function searchByName(){
document.getElementById("search").setAttribute("type","text");
}
function searchByDate(){
document.getElementById("search").setAttribute("type","date");
}
<input type="date" name="search" id="search" />
PS: The above script will run only once. If your user has pressed the first key a number, then the input will remain as date otherwise, it will change to text