Add condition to javascript

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!

Try:

if (text.value==="A." || text.value==="B.") {

1 Like

It works, thank you, PaulOB!

1 Like

If “A.” text value is. :-)

2 Likes

If there is more options this may be shorter:

if ([“A.”, “B.”, “C.”].includes(text.value)) {

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.