Hi, from this saved page , I use this function for the “Collocazione” field:
$field = document.querySelector('#collocazione');
if( /^8[1-2,4-8][0-9]*\./.test($field.value)){
$field.value = $field.value.substr(0, $field.value.indexOf('.') +2);
}
I would like it to be executed only when the “Sezione” field (‘cdSezi’) is set to “A.”
I tried to add these first two lines, but the value of “Sezione” field remains fixed to “A.”:
var text = document.getElementById('cdSezi');
if (text.value="A.") {
$field = document.querySelector('#collocazione');
if( /^8[1-2,4-8][0-9]*\./.test($field.value)){
$field.value = $field.value.substr(0, $field.value.indexOf('.') +2);
}};
Thank you very much!
This line is an issue. You are assigning “A.” to text.value.
if (text.value="A.") { // = set it to "A."
You need to use a comparison operator instead.
if (text.value === "A.") { // === does it equal "A." ?
BTW an easy mistake.
Just as an aside, I don’t know if you are confusing PHP with JS.
$field = document.querySelector('#collocazione');
This will define a global variable called ‘$field’, which isn’t the best idea unless it really needs to be globally available.
Otherwise this would be an improvement
const field = document.querySelector('#collocazione');
This link might be helpful
2 Likes
Thanks very much rpg_digital , it works now indeed! Thanks also for the advice, very kind from you!
1 Like
Sorry, rpg_digital , I’m trying to add an ‘or’ condition to text.value
:
if (text.value==="A." || "B.") {
but it doesn’t work, even trying with:
var text = document.getElementById('cdSezi');
if (text.value==="A.") {
if (text.value==="B.") {
const field = document.querySelector('#collocazione');
if( /^[1-9][1-9][1-9]*\./.test(field.value)){
field.value = field.value.substr(0, field.value.indexOf('.') +0);
}}}
Could you help me, please? Thanks!
PaulOB
March 11, 2023, 7:29pm
5
Try:
if (text.value==="A." || text.value==="B.") {
1 Like
It works, thank you, PaulOB !
1 Like
rpg_digital:
BTW an easy mistake.
If “A.” text value is. :-)
In programming jargon, Yoda conditions (also called Yoda notation) is a programming style where the two parts of an expression are reversed from the typical order in a conditional statement. A Yoda condition places the constant portion of the expression on the left side of the conditional statement.
Yoda conditions are part of the coding standards for Symfony and WordPress.
The name for this programming style is derived from the Star Wars character Yoda, who speaks English with a non-standard ...
2 Likes
If there is more options this may be shorter:
if ([“A.”, “B.”, “C.”].includes(text.value)) {
3 Likes