1. 程式人生 > >jquery 對form表單的動態操作

jquery 對form表單的動態操作

<!doctype html>
<html >
<head>
<title>表單練習3</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#b_add').click(function(){
var fullname = $("input[id='fullname']").val();
var sex = $("input[type='radio']:checked").val();
var dept = $('#dept option:selected').html();
if(fullname ==''){
alert('姓名不能為空');
return;
}
if(fullname.length > 10){
alert('姓名不能超過10個字元');
return;
}

//var id = jQuery("table").find("tr").length +1 
var trHTML = '<tr>'+
'<td><input type="checkbox" id="check"/></td>'+
'<td>'+fullname+'</td>'+
'<td>'+sex+'</td>'+
'<td>'+dept+'</td>'+
'</tr>';
$("#list").append(trHTML);
});


$('#b_del').click(function(){
//var tabRowLen = $("table tbody tr").length;

<!-- for(var i = 1; i < tabRowLen; i++ ) { -->
<!-- var row = $("#table").find("tr").eq(i) -->
<!-- var temp = row.find("td").eq(0); -->
<!-- if(temp.find('input').prop('checked')) {-->
<!-- row.remove(); -->
<!-- } -->
<!-- } -->
$('table tr td input:checked').each(function(){
n = $(this).parents("tr").index();
$("#list").find("tr:eq("+n+")").remove();
});
});
});
</script>
</head>


<body>
<p>
<label for="fullname">姓名:</label>
<input type="text" id="fullname" />
</p>
<p>

<label>性別:</label>
<input type="radio" name="sex" id="sex_1" value="男" /><label for="sex_1">男</label><!--//如果此處value為1和2獲取的值總是為1和2,獲取不到文字 -->
<input type="radio" name="sex" id="sex_2" value="女" /><label for="sex_2">女</label>
</p>
<p>
<label for="dept">部門:</label>
<select id="dept">
<option value="A">應用服務部</option>
<option value="B">平臺支援部</option>
<option value="C">解決方案部</option>
</select>
</p>


<table id="list" border="1">
<tr>
<th>選擇</th>
<th>姓名</th>
<th>性別</th>
<th>部門</th>
</tr>
</table>


<button id="b_add" type="button">新增</button>
<button id="b_del" type="button">刪除</button>
</body>

</html>

作為一個新手開始不知道如何操作,對應的函式也不知道,只能去查api,網上去看別人的例子.