checkbox group get value of checked checkbox jquery - javascript

Ive been searching for idea on how to get value of checkbox group but i need to the x and y for this so far what i have seen is only with one so i havent really found any relevant answer or idea to my problem so i will explain what i want to happend. In my X i have a number of columns namely first quarter,second quester,third quarter and fourth quarter in my Y i have names of students. And i also have an extra checkbox option to add additional student. I want to Check the check corresponding to names and quarter. I will used this to track down student who has taken the exam and who has not yet taken the exam. I am wondering how to group the the checkboxes in a way that when i check on it will automatically get the student name and corresponding quarter.
HTML:
<tr>
<td width="25%">
<hr/>
</td>
<td width="15%">
<center><span>1st Quarter</span>
</center>
</td>
<td width="15%">
<center><span>2nd Quarter</span>
</center>
</td>
<td width="15%">
<center><span>3rd Quarter</span>
</center>
</td>
<td width="20%">
<center><span>4th Quarter</span>
</center>
</td>
</tr>
<tr>
<td><span>Joe Smith</span>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
</tr>
<tr>
<td><span>John Smith</span>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
<td>
<center>
<input type="checkbox" name="studentrecord[]" />
</center>
</td>
</tr>
Check fiddle
Update
$("input[name='student[]']:checked").map(function() {
var $td = $(this).closest('td'),
index = $td.index();
valueToPush.push({
Quarter: quarter.eq($td.index()).find('span').text().trim(),
Student: $td.parent().find('td:first-child span').text().trim()
});
});

In that case, 1 approach is to create an array of objects where each object represent a checkbox like
$(document).on('click', '#check', function() {
var $quarters = $('table tr:first-child td');
var values = $("input[name='studentrecord[]']:checked").map(function(){
var $td = $(this).closest('td'), index = $td.index();
return {
quarter: $quarters.eq($td.index()).find('span').text().trim(),
student: $td.parent().find('td:first-child span').text().trim()
}
}).get();
console.log(values);
});
Demo: Fiddle
Note: No need to use event delegation if the button is present when script $(document).on('click', '#check', function() { }) is executed.
Another option is to store an array of quarters against each student like
$('#check').on('click', function () {
var $quaters = $('table tr:first-child td'),
students = {};
$("input[name='studentrecord[]']:checked").each(function () {
var $td = $(this).closest('td'),
student = $td.parent().find('td:first-child span').text().trim();
if (!students[student]) {
students[student] = [];
}
students[student].push($quaters.eq($td.index()).find('span').text().trim())
}).get();
console.log(students);
});
Demo: Fiddle

You can initially track each checkbox click and store them in an array. Later, while clicking the button you can retrieve the Student names and the quarters they appeared in directly. Check this Fiddle
var arrObj = {};
$("input[type='checkbox']").click(function(){
if($(this).is(':checked')) {
var studentName = $(this).closest('tr').find('td:first span').html();
var quarterIndex = $(this).closest('td').index();
var quarterName = $(this).closest('table').find('tr:first td:eq('+parseInt(quarterIndex)+')').find('span').html();
if(arrObj[studentName]) {
arrObj[studentName].push(quarterName);
} else {
arrObj[studentName] = [];
arrObj[studentName].push(quarterName);
}
}
});
$(document).on('click', '#check', function() {
for( var key in arrObj) {
alert(key+" appeard in: "+arrObj[key]);
}
});

Related

Getting next element in a table javascript

https://jsfiddle.net/en6jh7pa/1/
I am having issues grabbing the next element, it is returning null for the next element.
I am passing "this? as onclick and I assumed that you could use this to grab the next element but it seems that it instead returns null
Thanks for your help
function assignnames(checkboxelement){
checkboxelement.setAttribute("name", "checkbox");
var value1box = checkboxelement.nextSibling;
value1box.setAttribute("name", "notnull");
var value2box = checkboxelement.nextElementSibling;
value2box.setAttribute("name", "notnull");
alert("done");
}
<table border="1">
<tr>
<th>
Checkbox
</th>
<th>
value1
</th>
<th>
value2
</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="assignnames(this)" id="checkbox1"/>
</td>
<td>
<input type="text" name="" id="fname1">
</td>
<td>
<input type="text" name="" id="lname1">
</td>
</tr>
</table>
If you want to get the text inputs in the same row, you can go up to the row, then use a selector to get the inputs, e.g.
function getParent(node, tag) {
var tag = tag.toLowerCase();
do {
if (node.tagName.toLowerCase() == tag) {
return node;
}
node = node.parentNode;
} while (node && node.tagName && node.parentNode)
return null;
}
function getInputs(evt) {
var row = getParent(this, 'tr');
var inputs;
if (row) {
inputs = row.querySelectorAll('input[type="text"]');
}
console.log(`Found ${inputs.length} text inputs, node is ${this.checked? '':'not '}checked.`);
}
window.onload = function(){
document.getElementById('checkbox1').addEventListener('click', getInputs, false);
};
<table border="1">
<tr><th>Checkbox
<th>value1
<th>value2
<tr><td><input type="checkbox" id="checkbox1">
<td><input type="text" name="" id="fname1">
<td><input type="text" name="" id="lname1">
</table>
For the inputs to be siblings, they would all have to be within the same <td>, sharing a singular parent. With them spread out across multiple table cells, they would be considered cousins instead (keeping with the family tree metaphor), which doesn't have a similar shortcut property.
You can still use nextElementSibling along the way between inputs, but you'll also have to move up and back down between generations.
function assignnames(checkboxelement){
checkboxelement.setAttribute("name", "checkbox");
var value1box = checkboxelement
.parentElement // up a generation the checkbox' parent <td>
.nextElementSibling // then to the next <td> in the row
.firstElementChild; // and back down a generation to the next input
// the last step could also be: .querySelector('input')
value1box.setAttribute("name", "notnull");
var value2box = value1box
.parentElement
.nextElementSibling
.firstElementChild;
value2box.setAttribute("name", "notnull");
alert("done");
}
<table border="1">
<tr>
<th>
Checkbox
</th>
<th>
value1
</th>
<th>
value2
</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="assignnames(this)" id="checkbox1"/>
</td>
<td>
<input type="text" name="" id="fname1">
</td>
<td>
<input type="text" name="" id="lname1">
</td>
</tr>
</table>

Increment the id of html field [duplicate]

I have this table with some dependents information and there is a add and delete button for each row to add/delete additional dependents. When I click "add" button, a new row gets added to the table, but when I click the "delete" button, it deletes the header row first and then on subsequent clicking, it deletes the corresponding row.
Here is what I have:
Javascript code
function deleteRow(row){
var d = row.parentNode.parentNode.rowIndex;
document.getElementById('dsTable').deleteRow(d);
}
HTML code
<table id = 'dsTable' >
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
</table>
JavaScript with a few modifications:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
And the HTML with a little difference:
<table id="dsTable">
<tbody>
<tr>
<td>Relationship Type</td>
<td>Date of Birth</td>
<td>Gender</td>
</tr>
<tr>
<td>Spouse</td>
<td>1980-22-03</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>Child</td>
<td>2008-23-06</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
jQuery has a nice function for removing elements from the DOM.
The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."
$(this).closest("tr").remove();
Each delete button could run that very succinct code with a function call.
Lots of good answers, but here is one more ;)
You can add handler for the click to the table
<table id = 'dsTable' onclick="tableclick(event)">
And then just find out what the target of the event was
function tableclick(e) {
if(!e)
e = window.event;
if(e.target.value == "Delete")
deleteRow( e.target.parentNode.parentNode.rowIndex );
}
Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:
document.getElementById('dsTable').addEventListener('click',tableclick,false);
​​
Here is working code: http://jsfiddle.net/hX4f4/2/
I would try formatting your table correctly first off like so:
I cannot help but thinking that formatting the table could at the very least not do any harm.
<table>
<thead>
<th>Header1</th>
......
</thead>
<tbody>
<tr><td>Content1</td>....</tr>
......
</tbody>
</table>
Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example:
http://jsfiddle.net/p9dey/1/
Use the following code to delete the particular row of table
<td>
<asp:ImageButton ID="imgDeleteAction" runat="server" ImageUrl="~/Images/trash.png" OnClientClick="DeleteRow(this);return false;"/>
</td>
function DeleteRow(element) {
document.getElementById("tableID").deleteRow(element.parentNode.parentNode.rowIndex);
}
try this for insert
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
and this for delete
document.getElementById("myTable").deleteRow(0);
Yeah It is working great
but i have to delete from localstorage too, when user click button , here is my code
function RemoveRow(id) {
// event.target will be the input element.
// console.log(id)
let td1 = event.target.parentNode;
let tr1 = td1.parentNode;
tr1.parentNode.removeChild(tr1);// the row to be removed
// const books = JSON.parse(localStorage.getItem("books"));
// const newBooks= books.filter(book=> book.id !== books.id);
// console.log(books, newBooks)
// localStorage.setItem("books", JSON.stringify(newBooks));
}
// function RemoveRow(btn) {
// var row = btn.parentNode.parentNode;
// row.parentNode.removeChild(row);
// }
button tag
class Display {
add(book) {
console.log('Adding to UI');
let tableBody = document.getElementById('tableBody')
let uiString = `<tr class="tableBody" id="tableBody" data-id="${book.id}">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow(this)"></td>
</tr>`;
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem("books"));
// console.log(books);
if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
localStorage.setItem("books", JSON.stringify(books));
}
Hi I would do something like this:
var id = 4; // inital number of rows plus one
function addRow(){
// add a new tr with id
// increment id;
}
function deleteRow(id){
$("#" + id).remove();
}
and i would have a table like this:
<table id = 'dsTable' >
<tr id=1>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr id=2>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)" </td>
</tr>
<tr id=3>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
</tr>
</table>
Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)

How to change the inputs' onchange event by name or id?

I have a snippet of HTML which is the simple version of my site. The inputs name is related to the row index. So, I am wondering how to change the inputs' onchange event using the jQuery?
For each row, it has its own function related to the row index. For example, for tr index = 0, it has the function Test1(), for tr index = 1, it has the function Test2()...
Cannot simply using the input selector, because there are some other inputs in the page. Only the id and name for the input are unique.
<tr stampId = '1001' index = '0'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#0#1" id="QuickOrderQty#6#0#1" ct="Field" onchange=" SaveControlState(event,'Text');">
</span>
</td>
</tr>
<tr stampId = '1001' index = '1'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#1#1" id="QuickOrderQty#6#1#1" ct="Field" onchange=" SaveControlState(event,'Text');">
</span>
</td>
</tr>
<tr stampId = '1001' index = '2'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#2#1" id="QuickOrderQty#6#2#1" ct="Field" onchange=" SaveControlState(event,'Text');">
</span>
</td>
</tr>
<tr stampId = '1001' index = '3'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#3#1" id="QuickOrderQty#6#3#1" ct="Field" onchange=" SaveControlState(event,'Text');">
</span>
</td>
</tr>
Well, maybe I should put my desired result here.
<script>Do something here, then change the onchange events to below.</script>
<tr stampId = '1001' index = '0'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#0#1" id="QuickOrderQty#6#0#1" ct="Field" onchange="Test1();">
</span>
</td>
</tr>
<tr stampId = '1001' index = '1'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#1#1" id="QuickOrderQty#6#1#1" ct="Field" onchange="Test2();">
</span>
</td>
</tr>
<tr stampId = '1001' index = '2'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#2#1" id="QuickOrderQty#6#2#1" ct="Field" onchange="Test3();">
</span>
</td>
</tr>
<tr stampId = '1001' index = '3'>
<td>
<span>
<input type="text" name="QuickOrderQty#6#3#1" id="QuickOrderQty#6#3#1" ct="Field" onchange="Test4();">
</span>
</td>
</tr>
Sorry if any mistakes occurred. This is my first time answering questions. I am not even that experienced.
if I understood you correctly, you want to know the element that caused the event to trigger. You can use the word this
$("input").change(function(event) {
var x = $(this).val();
// x = the value of the input element that triggered the event.
});
I hope this helps.
If you're using jQuery, you shouldnt be using inline onchange event handlers. Also, if you wish to target multiple elements with the same behaviour use a shared class. If you do both those things this becomes trivial using jQuery's index() method:
var functions = {
Test1: function(){ console.log("TextBox1 changed") },
Test2: function(){ console.log("TextBox2 changed") },
Test3: function(){ console.log("TextBox3 changed") },
Test4: function(){ console.log("TextBox4 changed") }
}
$(document).on('change','.myClass',function(){
var index = $(this).index();
functions["Test" + index]();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="myClass">
<input type="text" class="myClass">
<input type="text" class="myClass">
<input type="text" class="myClass">

How to return false and show alert IF another checkbox hasn't been selected

I'm completely new to JavaScript and I'm completely stumped as to how to start this (better explanation beneath the code).
<form>
<div id="NECESSARY">
<table id="Table1">
<tr>
<td class="name">necessary-a</td>
<td class="button">
<input type="radio" name="necessary" value="uniquename1" /></td>
</tr>
<tr>
<td class="name">necessary-b</td>
<td class="button">
<input type="radio" name="necessary" value="uniquename2" /></td>
</tr>
</table>
</div>
<div id="group2">
<table id="Table2">
<tr>
<td class="name">group2-a</td>
<td class="button">
<input type="checkbox" name="group2" value="uniquename3" /></td>
</tr>
<tr>
<td class="name">group2-b</td>
<td class="button">
<input type="checkbox" name="group2" value="uniquename4" /></td>
</tr>
</table>
</div>
<div id="group3">
<table id="Table3">
<tr>
<td class="name">group3-a</td>
<td class="button">
<input type="radio" name="group3" value="uniquename5" /></td>
</tr>
<tr>
<td class="name">group3-b</td>
<td class="button">
<input type="radio" name="group3" value="uniquename6" /></td>
</tr>
</table>
</div>
<div id="canbeselectedwhenever">
<table id="whenever">
<tr>
<td class="name">whenever-a</td>
<td class="button">
<input type="checkbox" name="whenever" value="uniquename7" /></td>
</tr>
<tr>
<td class="name">whenever-b</td>
<td class="button">
<input type="checkbox" name="whenever" value="uniquename8" /></td>
</tr>
</table>
</div>
</form>
so if a checkbox/radio button from group1 or group2 is selected before an input from NECESSARY, the checkbox/radio button won't be selected, and will show an alert on the screen. however, an input from "whenever" can be selected without requiring an input from "necessary" to be selected.
sorry for the question, but I'm really incredibly appreciative of any help that can be given.
thank you :)
I made a fiddle.
FIDDLE
Find .addEventListener info.
Javascript Code:
// get all the input elements
var inputs = document.getElementsByTagName("input");
var temp = []; // holds the radio/checkboxes
var necessary = []; // holds the necessary elements
for(var i = 0; i < inputs.length; i++){
if(inputs[i].name !== "necessary")
temp.push(inputs[i]);
else
necessary.push(inputs[i]);
}
inputs = temp.slice(0); // get a copy of the temp array and store in inputs
for(var i = 0;i < inputs.length; i++){
// add an event listener which fires the `mouseDown` on 'click'
if(inputs[i].name !== "whenever") // `whenever` elements do not undergo checks
inputs[i].addEventListener("click", mouseDown, false);
}
function mouseDown(checkbox){
var any_checked = false; // is any radio button checked ?
for(var i = 0; i < necessary.length; i++){
if(necessary[i].checked){ // if any is checked
any_checked = true; // any radio is checked = true
break; // come out of loop
}
}
if(! any_checked){ /// if nothing is checked
alert("You left all fields blank."); // alert user
for(var i = 0; i < inputs.length; i++){
inputs[i].checked = false; // make the checked property false.
}
}
}
Hope that helps!
I think it's a very basic javascript question or so it sounds. You need to add onClick event handler to the element on selection of which you want to check that if condition. Then you need to learn how to read the value of an element (hint document.getElementById(id)) and I guess thats all. Google onclick, checkbox value and other terms or read w3schools.com

redirect to another page after selecting radiobutton in mvc3

I have search box and add and edit buttons in one page.i have to edit a detail after selecting radiobutton.The script for selecting radiobutton and redirecting to next page is given below.But only alert to 'Select resume' only works.rest of code is not working.Pls help
<script type="text/javascript">
$(document).ready(function () {
var which_button;
var rad;
$('input[type="image"]').click(function (event) {
process_form_submission(event);
if (which_button == "Edit") {
if (!$("input[name='rdoUserId']:checked").val()) {
alert('Select a Resume!');
return false;
}
else {
rad = $("input[name='rdoUserId']:checked").val();
var url = "Edit/" + rad;
$('#frmIndexResume').attr("action", url);
$('#frmIndexResume').submit();
}
}
return false;
})
function process_form_submission(event) {
event.preventDefault();
//var target = $(event.target);
var input = $(event.currentTarget);
which_button = event.currentTarget.value;
}
});
</script>
<form name="frmIndexResume" method="get"action="">
<table id="tblSearch">
<tr>
<td>Name:#Html.TextBox("Names")</td>
<td>From:#Html.TextBox("FromDate")</td>
<td>To:#Html.TextBox("ToDate")</td>
<td><input type="image" value="Search" src="#Url.Content("~/images/Search.png")" width="60px"height="40px" alt="Search"/></td>
</tr>
</table>
<table id="Createbtn">
<tr>
<td>
<a href="#Url.Action("Create", "Resume")" title="Create">
<img src="#Url.Content("~/images/Create.png")" width="40px" height="30px"alt="Create"/></a>
</td>
<td>
<input type="image" value="Edit" src="#Url.Content("~/images/Edit.png")" width="40px" height="30px" alt="Edit"/>
</td>
</tr>
</table>
<table id="tblResume">
<caption>Listings</caption>
<tr>
<th>Select</th>
<th>
Name
</th>
<th>
DOB
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<input type="radio" value="#item.Id" name="rdoUserId" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
</tr>
}
</table>
</form>
You have the radio button in a loop causing there to be duplicates of the radio button.
#foreach (var item in Model)
{
...
<input type="radio" value="#item.Id" name="rdoUserId" />
...
}
The 'name' attribute is not a unique identifier. My guess is the jQuery is picking either the last or first radio button in the form since there is more than one of them.
There may be more issues besides this with the form also.
Maybe window.location is what you are looking for.
You can easily redirect via:
window.location = url;
or via:
window.navigate(url);
Please note that the second approach maybe ie-specific.

Categories