2016-09-29 33 views
0

我想,當在一個<input>字段失去焦點,對這個字段的值執行幾個操作,包括改變內容本身(以便它是大寫)如何更新.focusout()上的字段?

在以下code

HTML

<input id="name" type="text"></input> 
<div id="upper"></div> 

的JavaScript + jQuery的

$("#name") 
    .focusout(function() { 
    // get the text from the form which lost focus 
    name = $("#name").val(); 
    // turn it into uppercase 
    name = name.toUpperCase(); 
    // update the form and another entry 
    $("#upper").text(name); 
    $("#name").text(name); 
    }) 

事件被正確捕獲,<div>更新爲小寫文本。但是,該字段的內容不會更新。

離開它時可以更新<input>字段的內容嗎?

+1

變化'value'('.VAL()')不是文本? http://api.jquery.com/val/ – Pogrindis

+0

'val()'是用於表單元素的,'text()'是幾乎所有其他的東西。 –

+1

不相關,但我想說2件事。首先:你應該在使用之前定義一個變量('var name = ...'或'let name = ...',而不是'name = ...')。第二,在函數內部,你可以使用'$(this)'而不是重新調用'$('#name')' –

回答

1

更改文本()爲val()用於現場

$("#name").val(name); 
0

使用jQuery.val()設定值,不jQuery.text(),還要注意thishandler-functionElementevent被調用,因此this可以用來代替的specified-selector

你可以試試這個簡單的代碼:

$("#name").focusout(function() { 
 
    var name = this.value.toUpperCase(); 
 
    $("#upper").text(name); 
 
    $(this).val(name); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<input id="name" type="text"></input> 
 
<div id="upper"></div>