简体   繁体   中英

How to distiguish when to use .val() or .text() dynamically using jQuery?

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?

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/

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 */}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM