简体   繁体   中英

how to populate form fields on the basis of other field's value in html using javascript

I want to autopopulate a form element/field value instantly on the basis of another form field value using javascript.

As shown in the figure, if a user fills the choice as "A" then the 'filled' field must automatically be filled with B without refreshing.

Thanks in advance for help :)

Here is a screenshot of how I want it to look:

From what I understand; When a user writes 'A', a javascript should run and put 'B' in the other field.

If so, in my following code, I first placed an onchange function, meaning it will only run when the user clicks away from the textbox (You can instead use an onsubmit and a submit button, I just used this to avoide using a form). It will call the function "autofill()". autofill() has 3 lines of code, the first will search the document for an id "field1" and gets its value and saves it as variable x. The second will compare that to a hard coded character 'A', if it equals A it will then move to the third line where it will place 'B' in the second field with id "field2".

HTML:

<input type='text' id='field1' onchange="autofill()">
<input type='text' id='field2'>

Javascript:

function autofill(){
    var x = document.getElementById('field1').value;
    if(x=='A')
    {
        document.getElementById('field2').value= 'B';
    }
}

You can create multiple 'if' statments to check for other characters, or remove the if statment all together if you want it to show 'B' regardless!

Hope this helped, and don't forget to "check" the right answer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM