Search code examples
javascriptstringfunctionalter

Data entered alters string length


I am new to JavaScript and I have been doing some work creating a form in HTML and JavaScript. In this work I have been trying to limit the string of a field depending on the text entered into a previous field.

What i have been trying is if the country 'Australia' is entered into the 'Country' text box than the 'Postcode' text box is limited to only 4 numbers (the Australian postcode standard)

i have done this much of a function so far:

document.getElementById('txtcountry').onblur = function postcode()
{
var country = document.getElementById('txtcountry').value;
if (country == "Australia" || category == "australia")
{
    document.getElementById('txtpostcode').maxLength = 4;
    }
    else
{
    document.getElementById('txtpostcode').maxLength = 9;
}
}

Here is the segment of the initial HTML that i have to use the function with:

<b>Postcode:</b> <input type="text" id="txtpostcode" name="postcode">
<br>
<b>Country:</b> <input type="text" id="txtcountry" name="country">

I am calling the function using :

<form name="rego" action="submit.htm" onsubmit="return !!(validateText() & validateCheckBoxes(this) & validateRadioButton() & validateEmail() & populateInstitution() & postcode());" method="POST">

Any help would really be appreciated!

UPDATE: i have updated my function to the finished function after some help as it doesn't seem to work and i need some further help with it


Solution

  • Are you trying to set the maxLength property:

    var pc = document.getElementById('txtpostcode');
    pc.maxLength = 4;
    pc.value = pc.value.substr(0,4); // remove any extra characters already entered
    

    ...and then add an else condition to set the maxLength to whatever your default is for other countries.

    You would then call your postcode() function from the blur event of your txtcountry field.

    EDIT: Note that the function you've shown has an undefined variable category in the second part of the if test - should be country. And as I mentioned already you do need to call the function from somewhere.