mpdc
mpdc

Reputation: 3560

Remove some text from hidden input's value on select change

I am building a form where I take people's address details. To begin with State/County is not required, however, if they choose the country Australia, Canada or USA, it is.

Here is my code with demonstrates this: the required fields are sent to a PHP script via <input name="required" value="address,town,country,post_code"> for processing, and State/County is appended to this list when one of the aforementioned countries is selected:

$("select[name=country]").change(function() {
    if ($(this).val() == "USA" || $(this).val() == "AUSTRALIA" || $(this).val() == "CANADA") {
        alert("You have selected '" + $(this).val() + "'.\nPlease ensure you enter your State.");
        $("input[name=state_county]").focus();
        $("input[name=required]").val($("input[name=required]").val() + ",state_county");
    } else {
        // How do I remove it, though?
    }
});

My question comes from when someone unselects one of those three countries. How do I remove a certain part of an input's value, i.e. how do I remove ,state_county from name="required"?

Upvotes: 0

Views: 38

Answers (1)

Tony DeStefano
Tony DeStefano

Reputation: 829

If someone chooses USA and then AUSTRALIA and then CANADA, your input field is going to be appended with ,state_county three times.

Try this:

<script>

    $("select[name=country]").change(function() {

        // Save the initial value in a temporary variable
        var value = $("input[name=required]").val().replace(',state_county', '');

        if ($(this).val() == "USA" || $(this).val() == "AUSTRALIA" || $(this).val() == "CANADA") {
            alert("You have selected '" + $(this).val() + "'.\nPlease ensure you enter your State.");
            $("input[name=state_county]").focus();
            $("input[name=required]").val(value + ',state_county');
        } else {
            $("input[name=required]").val(value);
        }
    });

</script>

That will remove the ,state_county every time and then add it on only if it is needed.

Upvotes: 1

Related Questions