2012-09-25 5 views
1

Voici mon code javascript, je veux passer la valeur actuelle sélectionnée de l'option de ma fonction js, dans ce code i utilisé nombre statique 6.JavaScript passe this.value argument pour fonctionner

<select name='project_name' class='required input_field' id='project_name' onchange="sendRequest('GET','getClientName.jsp?ProjectId=6')"> 
<option value=''>-- Select --</option> 
<option value="1">Project 1</option> 
<option value="2">Project 2</option> 
<option value="3">Project 3</option> 
</select> 

aide moi pour résoudre ce ...

+0

@Buzz J'ai essayé comme ça, onchange = "sendRequest ('GET', 'getClientName.jsp? ProjectID = this.value')" –

Répondre

7

Modifier la chaîne 'getClientName.jsp?ProjectId=6' à

'getClientName.jsp?ProjectId=' + this.options[this.selectedIndex].value) 

ou

'getClientName.jsp?ProjectId=' + this.value) 

mais je pense que le premier est plus compatible avec les navigateurs.

+0

merci, a travaillé son .. –

+1

J'ai toujours utilisé votre deuxième méthode et il n'y avait pas de problème sur un navigateur –

+0

Ok merci, n'était pas sûr à ce sujet – Marc

2
var selectBox = document.getElementById('project_name'); 
selectBox.addEventListener('change', function() { 
    sendRequest('GET', 'getClientName.jsp?ProjectId=' + this.value); 
}); 
+0

Je préfère cette méthode (aussi longtemps qu'elle tient compte de la sottise 'attachEvent()'): http://jsfiddle.net/gSdFy/ –

+0

Ouais j'ai omis la couverture de code pour '' attachEvent() '' pour la brièveté :) – richoffrails

0

Il vous aidera à obtenir la valeur d'option sélectionnée. Essayez ce lien http://jsfiddle.net/xyaaa/9/.

<html> 
    <head> 
     <script> 
      function getOption(t){ 
       var val; 
       var options = t.options; 
       for(var i=0,len=options.length;i<len;i++){ 
        var option = options[i]; 
        if(option.selected){ 
         val = option.value; 
        } 
       } 
       return val; 
      } 
      function sendRequest(method , url){ 
        console.log(url); 
      } 
    </script> 
    </head> 
      <body> 
       <select onchange="var x=getOption(this);sendRequest('GET','getClientName.jsp?ProjectId='+x)"> 
        <option value="1">Project 1</option> 
        <option value="2">Project 2</option> 
        <option value="3">Project 3</option> 
       </select> 
    </body> 
</html> 
Questions connexes