开发者

Checkbox that submits form on click

开发者 https://www.devze.com 2023-03-06 02:49 出处:网络
I\'m usi开发者_高级运维ng Codeigniter and wants to know how I can make a checkbox that submits the form on click?

I'm usi开发者_高级运维ng Codeigniter and wants to know how I can make a checkbox that submits the form on click?

Secondly, this checkbox will be one of several checkboxes that will act as a filter like products > $20, products < $30, how do i pass it in the url? I'm thinking /1+2+3


Haven't worked with Codeigniter much, but I can answer how to make the form submit on checking the checkbox with JS:

<form id="something">
    <input type="checkbox" name="foo" id="foo" value="yes" />
</form>

<script type="text/javascript">
$("#foo").click(function() {
    if ($(this).is(":checked"))
        $("#something").submit();
});
</script>


The javascript questions seem to have been solved already; let's step to the codeigniter ones.

You can pass the url in one of those two ways.

  1. Idiomatic but limited: as /1/2/3/4/etc. The controller function handling that url could both use func_get_args to read them or, if you already know how many parameters will be passed at the most, give a default value of null to all non-necessary paramenters;

  2. Not Codeigniterish but seriously better for search parameters: enable the query strings on your config file, pass arguments as you would normally with GET (min=2&max=3 and so on) and get their value with CI's input class ($min = $this->input->get('min')).


This has nothing to do with PHP, nor CodeIgniter. The solution is to submit the form in the onclick event of the element.

<input type="checkbox" name="filterx" onclick="document.forms[0].submit()" />

You can use the OnSubmit event of the form to nicely format the url, if you like.

To do this, you can

  • get the values of all desired elements,
  • build a nice url from it,
  • set the url using location.href = yourniceurl,
  • cancel the regular submit by returning false.

Note that both solutions require javascript to be enabled. So it is a good thing to have other means of submitting the form (submit button). Don't rely on submitting by pressing Enter. Opera will use the Enter key for toggling the checkbox instead of submitting the form. If you like, you can hide the submit button using Javascript, that way, users having Javascript will have their form auto-submitted, while users without can use the button. You will need to make sure that your server side form validator not only accepts the nice url, but the ugly url (which posts values like ?filterx=on) too.

0

精彩评论

暂无评论...
验证码 换一张
取 消