Select all textboxes using jQuery - javascript

I have code which displayed a person's info in a table(fields:name, surname, address, etc.) and one of the inputs is a checkbox. The code is as follows:
$("#table").append('<tr class="trow'+j+'">'+
'<td class="ids" id="z'+i+'">'+totrecs+'</td>'+
'<td>'+member[i].jdate+'</td>'+
'<td class="users"
'<td id="contact'+i+'">'+member[i].fname+' '+member[i].lname+'</td>'+
'<td id="myaddress'+i+'">'+member[i].address1+' '+member[i].town+'</td>'+
'<td><input type="checkbox" name="whome" id="showMe'+i+'"'+
'class="boxes" onclick="getMe('+i+')" /></td></tr>');
totrecs++;
j++;
}
What I am tryin to do is program a function that when clicking a certain button all of the checkboxes will be selected/checked.
I would appreciate any help. Thank You.

this may be helpful: JQquery Select All Checkboxes tutorial

To check all checkboxes in #table using jQuery:
$('#table :checkbox').attr('checked', '');
Note that this will not trigger any click events you set for the checkboxes. You should use the change event instead of click to make it happen as expected.

<input type="button" value="Check/Uncheck All" />
$('#btnId').on('click', function() {
var check = false;
if( !$(this).hasClass('checked')){
bool = true;
}
$(this).toggleClass('checked');
$('#table input[type="checkbox"]').prop('checked', check)
});

Related

Checkbox not checked onclick JavaScript

I'm trying to add an input field on click of checkbox, and I want the checkbox to be checked (which is its default behaviour!), but the checkbox is not getting checked even after the input field appears. The following is my HTML code with JavaScript.
function check_test() {
if (document.contains(document.getElementById("test_input"))) {
document.getElementById("test_input").remove();
}
document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()" />
</div>
I also tried this in JsFiddle which gives the same error and am not sure what I'm doing wrong.
https://jsfiddle.net/1yLb70og/1/
You're overwriting the content of the same div that the checkbox lives in, using innerHTML like that. Use a second div, or use create element and append child instead of replacing the entire contents.
This works.
<html>
<div id="test_div1">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()"/>
</div>
<div id="test_div"></div>
<script>
function check_test() {
if(document.contains(document.getElementById("test_number"))) {
document.getElementById("test_number").remove();
}
document.getElementById("test_div").innerHTML += "<input type='number' name='test_number' id='test_number'/>";
}
</script>
</html>
You're conditionally removing the #test_input if it exists in the DOM, but then you're not using an else when adding it. So no matter which state you're in, you'll always end the function with having added the input to the DOM.
As others have mentioned, when you += on the innerHTML, then you're actually creating a whole new string, thereby reinitializing your original checkbox to unchecked.
You may want to just append a new child to the wrapper. I've also used the onchange event instead so that it will do what you want no matter if the box is checked by a click or programmatically.
function check_test(checkbox) {
const checked = checkbox.checked; // is it checked?
const testInput = document.getElementById("test_input"); // test_input element
// if it's checked and doesn't have an input, add it
if (checked && !testInput) {
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'test_input';
newInput.id = 'test_input';
checkbox.parentNode.appendChild(newInput);
}
// otherwise, if it's not checked and there is an input in the DOM, remove it
else if (!checked && testInput) {
document.getElementById("test_input").remove();
}
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test(event.target)" />
</div>
By doing += you're overriding previous checkbox.
You could use:
document.getElementById("test_div").insertAdjacentHTML("afterend", "<input type='text' name='test_input' id='test_input'/>");
Instead of:
document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
Not the greatest solution; however, it works and it's extremely simple. Then you just fix up the rest of the page with CSS styling.
Try adding an event in the function declaration:
function check_test(e)
Then calling e.checked; at the top or bottom of the function.
Let me know if that works.
Answering from my phone so I can't test myself.
When use innerHTML all events of the element is canceled.
You need to use DOM functions.
<html>
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test()" />
</div>
<script>
function check_test() {
var testdiv = document.getElementById("test_div");
if (!document.contains(document.getElementById("test_number"))) {
var newInput = document.createElement('input');
newInput.id = 'test_number';
testdiv.appendChild(newInput);
}else{
document.getElementById("test_number").remove();
}
}
</script>
</html>
related:
https://stackoverflow.com/a/595825/5667488

JQuery Get Value from Select Option not working

I dont know why my jquery code does not works to get value from select option.
I have created a function where when I click on "Add New Row" button then it will create a new row to my table.
Here's my JS code to add new row
$(".tambah_sofa").on('click',function(){
html = '<tr id="row_'+i+'">';
html += '<td><button type="button" id="delete-button" data-row-delete="row_'+i+'">X</button></td>';
html += '<td><select name="sofa[]" id="sofa"> <option value="'+sofa_rumah+'">Sofa rumah</option><option value="'+sofa_pejabat+'">Sofa Pejabat</option><option>Sofa Kedai</option><option>Tilam Tak Bujang</option> </select> </td>';
html += '<td>X</td>';
html += '<td><input type="number" name="quantity[]" id="quantity_'+i+'" value="1" disabled="disabled"></td>';
html += '</tr>';
sidebar = '<tr id="row_'+i+'">';
sidebar += '<td><input style="width:50%;" type="text" id="price_sofa" value="" disabled="disabled"></td>';
sidebar += '</tr>';
$('#table_item').append(html);
$('#table_sidebar').append(sidebar);
i++;
});
Below is my code to get select option values into textbox :
$('#sofa').on('change', function () {
$('#price_sofa').val(this.value);
}).trigger('change');
I try to follow this JSfiddle demo : http://jsfiddle.net/JwB6z/2/
The code is working but when I try implement to my "add new row" function, it's not working.
I believe this is because any new row is not being recognised. I think you should bind the change to body...
example:
$('body').on('change', '#sofa', function () {
you can always use this:
$('#sofa').on('change', function () {
$('#price_sofa').find(':selected').val();
}).trigger('change');
EDIT: The above one is used to get the value you entered if you want to add the text and not value you can always put
$('#price_sofa).find(':selected').text();
EDIT2: When you use $('#price_sofa').val(this.value); you are not taking the selected option and a you can see in the fiddle here that you added they didn't use the function that you used.
Hope this helps

How to get a count of checkboxes checked on pagination Jquery dataTables

Below is my code, I want to get the count of checked checkboxes of all pages in my DataTable. Please advice how to proceed
<td align="center"><input type="checkbox" align="center" id="all" class="groupCheckBox" name="emails[]" value=' . $user['id'] . '></td>
Below code I used for get the values of checked boxes in all pages on button click
$('#merge_button').click(function () {
var id = "";
var oTable = $("#userTable").dataTable();
$(".groupCheckBox:checked", oTable.fnGetNodes()).each(function () {
if (id != "") {
id = id + "," + $(this).val();
} else {
id = $(this).val();
}
document.getElementById("email").value = id;
});
});
but now I want to count the checkedboxes without button click function whenever user clicked on checkboxes and deduct count when unchecking boxes . pls advice
var table = $("#userTable").DataTable();
var countchecked = table
.rows()
.nodes()
.to$() // Convert to a jQuery object
.find('input[type="checkbox"].groupCheckBox:checked').length;
Uses the most recent API
"...please be aware that using deferRender will cause some nodes to be created only when they are required for display, so they might not be immediately available when this method is called." from https://datatables.net/reference/api/rows().nodes()
Quite easy.
$("td input[type='checkbox']:checked").length;

Check if all input/select fields of a table row have values

There is a table with some input and select fields in a row. I want to check if all input and select fields of an row have a value. This is how I would think to do that, but do I have to use closest and find? I think this is not optimal.
HTML
<table>
<tr>
<td><select><option></option><option>Select anything</option></td>
<td><input type="text" name="field1"></td>
<td><input type="text" name="field2"></td>
</tr>
<tr>
<td><select><option></option><option>Select something</option></td>
<td><input type="text" name="field3"></td>
<td><input type="text" name="field4"></td>
</tr>
</table>
JS
'change #table input, change #table select': function(event) {
var $this = $(event.currentTarget),
$row = $this.closest('tr'),
$elements = $row.find('input, select');
var empty = false;
$elements.each(function(index) {
if (!$(this).val()) empty = true;
});
if (empty)
console.log('some value is missing')
else {
console.log('valide');
// do something with values
}
}
There are really two questions here:
Most optimal method to select all inputs in a table row
Ensure all the inputs have a value
For the first question there is a subliminal side to that. Ensure that it IS an input and then select it within the context of the current row of the changed input.
First off, jQuery uses the Sizzle (https://sizzlejs.com/) engine under the covers for selection. One thing to be aware of is the "right to left" processing of the selector string by that engine.
Thus the most optimal selection is somewhat browser specific but the fastest way to select is an ID followed in modern browsers by a class. Some older browsers do not select by class as well but let's leave that for your research.
Selection: Bad way to do stuff
So given that, let's look at a complex selector that you might use:
'div.mycontainer div.mytablecontainer>table#mytable.mytableclass tr td select, div.mycontainer div.mytablecontainer>table#mytable.mytableclass tr td input'
First off DO NOT USE THAT. Now to explore why not: Remember we talked about the "right to left" selector processing? For discussion let us narrow down out selector to the last part:
"div.mycontainer div.mytablecontainer>table#mytable.mytableclass tr td input"
What this does then in starting on the right:
"find all the inputs in the DOM",
use that list of those inputs, "find all the inputs in a td element
use those td elements, find all those in a tr
find all those tr in a .mytableclass element
find all those in an element with an id of mytable (remember this ID MUST be unique)
Now keep going, find that single element id that is a table element
That is an immediate child of an element with classmytablecontainer
That is a DIV element div
That is a child of an element with class mycontainer
That is a DIV element div
Whew that's a lot of work there. BUT we are NOT DONE! We have to do the same thing for the OTHER selector in there.
Selection: Better way to do stuff
NOW let's do this better; first off let's leverage the modern browser class selector by adding a class to all our "scoped" inputs - things we want to check for entry.
<input class="myinput" />
It does really need a type="" attribute but ignore that for now. Let's use that.
$('#mytable').find('.myinput');
What this does is:
Select the element with ID of 'mytable' which is the FASTEST selector in all browsers; we have already eliminated those 47 other tables in our DOM.
Find all the elements with a class of class="myinput"; within that table; in modern browsers this is also very fast
DONE. WOW! that was SO much less work.
Side note on the .find() instead of "#mytable input"
Remember our right to left once again? Find all inputs in the DOM, then narrow to those inputs we found that are in that table NO STOP THAT right now.
Or (better likely) "#mytable .myinput"
SO our "rules" of selecting a group of elements are:
Use an ID to limit scope to some container if at all possible
Use the ID by itself NOT part of a more complex selector
FIND elements within that limited scope (by class if we can)
Use classes as modern browsers have great selection optimization on that.
When you start to put a space " " or ">" in a selector be smart, would a .find() or .children() be better? In a small DOM perhaps maintenance might be easier, but also which is easier to understand in 4 years?
Second question: not specific but still there
You cannot simply globally use !$(this).val() for inputs.
For a check box that is invalid. What about radio buttons? What about that <input type="button" > someone adds to the row later? UGH.
SO simply add a class to all "inputs" you DO wish to validate and select by those:
<input type="text" class="validateMe" />
<select class="validateMe" >...
Side note you MIGHT want to sniff the TYPE of the input and validate based upon that: How to get input type using jquery?
EDIT: Keep in mind your validation input MIGHT have a "true/false" value so then this might fail: !$(this).val() (radio buttons, checkbox come to mind here)
Some code and markup:
<table id="mytable">
<tr>
<td>
<select class="myinput">
<option></option>
<option>Select anything</option>
</select>
</td>
<td>
<input class="myinput" type="text" name="field1" />
</td>
<td>
<input class="myinput" type="text" name="field2" />
</td>
</tr>
<tr>
<td>
<select class="myinput">
<option></option>
<option>Select something</option>
</select>
</td>
<td>
<input class="myinput" type="text" name="field3" />
</td>
<td>
<input class="myinput" type="text" name="field4" />
</td>
</tr>
</table>
<div id="results">
</div>
probably NOT want a global (namespace the "selectors")
var selectors = '.myinput';
$('#mytable').on('change', selectors, function(event) {
var $this = $(event.currentTarget),
$row = $this.closest('tr'),
$elements = $row.find(selectors);
var $filledElements = $elements.filter(function(index) {
return $(this).val() || this.checked;
});
var hasEmpty = $filledElements.length !== $elements.length
var rowIndex = $row.index();
$('#results').append("Row:" + rowIndex + " has " + $filledElements.length + ' of ' + $elements.length + ' and shows ' + hasEmpty + '<br />');
if (hasEmpty)
console.log('some value is missing');
else {
console.log('valide');
// do something with values
}
});
AND something to play with: https://jsfiddle.net/MarkSchultheiss/fqadx7c0/
If you're only selecting on particular element with knowing which parent to select with, you should try using .filter() to filter out only element that did't have a value like following :
$('button').click(function() {
var h = $('table :input').filter(function() {
return $(this).val() == "" && $(this);
}).length;
alert(h);
});
DEMO
I did this plunk
https://plnkr.co/edit/q3iXSbvVWEQdLSR57nEi
$(document).ready(function() {
$('button').click(function() {
var table = $('table');
var rows = table.find('tr');
var error = 0;
for (i = 0; i < rows.length; i++) {
var cell = rows.eq(i).find('td');
for (a = 0; a < cell.length; a++) {
var input = cell.eq(a).find(':input');
if (input.val() === "") {
input.css("border", "solid 1px red");
error++;
} else {
input.css("border", "solid 1px rgb(169, 169, 169)");
}
}
}
if (error > 0){
alert('Errors in the form!')
return false;
} else {
alert('Form Ok!')
return true;
}
})
})
Simple Jquery validation, searching all the inputs (including selects), if it's null, increment the error counter and change class. If the error counter is > 0, alert error and return false;
Maybe isn't the best solution, but it sure can help get started.

How to get dynamically generated check box values

How to get the values of Dynamically generated CheckBoxes using jquery
for(i=startAt;i<limit;i++)
{
var str = '<tr>'+
'<td width="48" align="center"><input class="A" type="checkbox" name="checkbox" value='+ local[i]['_id'] +'></td>'+
'<td width="270" >' + local[i]['_id'] +'</td>'+
'<td width="883" class="alignRt">'+local[i]['count']+'</td>'+
'</tr>'
$("#tableBody").append(str);
}
using this I am able to get the total checkboxes at runtime
$(document).on('click', '.A', function(){
var n = $("input:checked.A").length;
console.log(n)
But I want to get the values too.
How can I do that ?
Use the :checked selector
jQuery('.A:checked')
You can then loop over the elements to get all their values.
$(document).on('click', '.A', function(){
var n = $( "input:checked.A" ).length;
var arr=[]
for(i=0;i<n;++i){
arr.push($($( "input:checked.A" )[i]).val())
}
alert(arr)
});
You can get checked checkboxes using:
$("#tableBody").find("input:checked");
It returns a list of checked checkboxes
use JQuery's $('#CheckboxID').val()

Categories