I'm developing an app who can register for university courses. they add select their register type,course type ,batch and their subjects. i'm putting subjects on the table when they selecting a course type also the batch. So they can select subjects, after they add it will put into the selected subjects table. My code will work on when they are working # first time. but suddenly they are changed they are register type,course type and batch it will list down the subjects. BUT when they selecting a subject it will add two table trs to the selected subjects Tables. Why is that ?
JQUERY
$("#subjectsTable").on('change', '.selectedSubjects', function (event) {
event.stopPropagation();
var selectedReg = $('#CouserFinder option:selected').val();
var selectedCouse = $('#CourseSet option:selected').val();
var selectedBatch = $('#alreadyBatchSorting option:selected').val();
if(selectedBatch != "Select Your Batch"){
var shouldChecked = $("#CT_No_Of_SubjectsCount").val();
var bol = $(".selectedSubjects:checkbox:checked").length >= shouldChecked;
$(".selectedSubjects:checkbox").not(":checked").attr("disabled",bol);
if ($(this).is(":checked")) {
var indexChecked = $(this).closest("tr").attr("data-index");
alert(indexChecked);
var selectedSCode = $(this).closest("tr").find(".selectedSCode").text();
$("#selectesSubjectsRecodes tr:last").after("<tr data-index=" + indexChecked + "><td>" + selectedReg + "</td><td>" + selectedCouse + "</td><td>" + selectedSCode + "</td><td>" + selectedBatch + "</td></tr>");
} else {
var indexAdded = $(this).closest("tr").attr("data-index");
var findRow = $("#selectesSubjectsRecodes tr[data-index='" + indexAdded + "']");
findRow.remove();
}
}
else{
alert("Warning!: Select Your Batch");
$(this).prop('checked', false)
}
});
HTML
<tr class="success" data-index="10">
<td>
<input class="selectedSubjects" type="checkbox" name="selectedSubjects">
</td>
<td class="selectedSCode">BCS-DIP-UID</td>
<td class="selectedSName">UID</td>
</tr>
SELECTED SUBJECT CODE (get it from the DOM )
<tr data-index="10">
<td>BCS-DIP-S3</td>
<td>BCS-DIP</td>
<td>BCS-DIP-UID</td>
<td>BCS-DIP-APR/2014-002</td>
</tr>
<tr data-index="10">
<td>BCS-DIP-S3</td>
<td>BCS-DIP</td>
<td>BCS-DIP-UID</td>
<td>BCS-DIP-APR/2014-002</td>
</tr>
Screen Shot
As you can see it will adding two trs.why is that ?
You are binding a new event handler to $("#subjectsTable .selectedSubjects") every time you call that function. The problem will stem from the fact that your javascript is in a function which is being called multiple times.
Related
So at work, I have to go through a list that contains thousands of users and select a checkbox by the ones I need to delete. Long story short it's a slow process. To make things faster I made this script to run in chrome using developer tools in the console.
var usernames = ["jimmy123"];
for(var i=0;i<usernames.length;i++)
{
jQuery("td:containsExact("+usernames[i]")").find('[type=checkbox]').parent().attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
alert("Everything Returned Okay!");
alert(usernames.length);
alert(count + " Checkboxes Checked!");
The Trouble is that let's say a user created 3 because they forgot the login for them "not uncommon" and their username is:
jimmy123
jimmy1234
jimmy12345
If I need to just check the box next to jimmy123 for removal my script selects all 3 since they have mostly the same username.I tried some filters but the result was the same.
Backend Screenshot
You can use filter() function here to match the exact text in the td and then mark the checkbox selected. See the below script, you didn't provide the HTML so I added a sample table with some td containing usernames and checkbox, you should update the script accordingly
$(function($) {
var usernames = ["jimmy123", "omer"];
for (var i = 0; i < usernames.length; i++) {
$("tr>td").filter(function() {
return $(this).text() == usernames[i]
}).find('[type=checkbox]').attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
console.log("Everything Returned Okay!");
console.log("usernames.length" + usernames.length, usernames);
console.log(count + " Checkboxes Checked!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="checkbox">omer</td>
<td><input type="checkbox">omer123</td>
<td><input type="checkbox">omer6565</td>
<td><input type="checkbox">omer63645</td>
<td><input type="checkbox">omer021</td>
<td><input type="checkbox">omer521</td>
<td><input type="checkbox">jimmy123</td>
</tr>
</table>
EDIT
You can assign an id to your table say my-table and then change the selector in the code above from
$("tr>td").filter(function() {
to the following
$("#my-table tr>td").filter(function() {
The exact selector could be suggested when you add the HTML for your user listings that you are using the script with.
EDIT2
According to your html it should be
$(function($) {
var usernames = ["jimmy123", "omer"];
for (var i = 0; i < usernames.length; i++) {
$("#listContainer_datatable tr td").filter(function() {
return $(this).text() == usernames[i]
}).find('[type=checkbox]').attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
console.log("Everything Returned Okay!");
console.log("usernames.length" + usernames.length, usernames);
console.log(count + " Checkboxes Checked!");
});
I have a table containing information now i want to pass the information of a selected row to another page.For creating a link to another page i have made image as a link and now i want to pass the information of the row to another so that i can display selected image and it's information.Please help.
My table. Suppose i click on first image so i want to pass the information of that particular to row to another page.
HTML AND JS
<table style="width:100%" id="ex-table">
<th>Image</th>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Description</th>
<script>
var fbRef = firebase.database().ref().child("Sell_Products");
fbRef.on("child_added", snap => {
var name = snap.child("name").val();
var price = snap.child("price").val();
var category = snap.child("category").val();
var description = snap.child("description").val();
var image = snap.child("image").val();
$("#ex-table").append("<tr><td><a href='auction.html'><img src=" + image + "/img></a></td><td>" + name + "</td><td>" + price + "</td><td>" + category + "</td><td>" + description + "</td></tr>" );
});
</script>
</table>
Thanks in advance
You should get the key of the child and pass it as a QueryString parameter in the URL you call when clicking the image.
fbRef.on("child_added", snap => {
var key = snap.key;
var name = snap.child("name").val();
var price = snap.child("price").val();
var category = snap.child("category").val();
var description = snap.child("description").val();
var image = snap.child("image").val();
$("#ex-table").append("<tr><td><img src=" + image + "/img></td><td>" + name + "</td><td>" + price + "</td><td>" + category + "</td><td>" + description + "</td></tr>" );
});
Then, in the auction.html page you get the key of the child and query the info from the database.
You coud also build an url with all the values in the query string if you want to avoid executing a new query on the auction.html page
I want to loop through a form with Javascript but my problem is that I have another form in the first form.
I'd like to loop through the first form only, not the inner one. I found this method on an other post :
var table = $("#table_cultures tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + productId
+ '\nProduct: ' + product
+ '\nQuantity: ' + Quantity);
});
This method works but loop through the both forms.
EDIT 1 :
The html looks like :
<form>
<table>
<tr>
<td>Something here</td>
</tr>
<tr>
<td>
<form>
<table>
//tr td ...
</table>
</form>
</td>
</tr>
</table>
</form>
nesting of <form> elements is not allowed
please see:
https://www.w3.org/TR/html5/forms.html#the-form-element
"...Flow content, but with no form element descendants..."
I am using Select2 for dropdown styling from http://ivaynberg.github.io/select2/ .
I have several dropdowns on the page which are styled correctly using the following:
<script>
$(document).ready(function() {
$("#dropdown1").select2();
$("#dropdown2").select2();
});
</script>
Now, I have another option on the page where it allows the user to add as many dropdowns as they want for additional options, the following way:
<img src="images/add.png" title="Add Row" border="0" onclick="addRowToCountryPrice('',''); return false;">
<input type="hidden" name="TotalLinesCountry" id="TotalLinesCountry">
<script>
var arr = new Array();
var ind=0;
function showCountryDrop(name1,sel, param){
var dval="";
dval = "<select name=\"" + name1 + "\" id=\"" + name1 + "\" class=\"countriesclass\">";
dval += "<option value=\"\">Select Country</option>\r\n";
selVal = (sel==0001) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0001\" " + selVal + ">United Kingdom</option>";
selVal = (sel==0002) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0002\" " + selVal + ">United States</option>";
selVal = (sel==0003) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0003\" " + selVal + ">Albania</option>";
selVal = (sel==0004) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0004\" " + selVal + ">Algeria</option>";
dval +="</select>";
return dval;
}
function addRowToCountryPrice(country,price) {
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cellVal = "";
var cellLeft;
var i=0;
arr[ind] = (iteration+1);
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = showCountryDrop("countryDrop_" + ind,country);
cellLeft = row.insertCell(i++);
var price = (price!=0) ? price : "0.00";
cellLeft.innerHTML = "<input type=\"text\" name=\"countryPrice_" + ind + "\" id=\"countryPrice_" + iteration + "\" value = \"" + price + "\" size=\"8\">";
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = "<img src=\"images/delete.png\" title=\"Delete Row\" border=\"0\" onclick=\" removeRowFromTable(" + ind + "); return false;\">";
document.getElementById("TotalLinesCountry").value = (parseInt(ind)+1);
ind++;
}
function removeRowFromTable(src)
{
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
if (arr[src]!="") tbl.deleteRow((arr[src]-1));
arr[src]="";
var counter = 1;
for( i=0; i<arr.length; i++) {
if (arr[i]!="") {
arr[i]= counter;
counter++;
}
}
return false;
}
</script>
While it generates the dropdowns correctly, they are not styled through the class "countriesclass", even if I do a:
$(".countriesclass").select2();
I also tried
dval +="</select>";
$(".countriesclass").select2();
return dval;
And that seems to be PARTIALLY working in a strange way. When I create the first dropdown, it doesn't get styled. When I create another second dropdown, then the first one gets styled but the second one doesn't. It then doesn't let me create further ones and shows an error.
Any ideas how I could get this working?
UPDATE: jsFiddle http://jsfiddle.net/y6af098z/2/
Your call to $('.countriesclass') goes off when the document is ready. But the select has not been added to the document yet, then. So no elements are found.
You should look up the added select after the user has clicked on the plus and you've added the select to the dom.
$('#plus').on('click', function () {
$tr = addRowToCountryPrice('Algeria', 0);
$('.countriesclass', $tr).select2();
});
The second argument $tr tells jquery only to look in the recently added table row, so that you only select the newly added select which is a child of the newly added tr. Not the selects in the other rows.
Like #dreamweiver already noted, you should make better use of jquery when creating the dom elements. That's what jquery is good at. I've updated the jsfiddle to show how you can create the select and table row the jquery way.
DEMO
Instead of using getelementbyId use getelementbyClass and give each dropdown a class, you can only have one getelementbyid.
Hope this helps. if you want i could send you the code for what you require?
The select2 when called was not able to find the dropdown list boxes,because they were added dynamically and hence the those were not visible for the jQuery class selector $(".countriesclass").select2();.
This type of behaviour can be overcome by referencing the selector from the document element, rather than referring the element directly like above. so the new selector should be like this
$(document).find("select.countriesclass").select2();
Also I have done few tunings in your code.
Live demo:
http://jsfiddle.net/dreamweiver/y6af098z/8/
Note: one more thing, when using jQuery lib make sure you make the most of it, don't use raw JS code instead use the jQuery equivalent syntax for the same, which would be simple and easy to use.
I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});