Search code examples
javascripthtmljquery-selectors

How to insert text to both text fields - small code


I wrote a code so I can autofill a webpage, the issue is that i want it to autofill 2 text fields but my code is only filling the first one. My knowledge is very limited so I don't know how to autofill the second text field with a different phrase.

let question = document.querySelector('crowd-form tr');
if (question) {
  let text = question.textContent.trim();
  let input = question.querySelector('input');
  if (input) {
    // Does text contain "man united"?
    if (text.includes('man united')) input.value = 'Manchester United F.C.';
    // Does text contain "manchester united"?
    else if (text.includes('manchester united')) input.value = 'Manchester United F.C.';
  }
}
In the example above, I'm able to insert the team name "Manchester United F.C." but I would like it to fullfill the other field with "Old Trafford". Can anyone help me?


Solution

  • I created below snippet. Can you please have a look and check if it works as per your requirement.

    // Instead of using querySelector() I directly added the text just for an example.
    let text = 'man united is too shit for ronaldo';
    
    // Reference of first textbox.
    let firstInput = document.getElementById('firstTextbox');
    // Reference of second textbox.
    let secondInput = document.getElementById('secondTextbox');
    
    // Assigning the value in firstTextbox based on the question text.
    if (firstInput) {
      firstInput.value = text.includes('man united') ? 'Man United F.C.' : text.includes('manchester united') ? 'Manchester United F.C.' : '';
    }
    
    // Assigning the value in secondTextbox.
    if (secondInput) {
      secondInput.value = 'Old Trafford';
    }
    <input id="firstTextbox" type="text"/>
    <input id="secondTextbox" type="text"/>