将输入按钮值设置为相同的名称但是大写

时间:2016-07-27 07:51:07

标签: javascript jquery

我尝试将输入按钮的值更新为与以前相同的名称,但是大写。我努力调用按钮值中的按钮值并继续收到错误。这就是我现在所拥有的:

function updateButton(button) {
    $(button).val(button.val().ToUpperCase())
}

我得到的错误是:

Uncaught TypeError: button.val is not a function

HTML:

<input type='button' id='btn1' value='test' class='btn' onclick='updateButton(this)'>
<input type='button' id='btn2' value='test' class='btn' onclick='updateButton(this)'>
<input type='button' id='btn3' value='test' class='btn' onclick='updateButton(this)'>

有关如何更新内部值的任何想法?

7 个答案:

答案 0 :(得分:1)

尝试:

$(button).val($(button).val().toUpperCase());

第二个按钮也需要被jQuery包装,并且toUpperCase以(讽刺的)小写t开头。

答案 1 :(得分:0)

首先请注意,更改案例的方法是toUpperCase(),而不是ToUpperCase()

从你得到的错误看来,button变量包含DOMElement而不是jQuery对象,因此在尝试访问jQuery的val()方法时会出错。相反,您可以直接使用DOMElement的value属性:

function updateButton(button) {
    $(button).val(button.value.toUpperCase())
}

更好的是,您可以使用不显眼的JavaScript来附加事件处理程序:

$('.btn').click(function() {
  $(this).val(this.value.toUpperCase());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' id='btn1' value='test' class='btn' />
<input type='button' id='btn2' value='test' class='btn' />
<input type='button' id='btn3' value='test' class='btn' />

答案 2 :(得分:0)

您正在将jQuery对象与其他js变量混合使用。 $(button)是一个jQuery对象,它选择按钮类型的所有元素,而button只是一个变量,如果之前没有定义,则类型为undefined

var button = $(button);
function updateButton(button) {
    button.val(button.val().toUpperCase())
}

答案 3 :(得分:0)

你得到.val()是jQuery方法,你正在使用本机DOM元素。

您需要创建一个jQuery对象才能使用.val(),可以使用val(fn)方法实现操作

$(button).val(function(_, value){
    return value.toUpperCase()
})

答案 4 :(得分:0)

我建议:

// select all <input> elements with a 'type' attribute
// equal to 'button'; then use the on() method - and
// its anonymous function - to bind the anonymous
// function as the 'click' event-handler:
$('input[type=button]').on('click', function(){

    // set the value of the current element -
    // 'this' will be the clicked input element -
    // to the string-value of its name attribute
    // set to uppercase:
    this.value = this.name.toUpperCase();
});

答案 5 :(得分:-1)

$( '#button_id')。VAL(button.val()。ToUpperCase())

答案 6 :(得分:-1)

试试这个:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
        function updateButton(button) {
          $(button).val($(button).val().toUpperCase());
        }
    </script>
    <input type="button" value="hello" onclick="updateButton(this)">
&#13;
&#13;
&#13;