Search This Blog

Sunday, September 30, 2012

How to get an element whose id starts with a particular pattern

Picking an element using its id is very in jquery, is not it? But what if the situation is you have three text fields and every of their id starts with a particular pattern? For example suppose you are working with three text fields

 <input type='text' name='properties_value' id ='properties_value_1' />  
 <input type='text' name='properties_value' id ='properties_value_2' />  
 <input type='text' name='properties_value' id ='properties_value_3' />  
 <input type='button' onclick='take_all_the_input();' value='Show'/>  

Now you want to work on the every text fields value using their id's. What will do? are u planning to write code for each and every text fields like the below???

 <script>  
 function take_all_the_input()  
 {  
    var input1 = $("#properties_value_1").val();  
    var input2 = $("#properties_value_2").val();  
    var input3 = $("#properties_value_3").val();  
   // I assume you just want to alert the values  
   alert(input1+' ' +input2+' '+input3);  
 }//end of function  
 </script>  
The above code will work but that is a very novice approach and will not work if you do not know exactly how many text fields will be there. That means if you have generate the text fields dynamically in that case you cant fix the number of text fields. Now come to the solution. The better solution (I am not telling it best but better because after reading this post you may write in your blog even better solution than my solution :) ). So the better solution is go through every text field's id that starts with a particular pattern (in this case 'properties_value_') since every id has started with 'properties_value_' and work on those values.

The code will be
 <script>  
 function take_all_the_input()  
 {  
   $("input[id^='properties_value_']").each(function()  
    {  
     // I assume you just want to alert the values  
     alert($(this).val());  
    }  
 }//end of function  
 </script>  

See we have used $("input[id^='properties_value_']").each(function() {..... Here you are going to traverse each of the id that starts with 'properties_value_' How are taking the id that starts with a particular pattern? using ^= . So this will give the attributes that starts with some pattern... On the other hand the $= will help you to find the ids that ends with a particular pattern.

Hope this helps.. Happy coding.


No comments:

Post a Comment