for loop doesn't work - what do I do wrong? - javascript

I am new to JavaScript. I would appreciate if you could help me with the code: thanks!
I'm trying to hide the answers to 10 questions and show them when clicked on the right button!
It only shows the last answer when i klick any button!
var ya = document.getElementsByClassName("A");
$(ya).hide();
for (var i = 0; i < 10; i++){
var x = document.getElementsByClassName("idcheck");
var z = x[i].id;
console.log(x[i]);
$(x[i]).click(function() {
var y = document.getElementsByClassName(z);
$(y).show();
});
}
This is the html:
<p>
<button id="B<?php echo $drow['id'];?>" class="btn btn-primary idcheck" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Lösung der Aufgabe!
</button>
</p>
<td><b class="text-success A B<?php echo $drow['id'];?>"><?php echo $brow['answertext'];?></b></td>
</tr>
<?php
}
?>

Your code is way more complicated than it needs to be. If you use jQuery, just stick with jQuery.
$(".A").hide();
$(".idcheck").on("click", function() {
var id = this.id;
$("." + id).show();
});

In your code you've use jQuery as well as bootstrap specific elements. So I'm assuming that you'r page has jQuery.
Please have a look at the following snippet
NOTE: I've cleaned up your HTML structure and removed unnecessary bootstrap specific classes
$('.idcheck') // We select all elements with the given class
.on('click', function() { // We attach a function for the 'click' event
var currID = $(this).attr('id').replace(/^B/i, ''); // We get teh ID fo the clicked buttona and remove 'B' from the start of it to it it's index
$('.B' + currID).show(); // We then use the index and generate a class selector to target the <td> tag to show it
})
.A {
display: none; // Hide the element initially
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<button id="B1" class="btn btn-primary idcheck" type="button">
Button for ID 1
</button>
</td>
<td><b class="text-success A B1">Content for ID 1</b></td>
</tr>
<tr>
<td>
<button id="B2" class="btn btn-primary idcheck" type="button">
Button for ID 2
</button>
</td>
<td><b class="text-success A B2">Content for ID 2</b></td>
</tr>
</table>

1) If you use jquery, use jquery!
2) have a look at scoping in js
$(".A").hide();
$(".idcheck").each(function(){
$(this).click(function() {
$("."+$(this).id).show();
});
});

Related

Having trouble sorting table with JQuery sort method

I am using PHP and JQuery to build a data table, I am using jQuery's .sort() method to sort the table. However, it is not working as excepted.
For the text fields, nothing is changed (except that the rows are rendered again).
For the numeric fields, the table sorts in a really weird manner.
Clearly the ID does not make sense like this? Here is my JavaScript code:
const rows = tbody.find('tr').sort((a, b) => {
let first, second;
if ($(e.target).attr('data-order') === 'asc') {
second = a;
first = b;
$(e.target).attr('data-order', 'desc');
}
else {
second = b;
first = a;
$(e.target).attr('data-order', 'asc');
}
const firstTd = $(first).children().eq($(e.target).attr('data-index') - 1).text();
const secondTd = $(second).children().eq($(e.target).attr('data-index') - 1).text();
// Take care of numbers
try {
return firstTd - secondTd;
}
catch (e) {
// Value is string
const value = firstTd.localeCompare(secondTd, "en");
return value;
}
}).appendTo(tbody);
Here is the source code for my table (I just added two rows):
<table class="table">
<thead>
<tr>
<th>
<button class="btn btn-light data-table-sort"
data-index="1" data-order="asc">
id <span class="fa fa-sort" aria-hidden="true"></span>
</button>
</th>
<button class="btn btn-light data-table-sort"
data-index="3" data-order="asc">
Text <span class="fa fa-sort" aria-hidden="true"></span>
</button>
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>72</td>
<td>af7c16d8f1</td>
<td>2021-11-26 06:16:55</td>
<td>
<form method="POST">
<input type="hidden" name="id" value="72">
<input type="submit" name="action" value="Details"
class="btn btn-info">
<input class="btn btn-primary" name="action"
type="submit" value="Edit">
<input data-id="72"
class="btn btn-danger data-table-delete"
name="action" value="Delete" type="submit">
</form>
</td>
</tr>
<tr>
<td>7</td>
<td>bedd6af3ed</td>
<!-- The same form as previous row -->
</td>
</tr>
</tbody>
</table>
I have made sure that tbody contains the correct value. I am also selecting the correct column. The table has to be dynamic and reusable so I can't hardcode everything.
Note: I have already tried appending rows to the table instead of the <tbody> element.
You probably need to detach elements since you reattach it again later:
tbody.find('tr').detach().sort...
This may need readjustments depending on how jQuery arrays are returned but detaching elements is the main idea and other things should be pretty trivial.

Display icon when at least one checkbox is checked

I display checkboxes in my table. Now when i check at least one checkbox, the icon must appear if not, it should be hidden. My icon is not hidden.
What am i doing wrong?
This is my code
<div class="row">
<div class="col-sm-12 ">
<a data-toggle="modal" id="btnAdd" data-target="#myModal" class="btn"> Add Items </a>
<i type="icon" class="fa fa-trash " ></i>
<div>
</div>
<table class="table" id="table">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
</tr>
</thead>
<tbody>
<td><input type="checkbox"></td>
//table data here
</tr>
#endforeach
</tbody>
</table>
var checkboxes = $("input[type='checkbox']"),
hideIcon = $("i[type='icon']");
checkboxes.click(function() {
hideIcon.attr("disabled", !checkboxes.is(":checked"));
});
You'll need to iterate through all your checkboxes on each click. Also, I would recommend using the prop function to check for the "checked" status. Then, to hide it, either use the hide function, or set the display property to hidden:
$("input[type='checkbox']").click(function() {
var atLeastOneChecked = false;
$("input[type='checkbox']").each(function(index) {
if ($(this).prop('checked'))
atLeastOneChecked = true;
});
if (atLeastOneChecked) {
$("i[type='icon']").show(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','inline-block'); //or set style explicitly
} else {
$("i[type='icon']").hide(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','none'); //set style explicitly
}
});

Hide/show elements in javascript

<tr>
<td>Name:</td>
<td><span id= "keep">Username</span><input id= "change" value= "Name" style= "display:none;"></td>
</tr>
I have this, what kind of javascript do I need in order to hide the span and let the input show? This should be done by clicking this edit button:
<i class="glyphicon glyphicon-edit"></i>
I have checked other questions on this site for duplication, but I tried alot and none answered my question!
<html>
<head>
<script>
function showMe(){
document.querySelector('#change').style.display = ''; //Show the input
document.querySelector('#keep').style.display = 'none' //Hide the span
}
</script>
</head>
<body>
<tr>
<td>Name:</td>
<td>
<span id = 'keep'>Username</span>
<input id = 'change' value= 'Name' style= 'display:none;'>
</td>
</tr>
<a href = '#' data-original-title = 'Edit this user' data-toggle = 'tooltip' type = 'button' class='btn btn-sm btn-warning' onclick = 'showMe()'><i class = 'glyphicon glyphicon-edit'>click me</i></a>
</body>
</html>
Use This Simple Code
first add library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
your html code
<i class="glyphicon glyphicon-edit"></i>edit
<span id= "keep">Username</span><input id= "change" value= "Name" style= "display:none;"></span>
and use script
<script>
$(document).ready(function(){
$("a").click(function(){
$(" #change").toggle();
$("#keep").hide();
});
});
</script>

How to use closest() in jQuery

I am trying to get value of a text box by using closest().
My form contains dynamically created table with one text box and button in each row . I want to show the value of text box in button click event.
Table format is given below
<table id="dataarea" class="table">
<tbody>
<tr>
<td>jaison<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="100">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
<tr>
<td>ARUN<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="500">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
</tbody>
</table>
I have written one javascript code (given below) . when the code will execute, it return a null value.
Function
function UpdateSchedule() {
var amt2 = $(this).closest('td.amountclm').find('.amtcls').val();
alert( amt2);
}
Please let me know why am not getting the null value.
jQuery .closest() goes up from the current element until it finds what you give it to find. jQuery .find() goes down until it finds what you give it to find.
This does the trick:
http://jsfiddle.net/6T3ET/
id must be unique, you need to use class instead:
<button class="schedule schbtn btn btn-primary" type="button">
<input class="amtcls txtamt" type="text" value="500">
an use .click() instead of inline onClick handler since you're using jQuery. So you can do:
$('.schedule').click(function() {
var amt2 = $(this).closest('td').prev('td.amountclm').find('.amtcls').val();
alert( amt2);
});
Please note that the .amountclm input is the child of a td whose is the immediate previous sibling of parent td of your clicked .schedule button.
Try this
replace 'this' with the 'schedule_' class attribute
function UpdateSchedule() {
var amt2 = $(".schedule_").closest('td.amountclm').find('.amtcls').val();
alert( amt2);
}
HTML :
<table id="dataarea" class="table">
<tbody>
<tr>
<td>jaison<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="100">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary schedule_" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
<tr>
<td>ARUN<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="500">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary schedule_" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
</tbody>
</table>
or try with Jquery as
$(document).on('click', '.schedule_',function(){
var amt2 = $(this).closest('td.amountclm').find('.amtcls').val();
alert( amt2);
} );
Use .parent() and .prev() in jquery for this contradiction
$(".schbtn").click(function() {
var amt2 = $(this).parent().prev("td.amountclm").find('.amtcls').val();
alert( amt2);
});
Fiddle
First of all .closest() is not plain JavaScript. It's a function from jQuery.
http://api.jquery.com/closest/
and it traverses up in the element hierachy. And td.amountclm is not in the element hierachy of the button#schedule.
Therefore .closest wont find it.

How to find previous element in jQuery on click event?

My button is in a TD and I want to just previous TD on button click event I am doing it following but not getting the value... How should I do it?
$(".prodcs").click(function () {
var test = $(this).attr(".prodcs").prev().find('#DDL option:selected').val();
alert(test);
CustomCategory.OnCustomClick($(this).attr("data-productid"));
});
Below is the HTML
<tr>
<td width="170">
<input type="text" class="form-control" placeholder="1">
</td>
<td width="560">
<select name="DDL" id="DDL" class="form-control"><option value="1">7'' - £10.00</option>
<option value="2">14'' - £15.00</option>
<option value="6">5'' - £5.00</option>
<option value="7">500 M- £15.00</option>
</select> </td>
<td width="102" align="right">
<a data-toggle="modal" href="#myModal" data-productid="3" id="product_3" class="btn btn-primary btn-lg popup prodcs">Customisation</a>
</td>
<td width="101" align="right">
<button type="button" class="btn btn-default">
<i class="glyphicon glyphicon-shopping-cart" style="font-size: 20px; color: #666"></i>
</button>
</td>
</tr>
Assuming .prodcs is the button
$(".prodcs").click(function () {
var test = $(this).closest("td").prev().find('select').val();
alert(test);
CustomCategory.OnCustomClick($(this).attr("data-productid"));
});
.closest() is used to find the td in which the button is present
.prev() finds the previous td element
.find('select') finds the select element inside the previous td
Note: If there are multiple elements with the id DDL, it is not valid use a class instead
try this:
$(".prodcs").click(function () {
var test = $(this).parent().prev().find('#DDL option:selected').val();
alert(test);
CustomCategory.OnCustomClick($(this).attr("data-productid"));
});
or
$(".prodcs").click(function () {
var test = $(this).closest('td').prev().find('#DDL option:selected').val();
alert(test);
CustomCategory.OnCustomClick($(this).attr("data-productid"));
});
Almost there just remove .attr(".prodcs"):
var test = $(this).prev().find('#DDL option:selected').val();

Categories

Resources