简体   繁体   中英

Change radio button 'checked' attribute on form submit

I've got two radio buttons. Which a user can select and submit dynamically to change the content of a HTML table I have.

How can I use jQuery to set the 'checked' attribute to the appropriate radio button. So, United Kingdom is checked by default and thus filled in 'blue'. When a user clicks Wales the radio button that is checked will be Wales and not United Kingdom.

This also needs to be reversible (ie selected UK after selecting Wales).

Here is my code:

<input type="radio" name="region" value="0" checked="checked" /> United Kingdom 
<input type="radio" name="region" value="1" /> Wales

And my current Javascript which just submits the form:

$('input[name=region]').change(function(){
                    $('form').submit();
                });

Please note that the form submits to the same webpage as that's where my HTML <table> is located.

see this code i hope it works.

jQuery(document).ready(function($) {
    $('input[name=region]').change(function(){
        alert(this.value);
                $('form').submit();
            });
});

if your form is method="POST" you need php:

<?php if(isset($_POST['region']) && $_POST['region'] == 1)) { echo 'checked="true"'; } ?>

or if its method="GET"

you can and set it with jQuery using getting parameter from url (example: http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html )

if

var param = 'your value of region param' 

then do

$(function() {
    $('input[name="region"][value="' + param + '"]')[0].checked = true; 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM