We discussed in my previous post that how efficient J Query is ?It enables to perform the required functionality in very less code as compare to the java script.

In this series of article I will write about small J query samples and their comparison with JavaScript code.

So starting this series, I am presenting here the code to select some item in combo box. (select tag in HTML).

Lets suppose I have a HTML form and we are having a combo box in that form. My task is to select some item in combobox. the task can be achieved by Javascript and Jquery both.
Lets see how can we achieve the purpose :


HTML code to have a combobox in a form.

 <html>
 <head>
 </head>
 <body>
  <select id="ddlStates" name="states[]" class="mySelect" onchange="callStateChange(this);">
           <option value="">State</option>
           <option value="NY">New York</option>
           <option value="NC">North Carolina</option>
           <option value="ND">North Dakota</option>
           <option value="OH">Ohio</option>
           <option value="OK">Oklahoma</option>
         </select>
 </body>
 </html>

Now if I want that the combobox gets selected on load then I can use Javascript as well as Jquery.

Lets suppose I want that on load , Newyork item should be selected.

JQuery code :



<script type="text/javascript">
$("#ddlStates").val('NC');
</script>


 JavaScript code:


<script type="text/javascript">  

  var stateComboBox = document.getElementById('ddlStates');
  stateComboBox.value = 'NC'
 </script>

The example can be found here :
Example

The complete source code of the example is follows:


 <html> 

 <head>  
 <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">  
 </script>  
  <script type="text/javascript">  
    function selectByJQuery() {  
      $("#ddlStates").val('JQ');  
    };  
    function selectByJavascript() {  
      var stateComboBox = document.getElementById('ddlStates');  
      stateComboBox.value = 'JS';  
    }  
 </script>  
 </head>  
 <body>  
  <select id="ddlStates" name="states[]" class="mySelect" onchange="callStateChange(this);">  
           <option value="">Options</option>  
           <option value="JQ">JQuery</option>  
           <option value="JS">Javascript</option>  
         </select>  
 <br/><br/><br/><input type="button" id="selectbyJQuery" value="JQuery Execution" onClick="selectByJQuery();"/>  
 <input id="selectbyJQuery" type="button" value="Javascript Execution" onClick="selectByJavascript();"/>  
 </body>  
 </html>  

0 comments:

Post a Comment

 
Top