简体   繁体   中英

HTML Form: Make div as submit button

I've created a webpage including a folder structure hierarchy using – html/php/js/mysql .

Therefore, I've created a design. It's simply a parent div with the class of folders and inside all folders are listed with an <h2> as the name. Through PHP I've set the folder ID as a custom attribute on each folder div:

<div class="folders">
   <div data-id="12452">
      <h2>Folder 1</h2>
   </div
   <div data-id="12453">
      <h2>Folder 2</h2>
   </div
   <div data-id="12454">
      <h2>Folder 3</h2>
   </div
</div>

Now, I would like to do that when someone clicks on folder one , a get parameter should be set in the url .

So basically the URL:

mywebpage.com/index.php ->'clicks folder' -> mywebpage.com/index.php?folder=12452

I have a couple of ideas how I could achieve that, like creating a hidden form that will be submitted with javascript when clicking a folder div, but I'm not quite sure which way is the best and cleanest.

I appreciate all the help.

You could do something like this, adding a click handler on the parent, and track which child were clicked on, and get its data-id

From there you can eg assign that url to a form and post it using the form 's submit() method

Stack snippet

 document.querySelector('.folders').addEventListener('click', function(e) { if (e.target.closest('div').dataset.id) { var url = "mywebpage.com/index.php?folder=" + e.target.closest('div').dataset.id; console.log(url); // eg /* var form = document.querySelector('form'); form.action = url; form.hidden_field.value = "some value"; form.submit(); */ } }) 
 <div class="folders"> <div data-id="12452"> <h2>Folder 1</h2> </div> <div data-id="12453"> <h2>Folder 2</h2> </div> <div data-id="12454"> <h2>Folder 3</h2> </div> </div> <form id="the_form"> <input type="hidden" name="hidden_field" value=""> </form> 

Since you're using jQuery you could attach a simple click like the following snippet shows.

NOTE: If you want from the h2 to looks like a clickable element you count change the cursor to pointer in your CSS rules like :

.folders h2 {
    cursor: pointer;
}

 $('.folders h2').click(function() { var folder_id = $(this).parent().data('id'); //This line was added just for log purpose console.log('?folder=' + folder_id); //Uncomment the following line that will redirect you with folder "id" as parameter //location.href = '?folder=' + folder_id; }) 
 .folders h2 { cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="folders"> <div data-id="12452"> <h2>Folder 1</h2> </div> <div data-id="12453"> <h2>Folder 2</h2> </div> <div data-id="12454"> <h2>Folder 3</h2> </div> </div> 

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