Christiana Mckro
Christiana Mckro

Reputation: 3

How to create a customizable link input in HTML?

I am using this link to create an QR generator on my HTML page:

<img id="qrimg" src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=2|99|XXX">
<input type="number" id="value">
<button type="submit" name="generate">Generate QR</button>

Please help me, when user fill value into the input box then hit Submit button, the link of image should change from XXX to user's input and generate new QR image.

Upvotes: 0

Views: 60

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36584

On the click you can split() src of image by | and change the last element of array to input value and then again join() by |

const img = document.querySelector('#qrimg');
const input = document.querySelector('input')


document.querySelector('button').addEventListener('click',(e) => {
  let src = img.src.split('|');
  src[src.length-1] = input.value;
  img.src = src.join('|')
  console.log(img.src)
})
<img id="qrimg" src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=2|99|XXX">
<input type="number" id="value">
<button type="submit" name="generate">Generate QR</button>

Upvotes: 1

mplungjan
mplungjan

Reputation: 178285

Just save the URL prefix in a var.

I also made the button a button and gave everything an ID

const img = document.getElementById("qrimg");
const inp = document.getElementById("value");
const url = img.src.replace("XXX","");
document.getElementById("generate").addEventListener("click",(e) => {
  e.preventDefault(); // if you keep the type=submit
  let val = inp.value;
  if (val) img.src=url+val;
})
<img id="qrimg" src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=2|99|XXX">
<input type="number" id="value">
<button type="button" id="generate">Generate QR</button>

Upvotes: 0

Related Questions