Get started with jquery

5 篇文章 0 订阅
4 篇文章 0 订阅

Getting a form value with jQuery

To get a form value with jQuery use the val() function. Let's say we have a form like this, using an id for each form element:

1<input name="foo" id="foo" type="text">
2  
3<select name="foo" id="bar">
4    <option value="1">one</option>
5    <option value="2">two</option>
6    <option value="3">three</option>
7</select>

We can display an alert for the values of "foo" and "bar" as easily this:

1window.alert( $('#foo').val() );
2window.alert( $('#bar').val() );

If we're using the name only and not specifying an id, the jQuery to get the form values would be this:

1window.alert( $('[name=foo]').val() );
2window.alert( $('[name=bar]').val() );

If you have a group of radio buttons and want to get the selected button, the code is slightly different because they all have the same name. Using the above code examples will show the value for the first radio button on the form with that name. To find out the value of the checked one, do this instead:

HTML:

1<input type="radio" name="baz" value="x">
2<input type="radio" name="baz" value="y">
3<input type="radio" name="baz" value="z">

jQuery:

1window.alert($('input[name=baz]:checked').val());

Setting a form value with jQuery

You can set the form values with jQuery using the same val() function but passing it a new value instead. Using the same example forms above, you'd do this for the text input and select box:

1$('#foo').val('this is some example text');
2$('#bar').val('3');
3OR
4$('[name=foo]').val('this is some example text');
5$('[name=bar]').val('3');

Using the above for a radio button will change the actual value of the radio button rather than changing the one that is selected. To change the radio button that is selected you'd do this:

1$('input[name="baz"]')[0].checked = true;

[0] would set the first one checked, [1] would set the second one checked and so on.

Working demos

For working demos of the above examples (and more) please see my demos for getting and setting form values with jQuery, how to check and uncheck a checkbox with jQuery, and clear a form with jQuery posts.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值