1. 程式人生 > >微信小程式獲取input輸入框的值

微信小程式獲取input輸入框的值

微信小程式獲取input輸入框的值

作者: 輕酌~淺醉 參考:ralStyle貴 官方文件

1,form表單獲取

wxml程式碼

<view class='box'>
  <form bindsubmit='searchBox'>
      <input type='text' class='userBox' name='username'></input>
      <input type='text' class='pwdBox' name='pwd'></input>
      <button class='login' form-type='submit'>登入</button>
  </form>
  <text>輸入的內容:{{first}}</text>
  <text>輸入的內容2:{{second}}</text>
</view>

js

searchBox:function(e){
    const that = this;
    let first,second;
    that.setData({
      first    :    e.detail.value.username,
      second   :     e.detail.value.pwd
    })
  }
  //這個函式一定要寫在標籤上才能用e.detail.value獲取到

2,bindinput事件獲取

wxml程式碼

//防止誤導,故去掉無關屬性
<input bindinput="getPhone"/>

js程式碼

getPhone(e){
	console.log(e);
}

官方對bindinput事件的說明:鍵盤輸入時觸發,event.detail = {value, cursor, keyCode},keyCode 為鍵值,2.1.0 起支援,處理函式可以直接 return 一個字串,將替換輸入框的內容。
列印的資料

  • currentTarget:{id: “”, dataset: {…}, offsetTop: 588, offsetLeft: 0}
  • detail:{value: "15600519819", cursor: 11}
  • target:{id: “”, dataset: {…}, offsetTop: 588, offsetLeft: 0}
  • timeStamp:1543306108218
  • touches:[]
  • type:“input”
  • proto:Object

我們需要的主要是detail物件裡的資料,其中value表示input資料,cursor表示長度