javascriptxpathxpath-2.0

how to fill input value onclick via xpath


i want to fill input value with click function, like this

<script>
function inputfillclick() {
document.getElementById('inputidx').value="KuchBhi"
}
</script>
 
 <input type="text" id="inputidx" name="inputidx" />
 <button class="button" onclick="inputfillclick()">Fill Now</button>
 

but the problem is i want do this on other page where the input field does not have id, i want to do this via xpath, is there any way?

<input maxlength="140" step="" enterkeyhint="done" autocomplete="off" type="password" class="uni-input-input">

and xpath is

//input[@type='password']

full xpath

/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view/uni-view[3]/uni-view[2]/uni-view[2]/uni-input/div/input

Solution

  • You can use the document.evaluate() method to select the input element using its XPath expression and then set its value using the value property.

      function inputfillclick() {
      var xpath = "//input[@type='password']";
      var inputElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      if (inputElement) {
        inputElement.value = "KuchBhi";
      } else {
        console.log("Input element not found.");
      }
    }
    

    In this code, the document.evaluate() method selects the first input element with a type attribute set to 'password' using the given XPath expression. If such an element is found, its value property is set to 'KuchBhi'. If no input element is found, the code logs a message to the console.

    You can call the inputfillclick() function using a button or any other event handler on the page where you want to fill the input field.