Reputation: 12002
I need to be able to know when to use val()
and when to use text()
with jQuery dynamically.
If I have a span
and an input
with the same class name, I need to apply val()
on the inputs and text()
on spans to set it's value/content.
Here is my HTML markup
<input class="att" name="some1" value="" type="text"><br>
<input class="att" name="some2" value="" type="text"><br>
<input class="att" name="some3" value="" type="text"><br>
<div class="att"></div><br>
<div id="test" class="att"></div><br><br>
<div id="cl">Click Me</div>
Here is what I tried which is not setting the value as expected
$(function(e){
$('#cl').click(function(e){
//Select any input that has the class "att" and apply the val() function
$('.att :input').val('123');
//Select any element that is not an input and apply the text() function
$('.att').not(':input').text('123');
//Search for an element with a known ID but apply `val()` if the element is input
$('#text .att :input').val('123');
//Search for an element with a known ID but apply `text()` if the element is not an input
$('#text .att').not(':input').text('123');
});
});
I also created a jfiddle with my code
How can I correctly apply the val() and text based on the element type?
Upvotes: 0
Views: 219
Reputation: 1218
You are using wrong selectors. Thats why you are not getting desired results. Use space between selectors when you need search further elements inside them, don't use them otherwise.
it should be .att:input
and
#text.att:input
and
#text.att
https://jsfiddle.net/gqxsdsyb/5/
Upvotes: 3
Reputation: 11136
Try the .is() function. You can do element detection with that. For example,
if ($(element).is("span")){/* set text */}
// or
if ($(element).is("input")){/* set val */}
Upvotes: 0