cdonts
cdonts

Reputation: 9599

How to add URL data (variables) when submiting a form?

I have this form on my web page:

<form action="my_target_file.py">
    <!-- some input textboxes here -->
    <input type="submit" value="Go!" />
</form>

When the form is submitted, I can access those values (the ones in the textboxes and other controls) easily. But I want to add some data to the my_target_file.py URL. For example, using Javascript, I can check if there's a checkbox checked or not. If it's checked, then I want to call my_target_file.py?checked=1 when submiting the form, along with all those values which the user has entered at the textboxes.

My current solution is to have a hidden textbox which I fill using Javascript when the checkbox is checked, for example. Then I read the hidden textbox from my_target_file.py, but that's not too clean.

How can I achieve this?

Upvotes: 0

Views: 102

Answers (1)

Joseph Myers
Joseph Myers

Reputation: 6552

Simply name the checkbox "checked" and set its value to "1"--JavaScript is not needed.

<input type="checkbox" name="checked" value="1" />

When added to the form code that you provided, the above checkbox will add a query string value of checked=1 within the existing query string if and only if the user has checked the checkbox.

As per your comment below, you can append hidden fields within a form like this:

var box = document.createElement('input');
box.type = 'hidden';
box.value = '1';
box.name = 'checked';
form.appendChild(box);

Do this for each parameter name and value that you want to store, and replace form with the JavaScript object that represents your form, e.g., document.forms[0] or document.getElementById("formid").

Upvotes: 1

Related Questions