webveuje/js/demo/jsform.html

99 lines
3.3 KiB
HTML
Raw Normal View History

2021-03-23 02:58:10 +00:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<input type="text" placeholder="姓名" value="" name="name" id="name">
<div>
<input type="radio" value="1" name="sex">
<input type="radio" value="2" name="sex">
</div>
<div>
<input type="checkbox" name="hob" value="game">玩游戏
<input type="checkbox" name="hob" value="bilibili">看小视频
<input type="checkbox" name="hob" value="tv">电视剧
</div>
<select name="lesson" id="lesson">
<option value="1">法学</option>
<option value="2">医学</option>
<option value="3">哲学</option>
</select>
<div>
<button onclick="save()">保存</button>
</div>
总结一:
1.radio 选中的时候for循环checked
2.checkbox 选中的时候要用个数组接收判断是否选中也是用checked属性值
3.select 下拉框 选中的时候要用selected 判断是否选中
4.数组转字符串 可以用join(),toString,for循环遍历数组再拼接字符串
<script>
var obj = {}
// function save(){
// var uname=document.getElementById('name')
// // console.log(uname.value)
// var sex= document.getElementsByName("sex");
// // console.log(sex[0].checked,sex[0].value)
// var hobby=document.getElementsByName('hob')
// // console.log(hobby[0].checked,hobby[0].value)
// var lesson=document.getElementById('lesson')
// // console.log(lesson.options)
// for(let i=0; i<lesson.options.length;i++){
// console.log(lesson.options[i].selected,lesson.options[i].value)
// }
// }
function save() {
obj.name = document.getElementById('name').value;
// console.log(obj,123)
var sex = document.getElementsByName('sex')
for (let i = 0; i < sex.length; i++) {
if (sex[i].checked) {
obj.sex = sex[i].value
}
}
var hob = document.getElementsByName("hob")
obj.hob = []
for (let i = 0; i < hob.length; i++) {
if (hob[i].checked) {
obj.hob[i] = hob[i].value
}
}
var lesson = document.getElementById('lesson')
for (let i = 0; i < lesson.length; i++) {
console.log(lesson[i])
if (lesson[i].selected) {
obj.lesson = lesson[i].value
}
}
// obj.hob=obj.hob.join(',')
obj.hob = obj.hob.toString()
console.log(obj, 123)
// 下面是ajax
$.ajax({
url: "https://kaoshi-shangpin.theluyuan.com/findshop",
data:obj,
type:"GET",
dataType:"json",
success: function (res) {
console.log(res)
}
});
}
</script>
</body>
</html>