Here's a very simple question... can I add/chain the JS method .split()
to jQuery's .val()
method? For example...
var myNewArray = $("#myString").val().split(",");
I seem to get $("#myString").val().split
is not a function in Firebug? I thought I could chain my JS and jQuery methods, perhaps I was wrong?
Thanks
Here's a very simple question... can I add/chain the JS method .split()
to jQuery's .val()
method? For example...
var myNewArray = $("#myString").val().split(",");
I seem to get $("#myString").val().split
is not a function in Firebug? I thought I could chain my JS and jQuery methods, perhaps I was wrong?
Thanks
Share Improve this question edited Apr 18, 2012 at 12:10 noob 9,2224 gold badges39 silver badges65 bronze badges asked Apr 18, 2012 at 12:06 Mike SavMike Sav 15.3k31 gold badges102 silver badges150 bronze badges 7-
2
That depends on what
$("#myString").val()
returns which in return depends on what the element with IDmyString
is. If the return value is a string, then of course yes. If it is an array, then no. – Felix Kling Commented Apr 18, 2012 at 12:10 -
3
What kind of HTML element are you doing
.val()
on? The behaviour of.val()
may vary. Specifically it may returnnull
for a<select>
that allows multiple selections if there are no selected options. – Christoffer Commented Apr 18, 2012 at 12:10 - So we#re saying I should check that $("#myString").val() isn't a null falsy (I should check it isn't null before splitting). – Mike Sav Commented Apr 18, 2012 at 12:12
- For me, your code works fine. See demo jsfiddle/dwF9t – Snake Eyes Commented Apr 18, 2012 at 12:12
- prof jsfiddle/eD75c/1 – Yorgo Commented Apr 18, 2012 at 12:13
4 Answers
Reset to default 2Why don't you have a look at the documentation? It says:
Returns: String, Number, Array
So you can use .split()
in 30% (to be more precise: 33.33...%) of the cases. It depends on which element you are using .val()
on.
So the answer to your question is: It depends.
yes you can the val()
return a string so its not jQuery when chaining after that , check the jquery refrence , and about chaining jquery with javascript the answer is no in most cases , because most jquery methods returns a jquery object not a DOM element or primitive javascript type , but in this case your returning a string , so everything should be fine
Perhaps your selector can't find an element and it returns an empty jQuery object. When you call val()
method on this object you'll get undefined
.
You can use .val().split(","). But I have question what is in #myString. If it is label then you have to write like this :
$(#myString).text().split(" ");