0

For this my code, when click on GET DATA i want to get element[0] ===> 1.png , how to do ?

function xx_fn() {
  var image_pack_val = document.getElementById("image_pack").value;
  var image = [image_pack_val][0]
  alert(image);
}
<div onclick="xx_fn()">
  GET DATA
</div>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">

3
  • @mahan - no need to change all our clicks to a button. It does not change the script in any way Commented Apr 19, 2018 at 13:53
  • @Huangism Your comment itself isn't helpful. If you can't add anything in a positive manner, don't bother posting. Commented Apr 19, 2018 at 13:53
  • @SteveHansell the google link has info on how to split a string which is helpful info, a bit of research is required for someone how is asking a question and this one doesn't show any Commented Apr 19, 2018 at 14:03

3 Answers 3

1

using replace and split

you may want to use a button instead of clicking a div

function xx_fn() {
  var image_pack_val = document.getElementById("image_pack").value;
  var image = image_pack_val.replace(/'/g,"").split(",")[0]
  console.log(image);
}
<div onclick="xx_fn()">
  GET DATA
</div>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">

Sign up to request clarification or add additional context in comments.

Comments

1

You could match the data and take the nth element of it.

function xx_fn() {
  var image_pack_val = document.getElementById("image_pack").value,
      allImages = image_pack_val.match(/[^',]+/g);

    console.log(allImages);
}
<button onclick="xx_fn()">GET DATA</button>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">

1 Comment

Not work when use var image = image_pack_val.match(/[^']+/)[1] for get element 2
0

Simply remove single quotes ' and then split on the comma ,.

function xx_fn() {
  let imageNameList = document.getElementById("image_pack").value;

  // remove all single quotes `'` and split on commas `,`
  let imageNames = imageNameList.replace(/'/g, "").split(",");
  console.log(imageNames[0]);
}
<div onclick="xx_fn()">
  GET DATA
</div>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">

1 Comment

beat you by 20 seconds

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.