Kurkula
Kurkula

Reputation: 6762

jquery split not working

I am trying to split a string values seperated by commas using jquery, but it throws split is not defined error. I am using latest version of jquery. Could you please help me on this.

Enter th names seperated by commas
    <input type=text id=thVal >
    <input type=button value='hide entered th related columns' id=btnclick>

$('#btnclick').click(function(){
   var array = $('#thval').val().split(",");    
   $.each(array,function(i){
   alert($(array[i]).val());
   });       
});

Upvotes: 2

Views: 9543

Answers (2)

Khamidulla
Khamidulla

Reputation: 2975

You should correct your jquery first selector. Correct way of selecting your input box by specifying your id selector. Because selector case sensitive.

$('#thVal').val().split(',');

Look this fiddly example here. Since you passing counter i and array to function each. Which will call for each element. So elements can be reached this keyword.

$('#btnclick').click(function(){
   var array = $('#thVal').val().split(",");    
   $.each(array,function(i){
   alert(this);
   });       
});

Upvotes: 5

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

IDs are case sensetive. This means that $("#thval") will NOT find an element with id="thVal".

I'd also like to point out that if you are using the "latest version of jQuery", then you can just do this instead:

document.getElementById('btnclick').addEventListener("click",function() {
    document.getElementById('thVal').value.split(",").forEach(function(part) {
        var elem = document.getElementById(part);
        alert(elem ? elem.value : "Element "+part+" does not exist");
    });
},false);

Vanilla JS is always faster, and in this case I even added in an error check for when an element doesn't exist!

Upvotes: 3

Related Questions