I'm creating a code that displays alerts when non-Hiragana is entered into a particular input of the form, but I'm a beginner, so I'm stuttering.
The code below seems to work as desired, but what should I do if there are two IDs that I would like to specify in const kana?
I thought I should specify two things in const, so I tried to set getElementById to querySelectorAll and parentheses like ('LastName_Kana_c, FirstName_Kana_c'); but none of them worked.
Is this idea correct in the first place?
I look forward to your kind cooperation.
const kana= document.getElementById('LastName_Kana__c');
kana.addEventListener('input', (event) =>{
let tmp = [ ];
kana.value.split("").forEach(function(item,i){
if(item.match(/^[\u3040-\u309f]+$/)){
tmp.push(item);
alert("It's hiragana, isn't it?");
}
});
if(tmp.length>0){
kana.value=tmp.join("");
} else{
kana.value="";
alert ""It's not hiragana, is it?");
}
});
NodeList
and process it in a loop.querySelectorAll
returns a list of elements (NodeList
).This is an array-like collection.Use the for
loop or the forEach
method to process all elements in this list.Either way, use the target
property of the event.
Example:
// Method 1: Set the Event Listener for each NodeList element
const buttons= document.querySelectorAll("#one, #two")
for (elm of buttons) {
elm.addEventListener("click", ev=>{
console.log("--- Method 1: Directly Configured Event Listener---")
console.log("currentTarget.id:", ev.currentTarget.id)
console.log("target.id:", ev.target.id)
})
}
// Method 2: Set up an Event Listener for one element to handle all events in the descendant element
const parent = document.getElementById("parent")
parent.addEventListener("click", ev=>{
console.log("--- Method 2: Event Listener Configured on Parent Element---")
console.log("currentTarget.id:", ev.currentTarget.id)
console.log("target.id:", ev.target.id)
})
<pid="parent">
Hello
<button id="one">Button1</button>
<button id="two">Button2</button>
</p>
In a simple case, I think method 1 is fine.Using event propagation, as in Method 2, gives you more consideration.For example, in the code above, the element parent
also contains areas other than buttons, so you have to consider the events that occur by clicking on it.
© 2024 OneMinuteCode. All rights reserved.