【form 表单】提交表单数据;文本框按下回车自动触发表单提交、输入框宽度自适应长度

提交表单数据:

通过表单提交:

<form action="https://www.imooc.com/api/http/search/suggest?words=js" method="post" enctype="application/x-www-form-urlencoded">
	<input type="text" name="username"/>
	<input type="text" name="password"/>
	<input type="submit" value="提交" />
</form>

按下提交按钮,浏览器将自动发出请求,携带输入的数据跳转到 action 指定的页面。
请添加图片描述

通过 Ajax 提交:

<form id="login" action="https://www.imooc.com/api/http/search/suggest?words=js" method="post" enctype="application/x-www-form-urlencoded">
	<input type="text" name="username"/>
	<input type="text" name="password"/>
	<input type="submit" value="提交" id="submit" />
</form>

const login = document.getElementById('login')
const {username, password} = login
const btn = document.getElementById('submit')
btn.addEventListener('click', e => {
	// 阻止表单的默认提交
	e.preventDefault()

	const xhr = new XMLHttpRequest()
	xhr.addEventListener('load', () => {
		console.log(xhr.response);
	})
	xhr.open('post', 'https://www.imooc.com/api/http/search/suggest?words=js', true)
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
	xhr.send(`username=${username.value}&password=${password.value}`)
})

按下提交按钮, Ajax 发出请求,携带输入的数据,且不会跳转页面。
请添加图片描述

文本框按下回车自动触发表单提交:

一个表单下,如果只有一个文本框时,按下回车将会默认触发表单的提交事件。多个文本框时,按下回车不会触发表单的提交事件。

<form>
   <input type='text'/>
</form>

解决方法:阻止表单的默认事件即可。

输入框宽度自动适应文本长度:

JS:

获取输入框中 value 值的字数,来动态设置 input 的宽度。

onchange:在属性值改变时还必须使得当前元素失去焦点才可以激活该事件。
onpropertychange: IE下,当一个HTML元素的属性改变的时候,都能通过 onpropertychange来即时捕获。在用js脚本改动该元素值时能触发onpropertychange事件。
oninput:是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器。但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。

<input type="text" style="width:50px;" id="test" onPropChanged ="handleChangeWidth()" oninput ="handleChangeWidth()"/>

<script type="text/javascript">
    function handleChangeWidth() {
        var dom = document.getElementById('test'),
        textLength = document.getElementById('test').value.length;

        //对字数及宽度做限制
        if(textLength>20){
            dom.style.width = '280px';
            return false;
        }
        dom.style.width = textLength*14 + 'px';
    }
</script>

CSS:

contenteditable 属性规定元素内容是否可编辑。可以结合 max-width、min-width 限制最大最小宽度。

去除获得焦点时蓝色的边框:outline:none;

<div contenteditable="true" style = 'width:300px'>这是一段可编辑的段落。请试着编辑该文</div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值