Can two form inputs have the same name if one is disabled?

I have an address form and I want to have a selection box for states if the country is in the USA and change it to a text box if it is a foreign country to enter a state / province.

I generate code in PHP (e.g., state selection and country selection), and I thought about displaying both select and text field and initially hide and disable the text field, and then if the user changes the country and turns on the text field and hide and disable selections.

My question is, do both inputs really have the same name if one of them is disabled when the form is submitted?

As a bonus question, is there a better way to do this?

+4
source share
2 answers

Yes, it is possible, and this is the best way to do this, since disabled inputs are not sent in the request and generate correct and semantic HTML.

As shown in w3 :

When set, the disabled attribute has the following effects for the element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in the tab navigation.
  • Disabled controls cannot be successful.

[...]

In this example, the INPUT element is disabled. Therefore, it cannot accept user input, and its value will not be presented on the form.

+5
source

Assuming you are using jQuery, you can do something like this:

HTML:

<select id="countries"> <option>Countries</option> </select> <select id="states" style="display: none"> <!-- States in US --> <option>States</option> </select> <textarea id="address" style="display: none"> </textarea> 

JS:

 // Cache states list and address box beforehand so we don't have to query every time. var $states = $("#states"), $address = $("#address"); $("#countries").change(function () { // Bind to change event for checking if US selected var isUnitedStates = $(this).val() == "United States"; if (isUnitedStates) { // US is selected, show States $states.attr("id", "address").show() $address.attr("id", "_address").hide() } else { // US is not selected, show Address box $states.attr("id", "_address").hide() $address.attr("id", "address").show() } }) 

This is not very convenient, but if you really want to make sure, this is the option for you.

+1
source

Source: https://habr.com/ru/post/1500224/


All Articles