Jquery trigger click then fill in input - javascript

I have a table row that when clicked should trigger a click event on page that opens a div. once this div is open, i need #poId to be populated with given id.
$('tr').click(function(){
var id = $(this).attr('id');
$('#purchase\\.exist').trigger('click');
//What goes here?
});
the page that results from the click is:
<input type='text' id='poId' name='poId'>
basically i need to know what i can use to fill poId with click automatically. in layman's terms
$('tr').click(function(){
var id = $(this).attr('id');
//Open page as a result of trigger
//paste the variable id in the poId input
});
Added fiddle:
This fiddle is completely stripped down but the idea is a user clicks on the word question. a table appears with two rows. when a user click on the table row, the purchase div is opened and the input needs to be populated with the id of the tr clicked.
Fiddle
I know there are other ways to do this without trigger, but opening the div actually entails a bunch of other things (ajax functions and such) before the div is opened, so just simply opening the purchase div wont work

To populate poId with the value of the ID of the tr that was clicked on (which I think is what you're asking):
$('tr').click(function(){
$("#poId").val(this.id);
$('#purchase').trigger('click');
});
(I am assuming that "#purchase\.exist" was a typo of some sort?)

$(function() {
$('.hide').hide();
$('tr').click(function() {
var id = $(this).attr('id');
$('#poId').val(id);
// the second argument is an array of parameters that will be passed to the function
$('#purchase').trigger('click', [id]);
});
// the first argument of function `click` receives is the event, the next are the arguments passed from the trigger
$('li').click(function(e, id) {
var liID = $(this).attr('id');
var div = $('#div_' + liID)
div.show();
div.find('input').val(id)
});
});
li:hover {
cursor: pointer;
}
tr:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id='purchase'>Purchase</li>
<li id='question'>Question</li>
</ul>
<div id='div_purchase' class='hide'>
<input type='text' id='poID' name='poID'>
</div>
<div id='div_question' class='hide'>
<table id='myTable'>
<tr id='12345'>
<th>12345</th>
</tr>
<tr id='45678'>
<th>45678</th>
</tr>
</table>
</div>

Related

input radio does not hide content when unchecked

input radio does not hide content when unchecked, i can't make the content be hidden when the radio input is unchecked
how can I hide the content of the unmarked radio input?
clicking on another radio input is unchecked but does not hide the content
$('#alternar').click(function () {
$('#prueba').toggle();
});
$('#alternarx').click(function () {
$('#pruebax').toggle();
});
/* commented out because this select doesn't appear in the HTML:
$(".placeholder").select2({
placeholder: "Make a Selection",
allowClear: true
});
*/
function uncheckAndCheck(event) {
// gets all radios with the name prefix like 'custom-radio-'
// and uncheck all of them
document.querySelectorAll("input[type='radio'][name^='custom-radio-']").forEach(radio => {
radio.checked = false;
});
// checks the radio that triggered the click event
event.target.checked = true;
}
#prueba{
display:none
}
#pruebax{
display:none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="radio" class="new-control-input" name="custom-radio-1" id="alternarx" onclick="uncheckAndCheck(event)"/>
<div id="prueba"> Content1 </div>
<input type="radio" class="new-control-input" name="custom-radio-2" id="alternar" onclick="uncheckAndCheck(event)"/>
<div id="pruebax"> Content2 </div>
George's solution works, but is reliant upon the HTML never changing. If you add any element between the radio button and the div, it will break the functionality.
To answer your question related to JavaScript:
It's unnecessary to check and uncheck the other radio inputs. You just need to give them the same name attribute.
Second, you're .toggle()ing the divs on click. That might be why they're acting strangely. You're not checking if the radio button is selected or not, and that's going to result in them toggling even when you click them when they're already selected. Luckily, you can just listen for them to change states.
Third, you can hold a selector for the target of the radio button you want to show/hide in a data attribute, and use one function for all of this.
Fourth, why mix inline onclick attributes, when you're using jQuery? Just listen for the event using the built-in listeners in jQuery.
//jQuery shorthand for $(document).ready(function(){ to be sure your DOM has loaded:
$(function() {
//run this on page load, too. Necessary because browsers will remember which one is checked on a page *refresh*, and hides the target divs initially when nothing is checked:
$checkedRB = $(".rbToggleDiv:checked");
if($checkedRB.length > 0) {
toggleVisibleDivs($checkedRB);
} else {
toggleVisibleDivs(false);
}
//both radio buttons have the same class as well, so you can listen for either of them to change states:
$(document).on("change", ".rbToggleDiv", function(e) {
//this = radio button that has changed
var $thisRB = $(this); //turn it into a jQuery object
if($thisRB.prop("checked")) { //only do something if this RB is checked
toggleVisibleDivs($thisRB);
}
});
function toggleVisibleDivs($targetRB) {
if ($targetRB === false) { //no target sent in
//hide all
$(".pruebaDiv").hide(); //hide all divs
} else { //target sent in
if ($targetRB.data("target-div")) { //make sure the data is set
var targetSelector = $targetRB.data("target-div"), //grab the string from the data object
$targetDiv = $(targetSelector); //use it to select the target div
if ($targetDiv.length > 0) { //make sure the div is selected
//hide all divs with the same class:
$(".pruebaDiv").hide();
//then, show only the one you want visible, the $targetDiv:
$targetDiv.show();
} else {
console.error("Div not found!", targetSelector);
}
} else {
//data not set:
console.error("Data was not set.");
}
}
}
});
.pruebaDiv {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- if they have the same names, they will act as a radio button list, and will act accordingly. Also, you should really choose more descriptive IDs and names: -->
<input type="radio" class="rbToggleDiv" name="rb-toggle-div" id="alternarx" data-target-div="#prueba" />
<input type="radio" class="rbToggleDiv" name="rb-toggle-div" id="alternar" data-target-div="#pruebax" />
<!-- for the sanity of the user, I've moved these two divs next to each other below the radio buttons so they don't move around: -->
<div class="pruebaDiv" id="prueba"> Content1 </div>
<div class="pruebaDiv" id="pruebax"> Content2 </div>
This is actually possible entirely with CSS. You can use the adjacent sibling combinator +, which affects an element immediately following the first.
#prueba{
display: none;
}
#pruebax{
display: none;
}
input:checked + #prueba,
input:checked + #pruebax {
display: block;
}
<input type="radio" class="new-control-input" name="custom-radio-1" id="alternarx" onclick="uncheckAndCheck(event)"/>
<div id="prueba"> Content1 </div>
<input type="radio" class="new-control-input" name="custom-radio-2" id="alternar" onclick="uncheckAndCheck(event)"/>
<div id="pruebax"> Content2 </div>

Jquery not detect click after append of element

i've made a sortable list with html5sortable library, where user have a category, where can add products inside, and can add other categories where to add products too.
The first one category is already displayed, and work fine when adding products, but if I add another category I can't add product on this category.
I've tried with "on" method instead of "click", as it should work on element created dinamically, but I think I'm using it in the wrong way.
Here is the HTML
<div class="container-categorie">
//THIS IS A CATEGORY ITEM, WITH ADD PRODUCT BUTTON INSIDE
<div class="category" id="categoria-1">
<input type="text" class="input-categoria" placeholder="NAME CATEGORY" autofocus="autofocus">
<div class="list" id="list-1">
//products will be added here
</div>
<div class="item-products add-product-container">
<div align="center" class="add-product-btn" id="addproduct-1">
+ add product
</div>
</div>
</div>
//END OF CATEGORY ITEM
<div class="add-categoria-container">
Nuova categoria
</div>
</div>
And here is the js code:
var i = 2;
$(".categoria").on('click', function() {
//to delegate the click I applied this event to "add product" button's container
});
//This add a product inside category div
$(".add-product-btn").click(function() {
var id_btn = $(this).attr("id");
var single_id = id_btn.substring(id_btn.indexOf("-") + 1);
$("#list-"+single_id).append('<div class="item-products">prova</div>');
sortable('.list');
});
//This should add a new category inside "container-categorie", with an "add product"
//button inside, to add products inside this new category
$(".add-categoria-container").click(function() {
$(".sortable-categorie").append('<div class="categoria"><input type="text" class="input-categoria" placeholder="NOME CATEGORIA PRODOTTI" autofocus="autofocus"><div class="list" id="list-'+i+'"></div><div class="item-products add-product-container"><div align="center" class="add-product-btn" id="addproduct-'+i+'">+ Aggiungi prodotto</div></div></div>');
sortable('.sortable-categorie');
});
Jquery can't listen to dynamically generated Elements directly, what you can do is you can provide parent element which is already there in DOM listen to them.
$("element which is already in DOM").on('click',"element to listen to", function() {
//Code here
});
$(".container-categorie").on('click',".categoria", function() {
//Code here
});
or you can directly listen to the body instead, but it is not preferable.
For Ref : https://api.jquery.com/on/#on-events-selector-data-handler
Try this
$(document).on('click',".your_class_name", function() {
//to delegate the click I applied this event to "add product" button's container
});
JQuery has no virtual DOM like Angular or React. That means JQ can't "see" the dynamically generated element. What you can do is using a onclick="functionYouWantToTrigger(someParameters)" directly in the HTML tag.

jQuery dynamic insert row for expand/collapse

I have a table structure as follows;
<tr>
<td><div class="icon-chevron-right"></div></td>
<td><div>List 1</div></td>
</tr>
<tr>
<td><div class="icon-chevron-right"></div></td>
<td><div>List 2</div></td>
</tr>
Now on click of the icon image (chevron), I want the details row to be displayed immediately below the clicked row (It should be a tr containing child table). This should be inserted/appended dynamically on click of any of the list row.
How do I do this using jQuery? Any examples for reference would be really helpful..
the following example creates a new tr (if does not exists) containing table element under the tr where the clicked icon exists.
function createChildTable(string)
{
return $('<table>').append(
$('<tr>').append(
$('<td>').append(string)
)
);
}
$('.icon-chevron-right').click(function() {
var details = $(this).closest('tr').next('tr.details');
if (details.length) details.show();
else {
// first time clicked
details = $('<tr>').append( createChildTable('child table details') ).addClass('details');
$(this).closest('tr').after(details);
}
});
Example Link
I'd say there are two main ways to do this, and you'll have to figure out which one is best for you; it depends.
What you're talking about is ADDING a row into the DOM. This is fine in some cases, it depends on what this collapsed row is used for. If you want to be able to remove the collapsed row and add it again, it could make your life difficult if you have to reconstruct all the inner HTML via JavaScript every time.
var collapseHTML = '<tr class="collapse"><td colspan="2">This is my new row</td></tr>';
$('.icon-chevron-right').click(function() {
$('.collapse').remove(); // Deletes all rows that has class "collapse"
collapseHTML.insertAfter( $(this).closest('tr') ); // Inserts what's stored in collapseHTML after "this closest tr"
});
Then, as someone else said, you can solve this by adding those rows from the get go like so:
<tr>
<td><div class="icon-chevron-right"></div></td>
<td><div>List 1</div></td>
</tr>
<tr class="collapse">
<td colspan="2">This is my new row</td>
</tr>
Then, your css should loook something like this:
.collapse {
display: none;
}
.collapse.active {
display: block;
}
This means that when you add the active class to the collapse row, it goes from display: none; to display: block;. This you do via JavaScript/jQuery:
$('.icon-chevron-right').click(function() {
$('.collapse.active').removeClass('active'); // Removes active from all active collapsed rows
$(this).closest('tr').next().addClass('active'); // adds active class to "this closest tr's next element" (which is the collapse row)
});
Hope this helps!

Get the value of an input field within multiple divs when clicking a submit button

How would I go about correctly writing this so that the var input is the value of the content input field within the .overlay div when the submit button is pressed? Keep in mind that there's several .overlay divs, so it needs to be that separate div.
I know how to make it work assuming only 1 div exists, but this isn't the case. My jQuery is as follows:
$('.button').click(function() {
var input = $(this).parents('.overlay')$(input[name=content]).val();
});
My HTML structure (assume this div is duplicated several times on the page):
<div class="overlay">
<input name="content" value="value">
<input type="submit" class="button" value="submit">
</div>
$('.button').click(function() {
var input = $(this).parent().find("input[name='content']").val();
});
should work.
Or, if you can rely on that exact structure:
$('.button').click(function() {
var input = $(this).prev().val();
});
like this
$('.button').click(function() {
var input_val = $(this).parent().find('input:first').val();
alert(input_val)
});
here is ia working demo

Hide or display a button according to row count of a table

i have a HTML table and a button send.
First of all the send button must have this style: style.display="none".
But if the table has at least one row the button should be displayed (block/inline);
I still have no idea how to relate between the table and the button.
I try to use JavaScript but i should think about a function and I don't found any of it to apply at type table. Thinking about CSS still also hard since I cannot find a relation between the table and the button.
A plain, non-jquery equivalent of Lance May's answer would be something like this:
var button = document.getElementById('the-button');
if (document.getElementById('the-table').getElementsByTagName('tr').length > 0){
button.style.display = 'block';
}else{
button.style.display = 'none';
}
You'll need to toggle the visibility of the button when the table is adjusted. Since that can be done in many ways, there's not way to know what is right for you.
For simplicity, give jQuery a try. I will make accessing the elements and modifying the styles much easier than 'vanilla' JavaScript. Also be sure that if you're updating the table after page load (via JavaScript), that you use this whenever you do that.
$(document).ready(function(){
if ($("#table > tr").length > 0)
$("#button").show();
else
$("#button").hide();
});
I hope that helps.
If the Button lies inside a TD which it most def. does then simply access it via:
td input {
display: none;
}
You even can define the stlye with a advanced selector like this in CSS3
input[type="button"] {
display: none;
}
I wrote about this at my blog.
With JavaScript you can grab the input field with
var myInput = document.getElementsByTagName('input');
myInput.style.display = none;
To select your input inside a tr, use something like
myTableRow.childNodes[0];
<html>
<head>
<title>whatever</title>
<style type="text/css">
.hidden {
display: none;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var $t = $('table');
var $h = $t.find('thead');
var $b = $t.find('tbody');
var $s = $('#send');
// the "add" button appends a new row
// into the table body; if the body
// transitions from empty, the "send"
// button is displayed
$('#add').bind('click', function ()
{
$b.append(newRow());
if (1 == $b.find('tr').length)
$s.removeClass('hidden');
});
// the remove button removes the last
// row from the table body (if there's
// any); if the body transitions to
// empty, the "send" button is hidden
$('#remove').bind('click', function ()
{
$b.find('tr:last').remove();
if (0 == $b.find('tr').length)
$s.addClass('hidden');
});
// generates a table row; this demo
// impl. just copies the heading row
var newRow = function ()
{
return $h.find('tr').clone();
};
});
</script>
</head>
<body>
<table border="1">
<thead>
<tr><td>foo</td><td>bar</td></tr>
</thead>
<tbody>
</tbody>
</table>
<input type="button" id="add" value="add" />
<input type="button" id="remove" value="remove" />
<input type="button" id="send" value="send" class="hidden" />
</body>
</html>

Categories

Resources