Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an address form and I want to have a select box for states if the country is the U.S. and change it to a textbox if it's a foreign country so that the state/province can be typed in.

I generate the code in PHP (such as the states select and country select) and I was thinking of outputting both the select and textbox and initially hiding and disabling the textbox, then if the user changes the country unhide and enable the textbox and hide and disable the select.

My question is, is it valid if both inputs have the same name, assuming one of them will be disabled when the form is submitted?

As a bonus question, is there a better way of doing this?

like image 267
Nate Avatar asked Sep 03 '13 01:09

Nate


2 Answers

Yes, it is possible and it is the best way to do this, since disabled inputs are not sent along in the request and it generates a valid and semantic HTML.

As show in w3:

When set, the disabled attribute has the following effects on an element:

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

[...]

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

like image 148
fotanus Avatar answered Oct 27 '22 01:10

fotanus


Assuming you use jQuery, you could 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 an option for you.

like image 42
Doggo Avatar answered Oct 27 '22 02:10

Doggo