Home > Software engineering >  Make an image alt attribute value as a form field value
Make an image alt attribute value as a form field value

Time:04-23

I want to add the alt value of the image as a form field value. How to do that with JS or Jquery?

Thank you

<img src="x.jpg" alt="grab me" id="ok" />

<form action="/#wpcf7-f1352-o1" method="post"  novalidate="novalidate" data-status="init">
  
<span ><input type="text" name="iamge-alt" value="" size="40"  aria-invalid="false"></span>

<input type="submit" value="OK" >
</form>

CodePudding user response:

.getAttribute() to grab alt property and then .forms[0] the first <form> and .elements[0] first form control (<input>) to the .value property.

const alt = document.querySelector('img').getAttribute('alt');

document.forms[0].elements[0].value = alt;
<img src="x.jpg" alt="grab me" id="ok" />

<form action="/#wpcf7-f1352-o1" method="post"  novalidate="novalidate" data-status="init">
  
<span ><input type="text" name="iamge-alt" value="" size="40"  aria-invalid="false"></span>

<input type="submit" value="OK" >
</form>

  • Related