Why .val() is always empty (Jquery)?

2019-08-26 19:46发布

I have a problem with an Input.

here's my html/php code :

$dotation = ($ig["dotation"]) ? $ig["dotation"]: '<input type="text" class="datepickerIG" name="igDota" size="8" value="test"/>';
            $bo .= '<tr style="background-color: black;">
                     <td class="dot">' . $dotation . '</td>
                     <td class="modif" ref="' . $ig["id"] . '"><a href="#">Modifier</a></td>

here's my js code :

        var dot_cha = $(this).parent().find('.dot').val();

my question is, why var dot_cha is always empty ?! when I use .html insteed of .val, I get the right so, where's my error ?

Thanks.

7条回答
可以哭但决不认输i
2楼-- · 2019-08-26 20:20

.val() grabs the value attribute of a input-element. ".dot" is a td and doesn't have a value-attribute.

What exactly is it you want dot_cha to be? If its the input you are after, this would work.

$(this).parent().find('.datepickerIG').val();

If it is the text of the td .html() or .text() will give you this.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-26 20:20

val retrieves the value of input and other tags which have this attribute. In your case, .dot is the class of a table row which has no attribute value... So you have to use .text() or .html().

查看更多
戒情不戒烟
4楼-- · 2019-08-26 20:21

val() is to be used with form elements (such as input, textarea etc...), not with elements.

You need to get the innerHTML or innerText of the element.

Something like:

var dot_cha = $(this).parent().find('.dot').text();

Though you need to ensure you have one element - as you may be getting a collection of elements.

查看更多
smile是对你的礼貌
5楼-- · 2019-08-26 20:22

From the jQuery API documentation:

The .val() method is primarily used to get the values of form elements such as input, select and textarea.

val is used on form elements. Since .dot is a td element (which is not a form element) using val on it will not work. To get the contents of any element other than a form element, use .html or .text

查看更多
做个烂人
6楼-- · 2019-08-26 20:24

From the docs:

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

查看更多
【Aperson】
7楼-- · 2019-08-26 20:25

The doc here says

The .val() method is primarily used to get the values of form elements such as input, select and textarea.

You're right .html works since in your case you have a td, and you should use

$(".dot").html()

Hope it helps

查看更多
登录 后发表回答