我得到空字符串''或& # 39;未定义# 39;从.val()函数

I'm getting empty string '' or 'undefined' from .val()-function

本文关键字:val 函数 未定义 字符串      更新时间:2023-09-26

我要做的是捕获input的值与类statisPrice-0或写在代码中,如:

statisPrice-" . $i . "

,因为数字将增加0,1,2,3,4...,我将需要稍后对该值进行一些数学计算。

我尝试了几种方法来捕获input的值,但我得到一个空字符串或undefined。我已经阅读了这里,所有的答案都没有帮助我解决我的问题。

echo "<input type='number' name='qtty-" . $i . "' class='col-md-6' min='" . $good['Ratio'] . "' step='" . $good['Ratio'] . "' value='" . $good['Ratio'] . "'>";
echo "<div class='col-md-3'>";
    echo "<div class='col-md-12'><strong>Цена в лв.</strong></div>";
    // this is the input:
    echo "<input type='hidden' class='statisPrice-" . $i . "' val='" . number_format((float)$good['PriceOut2'] * $good['Ratio'], 3, '.', '') . "'>";
    echo "<div class='col-md-12 price-" . $i . "'>" . number_format((float)$good['PriceOut2'] * $good['Ratio'], 3, '.', '') . "</div>";
echo "</div>";
我的jquery代码是:
$(document).ready(function(){
//change the price
    var thisIsIt = $(this);
     $("input[name*='qtty']").change(function() {
        var val = $(this).val();
        var getName = $(this).attr("name");
        var getNumber = getName.substr(5, 10);
        // this is the code where im trying to catch the input and i tryed several ways and noone of them worked :(
        var price = thisIsIt.find(".statisPrice-" + getNumber).val();
        alert(".statisPrice-" + getNumber);
        alert(price); //outputs empty string ""
        alert(val);
        thisIsIt.find(".price-" + getNumber).text(val * price);
    });
});

我不明白为什么它不能取hidden input的值并进行计算-> val * price

如果有人能告诉我我错在哪里,我将不胜感激。

正如@dandavis评论中提到的,你的<input>元素的属性需要是value而不是val

<input ... value=".." /> 

你应该使用

$( "input[name^='qtty']" )

使用console.log

代替alert

或者最好在问题位置放置一个调试器

var price = $(".statisPrice-" + getNumber).val();之前