HTML Form: Make div as submit button - javascript

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 e.g. 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);
// e.g.
/*
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>

Related

Working JQuery Script not working after ajax post response

I'd really appreciate any help!
I have a working jquery script. When a div is clicked, it updates the css class to active and executes a working ajax response.
I also have a filter functionality that works too. When a checkbox is ticked it calls a new list of div's from mysql with all the same class properties. However, when any of these new div's are clicked the ajax response doesn't work. If anyone could help I would be incredibly grateful!
HTML:
<div id="result" class="results">
<div class="w-embed"><img src="images/loader.gif" id="loader" width="" "200px"="" style="display:none;">
<?php
$sql="SELECT * FROM `posts`";
$result=$con->query($sql);
while($row=$result->fetch_assoc()){
?>
<div class="c-card" data-id="<?=$row['id'];?>">
<h1 class="s-h2">
<?=$row['title'];?>
</h1>
<!-- <div class="s-para m-light m-small"><?=$row['description'];?></div> -->
<div class="c-stats">
<div class="s-stat">Pay:
<?=$row['pay'];?>
</div>
<div class="s-stat">Deadline:
<?=$row['deadline'];?>
</div>
<div class="s-stat">Location:
<?=$row['location'];?>
</div>
<div class="s-stat">Cat:
<?=$row['category'];?>
</div>
</div>
<p class="s-para">
<?=$row['description'];?>
</p>
Find Out More
</div>
<?php }?>
</div>
</div>
Javascript:
<script>
$('.c-card').on('click', function(event){
event.preventDefault();
$('.c-card').removeClass('active'); //Removes class to all
$(this).toggleClass('active'); //Applies class
var action = 'data';
var dataId = $(this).data("id");
$.ajax({
type:"POST",
url:"ajax/selected.php",
data:{action:action,id:dataId},
success: function(response){
$("#jobber").html(response);
$("#changeme").text("altered");
}
});
});
</script>
This is the outputted response from the filters:
'<div class="c-card" data-id="'.$row['id'].'">
<h1 class="s-h2">'.$row['title'].'</h1>
<div class="c-stats">
<div class="s-stat">Pay:'.$row['pay'].'</div>
<div class="s-stat">Deadline:'.$row['deadline'].'</div>
<div class="s-stat">Location: '.$row['location'].';</div>
<div class="s-stat">Cat: '.$row['category'].'</div>
</div>
<p class="s-para">'.$row['description'].'</p>
Find Out More
</div>';
So my question is how do i make the new divs (called from the filter) to continue to be triggered and change class + execute the ajax query.
Thanks so much in advance!
I have been thought your actual problem was the ajax response is getting null.
<div class="c-card" data-id="<?=$row['id'];?>">
You are using the data-id attribute in the HTML section. But the script handles the id attribute using for getting the id. So the id is getting null for ajax call, Please use the below code or change the data-id attribute to id in the HTML section as you like.
var action = 'data';
var dataId = $(this).data("data-id");
"id" and "data-id" are different attributes for HTML. Please use same attributes in HTML and script
maybe because there is no html(div|| p || span ||...) element that have id of id="jobber"

How can I use jquery to append a div for me which also includes all of it's nested divs as well?

When a user creates a product, I want that product to be broadcasted to all other users and dynamically added to their screens. So far the broadcast aspect works amazingly.
But how can I dynamically add in this '.product' class, as well as all of a nested divs in an easy way? At the moment the only thing I can think of is copying and pasting all of it's divs in a jquery variable and adding it that way- there must be an easier way.
Here is where products are first loaded in when the page loads
<div class="product" id="{{$product->id}}">
<div class="product-image"><img src="/imgs/products/{{$product->type_id}}.png"></div>
<div class="product-content">
<div class="product-title" id="product-title">
{{ strtoupper(\App\ProductType::where('id', $product->type_id)->first()->name)}}
</div>
<div class="product-price">PRICE PER UNIT: <div class="price-value" id="price">{{$product->price}}</div> EXENS</div>
<br/>
QUANTITY: <div class="quantity-value" id="quantity">{{$product->quantity_available}}</div>
#if(strpos(\App\Group::where('id', $player->group_id)->first()->options, "\"showName\":true") !== false)
<br/>
SELLER: <div class="seller" id="seller">{{\App\User::where('id',$product->seller_id)->first()->name}}</div>
#endif
<br/>
PRICE: <div class="total-price" id="total-price">{{$product->price * $product->quantity_available}}</div>
<form class="buy-product-form" action="/UoE/buy-product/{{$product->id}}" method="POST">
{{csrf_field()}}
<button class="pull-right btn btn-primary">BUY NOW</button>
</form>
</div>
</div>
When the event is received the only way I can think of doing it as:
var productToAdd="<div class='buy-product-form'><div id='price'></div> " +
"" +
"" + //insert a massive string here containing all the other aforementioned sub-divs
"" + //And populate with json data
"" +
"</div>";
$('.content').append(productToAdd);
My solution was to take the entire code posted in the question and do make it as a one big HTML tag. That way my JS function can append the page with a HTML product div and it will already be bound with the necessary event listeners.

Copy HTML from element, replace text with jQuery, then append to element

I am trying to create portlets on my website which are generated when a user inputs a number and clicks a button.
I have the HTML in a script tag (that way it's invisible). I am able to clone the HTML contents of the script tag and append it to the necessary element without issue. My problem is, I cannot seem to modify the text inside the template before appending it.
This is a super simplified version of what I'd like to do. I'm just trying to get parts of it working properly before building it up more.
Here is the script tag with the template:
var p = $("#tpl_dashboard_portlet").html();
var h = document.createElement('div');
$(h).html(p);
$(h).find('div.m-portlet').data('s', s);
$(h).find('[data-key="number"]').val(s);
$(h).find('[data-key="name"]').val("TEST");
console.log(h);
console.log($(h).html());
console.log(s);
$("div.m-content").append($(h).html());
<script id="tpl_dashboard_portlet" type="text/html">
<!--begin::Portlet-->
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<!--begin::Form-->
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
<!--end::Portlet-->
</script>
I'm not sure what I'm doing wrong here. I've tried using .each as well with no luck. Both leave the value of the span tags empty.
(I've removed some of the script, but the variable s does have a value on it)
You have two issues here. Firstly, every time you call $(h) you're creating a new jQuery object from the original template HTML. As such any and all previous changes you made are lost. You need to create the jQuery object from the template HTML once, then make all changes to that object.
Secondly, the span elements you select by data-key attribute do not have value properties to change, you instead need to set their text(). Try this:
var s = 'foo';
var p = $("#tpl_dashboard_portlet").html();
var $h = $('<div />');
$h.html(p);
$h.find('div.m-portlet').data('s', s);
$h.find('[data-key="number"]').text(s);
$h.find('[data-key="name"]').text("TEST");
$("div.m-content").append($h.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl_dashboard_portlet" type="text/html">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
</script>
<div class="m-content"></div>
In my case only this is working:
var template = $('template').clone(true, true); // Copies all data and events
var $h = $('<div />');
$h.html(template);
$h.find('.input-name').attr('value', "your value here"); // Note: .val("your value here") is not working
$('.list').prepend($h.html());

jQuery select another element with certain class in same parent

let say i have this div
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)
I tried using:
$("#button").on("click",function(){
var ReturnedText = $(this).parent(".lookAtMe").text();
console.log(RetrunedText);
});
But the console log would retruned (empty string).
Where did i do wrong? please help. Thankyou very much.
Because there is n o parent with that class. You need find().
Actually you need to write
var ReturnedText = $(this).parent().find(".lookAtMe").text();
$("#button").on("click",function(){
var ReturnedText = $(this).parent().find(".lookAtMe").text();
console.log(ReturnedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>

How to dynamically append text to a modal?

I have this html
<div class="col-md-6">
<div class="jumbotron">
read more...
<div class="read-more hidden">
<p>1 - THE TEXT I NEED TO APPEND TO THE MODAL</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="jumbotron">
read more...
<div class="read-more hidden">
<p>2 - THE TEXT I NEED TO APPEND TO THE MODAL</p>
</div>
</div>
</div>
This is the section of the modal where I need to append the text within the element with the class read-more
<div class="modal-body">
<!-- TEXT FROM THE READ MORE CLASS ELEMENT NEEDS TO BE APPENDED HERE -->
</div>
And this the jQuery function I have so far where I am adding a data-attr for every element with the class read-more:
jQuery(document).ready(function($) {
var $readmore = $('.read-more');
var $readmoreParagraph = $('.read-more p');
$readmore.each(function(i, el) {
var $dataAttr = $(el).attr('data-attr', i);
});
});
To get this output:
<div class="read-more" data-attr="0">
<p>THE TEXT I NEED TO APPEND TO THE MODAL</p>
</div>
TL;DR:
I need to append to the modal-body the text on the <p> under the div with the class read-more.
Any suggestions?
UPDATE
I did this:
$('#myModal .modal-body').append($("[data-attr="+i+"] > p"));
But as a result I am getting this in the modal-body:
1 - THE TEXT I NEED TO APPEND TO THE MODAL
2 - THE TEXT I NEED TO APPEND TO THE MODAL
Use the show.bs.modal event to change the contents of the body each time it is shown.
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget), // Button that triggered the modal
content = button.siblings('.read-more').html(),
modal = $(this);
modal.find('.modal-body').html(content);
});
See http://getbootstrap.com/javascript/#modals-related-target
From what I understood after the comments, I suggest the following:
After triggering the modal, get the content of the read-more you would like, and just use that text and place it at the modal (not appending, an append adds to the object).
Like this (example for the id 1):
$('#myModal .modal-body').html($("[data-attr=1] > p").text());

Categories