So, I have two input fields, and I’m trying to store values into a string. The problem is that I’m not sure how to store the variable in the first input. For instance, if the user only inputs the value for p1, it should be "Partner IN (" + document.getElementById("p1").value + ")" but if the user enters both values for p1 and p2 it should be Partner IN (" + document.getElementById("p1").value + "," + document.getElementById("p2").value + ")". I want to make sure, that the variable ep has the updated values (i.e. if user decides to change values multiple times)
https://jsfiddle.net/Charan98/ynbh142x/
let ep;
document.getElementById("p1").addEventListener("blur", () => {
document.getElementById("p2").addEventListener("blur", () => {
if (document.getElementById("p2").value.length == 0) {
ep = "Partner IN (" + document.getElementById("p1").value + ")";
} else {
ep = "Partner IN (" + document.getElementById("p1").value + "," + document.getElementById("p2").value + ")";
}
});
ep = "Partner IN (" + document.getElementById("p1").value + ")";
console.log(ep)
});
<div>
<input id="p1" type="text" value="" />
<br>
<br>
<input id="p2" type="text" value="" />
</div>
5
Answers
I would listen to both and create a funciton getContent which is in charge of creating the content formatted
Here is an example in this fiddle:https://jsfiddle.net/o1cwb6th/
This is a great example of where arrays and their methods can work nicely. Post the values to the array individually, then join them into a comma-delimited string.
I assume you want to have
#p2
‘s listener active only after#p1
received ablur
event. But your current code is adding a new listener to#p2
whenever#p1
receives ablur
event.Instead, you could have the listener always attached, but return early in case
#p1
contains no value:You could also attach the same listener to both elements. That listener could then evaluate what and how many values to add dynamically. (See mykaf’s answer.)
If you don’t want to add the same listener twice, you could also make use of event delegation: Add the listener to a common ancestor. Example:
Edit : I didn’t know that the answer was marked as solved, sorry…
Anyway…
I saw your comment :
So there’s an idea to avoid this but I use
keyup
event.