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'">
mplungjan
180k29 gold badges183 silver badges246 bronze badges
asked Apr 19, 2018 at 13:37
reswe teryuio
1171 gold badge1 silver badge8 bronze badges
-
@mahan - no need to change all our clicks to a button. It does not change the script in any waymplungjan– mplungjan2018年04月19日 13:53:23 +00:00Commented 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.Steve Hansell– Steve Hansell2018年04月19日 13:53:24 +00:00Commented 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 anyHuangism– Huangism2018年04月19日 14:03:58 +00:00Commented Apr 19, 2018 at 14:03
3 Answers 3
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'">
answered Apr 19, 2018 at 13:39
mplungjan
180k29 gold badges183 silver badges246 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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'">
answered Apr 19, 2018 at 13:40
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
1 Comment
reswe teryuio
Not work when use
var image = image_pack_val.match(/[^']+/)[1] for get element 2Simply 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'">
answered Apr 19, 2018 at 13:39
phuzi
13.3k4 gold badges31 silver badges66 bronze badges
1 Comment
mplungjan
beat you by 20 seconds
lang-js