Use variable more times, click event

2

I have a select HTML and change the value of a variable after it passes the onchange () function. The problem is that I have another condition and I can not validate.

JS:

//function mode select
var option = 0
function getData(val) {
if (val.value === "option1"){
    option = 1
    alert("option deplacement!");
}else{  
    option = 2
    alert("option ligne!");

} 
 show();
}

function show() {
   console.log(this.option);
    val = this.option
    if (val == 2){
        var el = document.getElementById('id_click');
        el.onclick = function (e) {
            alert("click2")
            var ev = e || window.event;
            var x2 = el.getAttributeNS(null, "x"); 
            var y2 = el.getAttributeNS(null, "y"); 
            //console.log(x2+" "+y2)
        }
    }
 }

HTML:

<select id="selectid" onChange="getData(this);" >
   <option value="option1">Deplacement</option>
   <option value="option2">lignes</option>
</select>
<div id="id_div">dfsd</div>

Example on Jsfiddle

    
asked by anonymous 05.11.2015 / 13:32

3 answers

1

Because the variable option is defined in global scope and a declarative function, such as yours, to receive this directly from the global scope it is possible to use this . In this case you can simply add the this to the variable option within the function, eg: this.option = 1; .

See the example below.

jsFiddle

// Variavel definina em escopo global.
var option = 0;

function getData(elemento) {
  
  // atribui valor a variavel option usando o operador ternário.
  this.option = elemento.value === 'option1' ? 1 : 2;
}

function clicked(elemento) {
	if(this.option === 2) {
    	elemento.innerHTML = "você clicou e a cor mudou.";
        elemento.style.background = 'tomato';
    } else {
        elemento.innerHTML = "você pode até clicar mas nada acontecerá.";
    }
}
div {
    background: lightgray;
    height: 100px;
    margin: 10px;
    width: 200px;
}
<select id="selectid" onChange="getData(this);" >
	<option value="option1">Deplacement</option>
	<option value="option2">lignes</option>
</select>

<div onclick="clicked(this);"></div>
    
05.11.2015 / 13:57
1

You can use switch to make this operation and make it more readable, try it this way.

function getData(val)
{
var option = 0
switch(val.value) {
    case "option1":
        option = 1
        alert("option deplacement!");
        break;
    case "option2":
        option = 2
        alert("option ligne!");
        break;
    default:
        option = 0;
  }
if (option == 2) {
    alert("Option2");
  }

}
    
05.11.2015 / 13:46
0

Places IF inside function too

var option = 0
function getData(val) {
    if (val.value === "option1"){
        option = 1
        alert("option deplacement!");
    }else{  
        option = 2
        alert("option ligne!");
    }

    if(option==2){
        alert("option2");
    }
}
    
05.11.2015 / 13:37