用jQuery獲取表單的值


在日常開發過程中,有許多用到表單的地方。比如登錄,注冊,比如支付,填寫訂單,比如后台管理等等。

使用jQuery來獲取表單的值是比較常見的做法。

常見表單

單行文字域:<input type='text'>

<input type="text" id='name' value='pelli'>

密碼域:<input type='password'>

<input type="password" id='pass' value='password'>

單選:<input type='radio'  name='sex'>男 <input type='radio' name='sex'>女

<input type="radio" name='sex' id='man' value="1">
<label for="man"></label>
<input type="radio" name='sex' id='woman' value="0">
<label for="woman"></label>

多選: 

   <input type='checkbox' value='1' name='intrest'>籃球

   <input type='checkbox' value='2' name='intrest'>足球

   <input type='checkbox' value='3' name='intrest'>皮球

<input type="checkbox" value='1' name='intrest' id='ball1'>
<label for="ball1">籃球</label>
<input type="checkbox" value='2' name='intrest' id='ball2'>
<label for="ball2">羽毛球</label>
<input type="checkbox" value='3' name='intrest' id='ball3'>
<label for="ball3">手球</label>
<input type="checkbox" value='4' name='intrest' id='ball4'>
<label for="ball4">乒乓球</label>
<input type="checkbox" value='5' name='intrest' id='ball5'>
<label for="ball5">足球</label>

下拉列表:

  <select id='drop'>

    <option value='1'>昨天</option>

    <option value='2'>今天</option>

    <option value='3'>明天</option>

  </select>

<select name="city" id="city">
    <option value="1">北京</option>
    <option value="2">南京</option>
    <option value="3">上海</option>
    <option value="4">成都</option>
    <option value="5">西安</option>
</select>

多行文字域:

  <textarea>這里可以寫多行文字</textarea>

<textarea name="" id="remark" cols="30" rows="10">這里是備注</textarea>

 

用jQuery獲取值

// 昵稱
var name = $("#name").val();
console.log(name);

// 密碼
var pass = $("#pass").val();
console.log(pass);

// 性別
var sex = $("input:radio:checked").val();
console.log(sex);

// 性別
var sex1 = checkAll($("input:radio"));
console.log(sex1);

// 興趣
var hobby = checkAll($("input:checkbox"));
console.log(hobby);

// 城市
var city = $("#city").val();
console.log(city);

// 城市
var city1 = $("#city option:selected").val();
console.log(city1);

// 備注
var remark = $("#remark").val();
console.log(remark);

一個可以獲取單選和多選的函數,返回值得數組

//獲取單選或者多選的值,返回一個值得數組,如果沒有值,返回空數組,參數inputlist是jQuery對象
function
checkAll(inputlist){ var arr = []; var num = inputlist.length; for(var i = 0; i < num; i++){ if(inputlist.eq(i).is(":checked")){ arr.push(inputlist.eq(i).val()); } } return arr; }

 

總結:

單行文字:$("#text").val();

密碼:$("#pass").val();

單選:$("input:radio:checked").val();

多選:遍歷 $("input:checkbox"),判斷是否選中

下拉:$("#select").val();

   或者

   $("#select option:select").val();

多行文字:$("textarea").val();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM