Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery, Create multiple html Element with ascending IDs?

Here is what is needed to do:

<input type="text" id="main" placeholder="Put URL Here">

Every time the User Presses enter (or a Button on side of screen) I need Jquery to create:

<input type="hidden" id="url_1" readonly value='<-- input value from main-->'>
<!-- user adds another to #main -->
<input type="hidden" id="url_2" readonly value='<-- input value from main-->'>
<!-- etc -->

Here is what I got So far (only using HTML)

<figure class="mb-4">
<input type="text" name="" id="" placeholder="Image URL">
<button id="addimage">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>

For the Upload Image button, It submits a Image to my PHP upload image, and just returns the URL to the image

like image 474
user655355 Avatar asked Jan 24 '23 07:01

user655355


2 Answers

This will append the hidden inputs to the end of your <form> tag. It also keeps an array of urls in case that's useful. For this snippet, it shows the array in a div.

let urls = [], limit = 2, main, addButton, resetButton
window.addEventListener('load', () => {
  main = document.querySelector('#main'),
  addButton = document.querySelector('[data-url-saver]'),
  resetButton = document.querySelector('[data-url-reset]');
  addButton.addEventListener('click', () => saveURL())
  resetButton.addEventListener('click', () => reset())
  })

const saveURL = () => {
  let u = main.value;
  urls.push(u);
  let h = `<input type="hidden" data-url-hidden id="url_${urls.length}" readonly value=${u} />`
  document.querySelector('form').insertAdjacentHTML('beforeend', h);
  main.value = "";
  let de = document.querySelector('#debug');
  de.innerHTML = urls.join(", ");
  if (urls.length >= limit) {
    addButton.setAttribute('disabled', 'disabled');
    main.setAttribute('disabled', 'disabled');
    main.setAttribute('placeholder', 'Maximum URLs accepted')
  }
}

const reset = () => {
  urls = [];
  document.querySelectorAll('[data-url-hidden]').forEach(e => e.parentNode.removeChild(e));
  addButton.removeAttribute('disabled');
  main.removeAttribute('disabled');
  document.querySelector('#debug').innerHTML = "";
}
<form>
  <input type="text" id="main" placeholder="Put URL Here">
  <button data-url-saver type='button'>enter</button>
  <button data-url-reset type='button'>reset</button>
</form>

<div id='debug'></div>
like image 178
Kinglish Avatar answered Jan 30 '23 10:01

Kinglish


Create a div for hidden urls like

<div id="urls"></div>

try in jquery

var counter = 1;
$('#main').keypress(function (e) {
 if(e.which== 13){  // enter key code
    var url = $('#main').val();
    $('#urls').append('<input type="hidden" id="url_'+ counter +'" readonly value="' + url + '" >');
    $('#main').val(''); //clearing the input
    counter++;
  }
});   
like image 42
shubham kakade Avatar answered Jan 30 '23 11:01

shubham kakade