简体   繁体   中英

Form how to get div element from span

I am having form for uploading picture, which contains many divs. I want to get the name of that picture which is inside div containing span.

<form class="dropzone dz-clickable dz-started" action="form_upload.html">
<div class="dz-preview dz-processing dz-error dz-complete dz-image-preview">
<div class="dz-image">
//skipped as it is showing complete image 
</div>
<div class="dz-details">
   <div class="dz-size">
      80kb
   </div>
   <div class="dz-filename">
     <span data-dz-name="">aust_ews.PNG</span>
   </div>
 </div>

</div>

</form>

I'm trying to get the aust_ews.PNG but failed to get.

Here is my tries:

var e =$(".dz-filename").val();//failed

var e =$("#form dz-filename").val();//failed

.val() fetches the value (think of input fields), but you need the contents between the tags - you need .html() .
Apart from that, you need to fetch the contents of the inner span , not the outer div - otherwise, the result would be <span data-dz-name="">aust_ews.PNG</span> .

In code:

var e = $('.dz-filename span').html();

If it still doesn't work, verify that you have the jQuery library loaded. You can check in the console by simply typing in $ and pressing enter. It should state something like "function".

It's good practice to execute things like that inside ready . Just to be sure it'll work in the way you're expecting:

$(document).ready(function()
{
  var e = $('.dz-filename span').html();
});

About ready see more on jquery.com manual .

Instead of

$(".dz-filename").val();

try

$(".dz-filename").text();

As what ever html or text present inside the div is not the value, it is the content of that div. And you can get it by using html() or text().

val() works only with input elements like text, select, radio, checkbox as it searches for the value attribute and return it.

Working Fiddle

Please check this. It's working here. I have checked with the alert.

You just need to pass your code inside $(document).ready(function(){} function.

 $(document).ready(function(){ var e = $(".dz-size").html(); alert(e) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <form class="dropzone dz-clickable dz-started" action="form_upload.html"> <div class="dz-preview dz-processing dz-error dz-complete dz-image-preview"> <div class="dz-image"> //skipped as it is showing complete image </div> <div class="dz-details"> <div class="dz-size"> 80kb </div> <div class="dz-filename"> <span data-dz-name="">aust_ews.PNG</span> </div> </div> </div> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM